Javascript Output Questions
Published: 2024-02-19 06:36:25

Q1.

```
let a = {};
let b = { key: "b" };
let c = { key: "c" };

a[b] = 123;
a[c] = 456;

console.log(a[b]);
```
The output of this code will be 456.

Because -> A js object when reads another object as key it saves it with name "object" rather than the object name. 

Q2. 

```
let obj1 = { key: "value" };
let obj2 = obj1;
let obj3 = obj2;

obj1.key = "new value";
obj2 = { key: "another value" };
```

console.log(obj1.key, obj2.key, obj3.key);
The output of this code will be `new value` `another value` `new value.

This is because when an object is assigned to a variable, the variable stores a reference to the object in memory rather than the object itself. Changing the value of a property of the object using one variable will affect the value of that property when accessed using a different variable that references the same object. However, reassigning a new object to a variable will change the reference stored in that variable, so the original object is no longer accessible using that variable.

Q3. 

```
const obj = {
  a: "foo",
  b: function () {
    console.log(this.a);
  },
};

const c = obj.b;

obj.b();
c();
```
Answer - foo, undefined

c refers to the function and not the whole object and so a remains undefined.

Q4.

```
let x = 1;

if (function f() {}) {
  x += typeof f;
}

console.log(x);
```
Answer - 1undefined
The if statement is evaluating the function f as a boolean value. In JavaScript, functions are truthy values, so the condition will evaluate to true and the code block inside the if statement will be executed. The value of x is then incremented by the string "undefined", which is the result of calling typeof f.


Q5. 

```
let x = [1, 2, 3];
let y = [1, 2, 3];
let z = y;
console.log(z === y);
console.log(x == y);
console.log(x === y);
console.log(z == y);
console.log(z == x);
```
Answer -
true false false true false

When comparing two objects with the == operator, it compares their references, not their values. In this case, x and y are different objects with the same values. z is assigned the value of y, so they refer to the same object. As a result, the first comparison returns false, the second comparison also returns false and the third comparison returns true. and the last comparison also returns false.

Q6.

```
var x = 0;
for (let i = 0; i < 5; i++) {
  setTimeout(() => {
    x++;
    console.log(x);
  }, 1000);
}
```
Answer:

1 2 3 4 5

If it was i then it would have been 5,5,5,5,5 since i is a loop variable


Q7. 

```
const arr1 = [1, 2, 3];
const arr2 = [...arr1];

arr2.push(4);

console.log(arr1);
console.log(arr2);
```
VM224:6 (3) [1, 2, 3]
VM224:7 (4) [1, 2, 3, 4]

```
const arr1 = [1, 2, 3];
const arr2 = arr1;

arr2.push(4);

console.log(arr1);
console.log(arr2);
```
VM232:6 (4) [1, 2, 3, 4]
VM232:7 (4) [1, 2, 3, 4]

So we see [...arr] creates a shallow copy whereas =arr2 keeps the reference same.


Q8. 

```
console.log(typeof 42);
console.log(typeof "Hello");
console.log(typeof true);
console.log(typeof [1, 2, 3]);
console.log(typeof { name: "John", age: 25 });
console.log(typeof null);
console.log(typeof undefined);
console.log(typeof function () {});
```

Answer:
number
string
boolean
object
object
object
undefined
function

Q. 10

```
const person = {
  name: "John",
  age: 30,
};

Object.freeze(person);
person.age = 40;

console.log(person.age);
```
A: 30
B: 40
C: TypeError
D: ReferenceError
Answer -
A: 30

In this code, the Object.freeze() method is used to make

the person object immutable. This means that the properties of the object cannot be modified.

When attempting to assign a new value to person.age after freezing the object, it does not throw an error or modify the object. Instead, it silently fails in non-strict mode and throws a TypeError in strict mode.

Since the code is not running in strict mode, the assignment person.age = 40 does not have any effect. Therefore, when console.log(person.age) is executed, it will output the original value of 30.

Hence, the output will be 30.

Q11.

```
const obj = {
  a: 1,
  b: 2,
  c: {
    a: 3,
    b: 4,
  },
};

