Can you answer these JavaScript Questions?

chitaranjan biswal
2 min readFeb 18, 2024
Photo by Ashkan Forouzani on Unsplash

JavaScript has some tricky parts that can puzzle developers. In this article, we’ll explore a few of these puzzles.

1.Why [3,8,8,9][1,2,3,4,1] = 8?

In JavaScript, when you use an array as an index to access elements of another array, only the last value of the array index is considered. Therefore, [1,2,3,4,1] is essentially treated as 1 in this case.
So [3,8,8,9][1,2,3,4,1] would be equivalent to [3,8,8,9][1], which indeed returns 8, because 8 is the element at index 1 of the array [3,8,8,9].

let result=[3,8,8,9][1,2,3,4,1] ;
console.log(result) //output 8

2. Adding an Array and an Object:

// Adding an Array and an Object
console.log([] + {});
// Output: "[object Object]"

When you use the + operator with arrays and objects in JavaScript, it performs type coercion to convert both operands to strings and then concatenates them .An empty array [] converts to an empty string "".An empty object {} converts to the string "[object Object]".Therefore, the concatenation of an empty string with "[object Object]" results in "[object Object]".So, the code logs "[object Object]" to the console.

3. The Type of NaN:

// The Type of NaN
console.log(typeof NaN);
// Output: "number"

NaN (Not-a-Number) is a special value in JavaScript representing an invalid mathematical operation. Despite its name, typeof NaN returns "number" because NaN is considered a numeric data type. This behavior may seem unexpected, but it's consistent with JavaScript's type system.

4. Does 0.1 + 0.2 Truly Equal 0.3?:

// Precision in Floating-Point Arithmetic
console.log(0.1 + 0.2 === 0.3);
// Output: false

Floating-point arithmetic in JavaScript, governed by the IEEE 754 standard, can sometimes lead to precision errors due to the limitations of representing decimal fractions in binary. In this case, adding 0.1 and 0.2 does not precisely equal 0.3 due to rounding errors inherent in floating-point arithmetic. This question force us to know the importance of understanding how floating-point numbers work in JavaScript and being mindful of precision errors.

5. console.log(typeof []):

// The Type of an Empty Array
console.log(typeof []);
// Output: "object"

Even though arrays have their own special features in JavaScript, like having a length and special functions, when we ask JavaScript what type an empty array is, it tells us it’s an object. This shows us that arrays are a type of object in JavaScript.

--

--