const {
  a,
  b,
  c: { a: nestedA },
} = obj;
```
console.log(a, b, nestedA);
A: 1 2 3
B: 1 2 4
C: 3 2 1
D: SyntaxError
Answer: A: 1 2 3

This code snippet uses destructuring assignment to extract values from the obj object. It extracts the properties a, b, and the nested property a from the c object and assigns them to the corresponding variables a, b, and nestedA, respectively.

After destructuring, the variables will hold the following values:

a: 1 (value of obj.a)
b: 2 (value of obj.b)
nestedA: 3 (value of obj.c.a)
When console.log(a, b, nestedA) is executed, it will print 1 2 3, as the values of the variables match the above assignments.

Hence, the correct answer is A: 1 2 3.


 Understanding the `.sort()` Method Variations
const fruits = ["banana", "apple", "orange", "grape", "kiwi"];

// Task 1: Sort the array of fruits in alphabetical order (default behavior)
// Task 2: Sort the array of fruits in descending alphabetical order
// Task 3: Sort the array of fruits based on the length of the fruit names in ascending order
// Task 4: Sort the array of fruits in ascending order by the second character of each fruit name
Answer

Task 1: Sort in alphabetical order (default behavior)

const alphabeticalOrder = [...fruits].sort();
console.log(alphabeticalOrder); // Output: ['apple', 'banana', 'grape', 'kiwi', 'orange']
Task 2: Sort in descending alphabetical order

const descendingOrder = [...fruits].sort((a, b) => b.localeCompare(a));
console.log(descendingOrder); // Output: ['orange', 'kiwi', 'grape', 'banana', 'apple']
Task 3: Sort based on the length of the fruit names in ascending order

const sortByLength = [...fruits].sort((a, b) => a.length - b.length);
console.log(sortByLength); // Output: ['kiwi', 'apple', 'grape', 'banana', 'orange']
Task 4: Sort in ascending order by the second character of each fruit name

const sortBySecondChar = [...fruits].sort((a, b) => a[1].localeCompare(b[1]));
console.log(sortBySecondChar); // Output: ['banana', 'kiwi', 'apple', 'orange', 'grape']
Explanation:

Task 1 utilizes the default behavior of .sort() to arrange elements alphabetically.
Task 2 reverses the order by using localeCompare() with the reverse comparison.
Task 3 sorts the array by the length of the elements, ensuring ascending order.
Task 4 specifically compares the second character of each element for sorting.

``` js
let x = 1;

if (function f() {}) {
  x += typeof f;
}
```

console.log(x);
Answer - 1undefined
The if statement is evaluating the function f as a boolean value. In JavaScript, functions are truthy values, so the condition will evaluate to true and the code block inside the if statement will be executed. The value of x is then incremented by the string "undefined", which is the result of calling typeof f.


Q

``` js
const add = (a = 1, b = 2) => a + b;
console.log(add());
console.log(add(5));
console.log(add(undefined, 10));
```
Answer:

3
7
11

Q What will be the output of the following code snippet?

```
const person = {
  name: "John",
  age: 30,
};

Object.freeze(person);
person.age = 40;

console.log(person.age);
A: 30
B: 40
C: TypeError
D: ReferenceError
```
Answer -
A: 30

In this code, the Object.freeze() method is used to make

the person object immutable. This means that the properties of the object cannot be modified.

When attempting to assign a new value to person.age after freezing the object, it does not throw an error or modify the object. Instead, it silently fails in non-strict mode and throws a TypeError in strict mode.

Since the code is not running in strict mode, the assignment person.age = 40 does not have any effect. Therefore, when console.log(person.age) is executed, it will output the original value of 30.

Hence, the output will be 30.

```JS
let x = 10;

function outer() {
  console.log(x);

  if (false) {
    var x = 20;
  }
}

outer();
```
A: 10
B: 20
C: undefined
D: ReferenceError
Answer: C: undefined


Q. What will be the output of the following code snippet?
const obj = {
  a: 1,
  b: 2,
  c: {
    a: 3,
    b: 4,
  },
};

const {
  a,
  b,
  c: { a: nestedA },
} = obj;

console.log(a, b, nestedA);
A: 1 2 3
B: 1 2 4
C: 3 2 1
D: SyntaxError
Answer: A: 1 2 3

This code snippet uses destructuring assignment to extract values from the obj object. It extracts the properties a, b, and the nested property a from the c object and assigns them to the corresponding variables a, b, and nestedA, respectively.

After destructuring, the variables will hold the following values:

a: 1 (value of obj.a)
b: 2 (value of obj.b)
nestedA: 3 (value of obj.c.a)
When console.log(a, b, nestedA) is executed, it will print 1 2 3, as the values of the variables match the above assignments.

Hence, the correct answer is A: 1 2 3.