Hereβs a list of 100 JavaScript output-based interview questions along with detailed explanations of each, helping you grasp the key concepts easily.
console.log(typeof null);Output: "object"
Explanation: In JavaScript, null is considered to be an object for legacy reasons. It's a bug in the language but can't be fixed due to backward compatibility.
console.log(1 + "2" + "2");Output: "122"
Explanation: JavaScript uses type coercion. Here, 1 is a number, '2' is a string. The number 1 is coerced into a string, resulting in concatenation: '1' + '2' + '2' = "122".
console.log("1" - 1);Output: 0
Explanation: When using the - operator, JavaScript converts the string '1' into a number and performs the subtraction, resulting in 0.
console.log(true + false);Output: 1
Explanation: In JavaScript, true is coerced to 1 and false to 0. Hence, 1 + 0 = 1.
console.log(3 > 2 > 1);Output: false
Explanation: 3 > 2 evaluates to true. Then, true > 1 is evaluated as 1 > 1, which is false.
console.log([] + []);Output: "" (empty string)
Explanation: When you use + with arrays, JavaScript converts them to strings. Since both are empty arrays, you get an empty string.
console.log([] + {});
console.log({} + []);Output:
- First:
"[object Object]" - Second:
0
Explanation:
[] + {}: Array gets converted to an empty string, and object gets converted to'[object Object]', so the result is"[object Object]".{}is interpreted as a block, and+[]results in0.
console.log(1 + +"2");Output: 3
Explanation: The unary + operator before '2' converts it to a number, so it's equivalent to 1 + 2 = 3.
let a = [1, 2, 3];
a[10] = 99;
console.log(a.length);Output: 11
Explanation: Setting a value at index 10 means the arrayβs length becomes 11, even though there are empty slots between index 3 and 9.
console.log(null == undefined);Output: true
Explanation: null and undefined are loosely equal but not strictly equal (===).
console.log(!!null);
console.log(!!"");
console.log(!!1);Output:
falsefalsetrue
Explanation: The !! converts a value to its boolean equivalent. null and "" are falsy, while 1 is truthy.
console.log(typeof NaN);Output: "number"
Explanation: NaN stands for "Not-a-Number", but it is still of type "number" in JavaScript.
let a = 1;
let b = 2;
console.log((a = b));Output: 2
Explanation: The expression a = b assigns the value of b to a, and the result of the assignment is the value assigned, which is 2.
console.log([] == []);
console.log({} == {});Output:
falsefalse
Explanation: Arrays and objects are compared by reference, not by value. Two different arrays or objects are never equal, even if they have the same contents.
let a = [1, 2, 3];
let b = a;
b.push(4);
console.log(a);Output: [1, 2, 3, 4]
Explanation: b is a reference to the same array as a, so pushing to b also affects a.
console.log([] == ![]);Output: true
Explanation: The ![] converts the empty array to false. Then, [] == false becomes true because of type coercion ([] is falsy).
console.log(typeof function () {});Output: "function"
Explanation: Functions in JavaScript are of the type "function".
let a = [1, 2, 3];
delete a[1];
console.log(a);
console.log(a.length);Output:
[1, empty, 3]3
Explanation: delete removes the value but does not update the length of the array. It leaves an empty slot (undefined).
let a = 5;
console.log(a++);
console.log(++a);Output:
57
Explanation:
a++returns the current value (5), then incrementsato6.++aincrementsafirst (7), then returns it.
console.log(typeof typeof 1);Output: "string"
Explanation:
typeof 1returns"number".typeof "number"returns"string"because"number"is a string.
console.log("5" - 3);Output: 2
Explanation: The - operator forces the string "5" to be converted into a number, so 5 - 3 = 2.
console.log([1, 2] + [3, 4]);Output: "1,23,4"
Explanation: When arrays are concatenated using +, they are first converted to strings. ['1,2'] + ['3,4'] = "1,23,4".
console.log(0.1 + 0.2 == 0.3);Output: false
Explanation: Due to floating-point precision errors, 0.1 + 0.2 equals something like 0.30000000000000004, not exactly 0.3.
let a = 0;
console.log(a++);
console.log(a);Output:
01
Explanation: a++ increments the value of a but returns the previous value.
console.log([] == ![]);Output: true
Explanation: ![] evaluates to false, and [] == false is coerced to true because of JavaScript's type coercion rules.
console.log({} + {});Output: [object Object][object Object]
Explanation: When objects are concatenated, they are converted to strings, resulting in "[object Object][object Object]".
console.log(3 + "3" - "3");Output: 30
Explanation: '3' - '3' is 0, and 3 + '0' results in 30.
console.log(true == "1");Output: true
Explanation: The string '1' is coerced
into the number 1, and true is also coerced into 1, making them equal.
console.log(!!false == !!"");Output: true
Explanation: Both false and '' are falsy values. Using the !! operator converts them into false, so the result is true.
console.log([] == ![]);Output: true
Explanation: The ![] is evaluated as false, and [] == false results in true due to type coercion.
console.log([] == false);Output: false
Explanation: [] is an empty array and false is a boolean. When comparing different types, JavaScript attempts to coerce them to a common type. Here, [] is coerced to a string "" and false to "false", so they are not equal.
console.log([] == 0);Output: false
Explanation: An empty array [] is coerced to an empty string "" and then to 0 in the context of numerical comparison. However, [] coerces to false in other contexts, but not 0. Thus, [] == 0 is false.
console.log(0 == "0");
console.log(0 === "0");Output:
truefalse
Explanation:
==performs type coercion, so0is coerced to'0', making them equal.===checks for strict equality without type coercion, so0(number) and'0'(string) are not equal.
console.log([1, 2] == [1, 2]);Output: false
Explanation: In JavaScript, arrays are compared by reference, not by value. Even though the arrays have the same contents, they are different objects in memory, so they are not equal.
console.log(1 + "2" - 1);Output: 11
Explanation: 1 + '2' results in '12' due to string concatenation. Subtracting 1 from '12' coerces '12' back to a number, resulting in 11.
console.log("5" - 3);
console.log("5" * 2);
console.log("5" / 2);Output:
2102.5
Explanation:
'5' - 3converts'5'to a number, resulting in2.'5' * 2converts'5'to a number and multiplies, resulting in10.'5' / 2converts'5'to a number and divides, resulting in2.5.
console.log(0.1 + 0.2 == 0.3);
console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);Output:
falsetrue
Explanation:
0.1 + 0.2is not exactly0.3due to floating-point precision errors.Number.EPSILONis a tiny number representing the smallest interval between two representable numbers, used to check if the result is within acceptable precision.
console.log(typeof null == typeof undefined);Output: true
Explanation: Both null and undefined have the same type when using typeof, which is "object" for null (legacy bug) and "undefined" for undefined. The comparison is true for the types used in typeof.
console.log([1] == [1]);
console.log([1] === [1]);Output:
falsefalse
Explanation:
==and===compare references, not values. Different array instances even with the same contents are not equal.
console.log("a" + +"b");Output: "aNaN"
Explanation: + 'b' attempts to coerce 'b' to a number, resulting in NaN. Concatenating 'a' with NaN results in 'aNaN'.
console.log("true" == true);
console.log("true" === true);Output:
falsefalse
Explanation:
==performs type coercion, but'true'is a string andtrueis a boolean, so they are not equal.===checks for strict equality without type coercion.
console.log(1 + "2" + 2);Output: "122"
Explanation: 1 + '2' results in '12', and '12' + 2 results in '122' because 2 is coerced to a string.
console.log([] + {});
console.log({} + []);Output:
"[object Object]"0
Explanation:
[] + {}: Array[]is converted to an empty string"", and{}is converted to[object Object].{}is interpreted as a block statement, so{} + []is equivalent to0 + []which results in0.
console.log(1 + "1" - 1);Output: 10
Explanation: 1 + '1' results in '11'. Subtracting 1 from '11' coerces it back to a number, resulting in 10.
console.log([1] + [2]);
console.log([1] + 2);
console.log(2 + [1]);Output:
"12""12""21"
Explanation:
- Arrays are converted to strings when used with
+, so[1] + [2]becomes"1" + "2". [1] + 2is"1" + "2".2 + [1]is2 + "1"which results in"21".
console.log(+"1" === 1);Output: true
Explanation: + '1' converts the string '1' to the number 1, which is strictly equal to 1.
console.log(0 == "0");
console.log(0 === "0");
console.log(0 == []);Output:
truefalsefalse
Explanation:
==performs type coercion, converting'0'to0.===checks for strict equality.[]coerces tofalse, so0 == []isfalse.
console.log([2] == [2]);
console.log([2] === [2]);
console.log({} == {});Output:
falsefalsefalse
Explanation: Arrays and objects are compared by reference. Different instances with the same content are not equal.
console.log("1" - -"1");Output: 2
Explanation: '1' - - '1' is equivalent to 1 - (-1), which equals 2.
console.log("foo" + +"bar");Output: "fooNaN"
Explanation: +'bar' attempts to convert 'bar' to a number, resulting in NaN. Concatenating 'foo' with NaN results in 'fooNaN'.
console.log(null + 1);
console.log(null - 1);
console.log(null * 1);
console.log(null / 1);Output:
1-100
Explanation:
nullis coerced to0in numerical operations, except for addition wherenull + 1results in1.
console.log(0.1 + 0.2 == 0.3);
console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);Output:
- `false
`
true
Explanation:
- Floating-point arithmetic may not be precise.
Number.EPSILONis used to check if two numbers are close enough to be considered equal.
console.log([1] + [2] + 3);Output: "123"
Explanation: [1] + [2] results in '12', and '12' + 3 results in '123'.
console.log(+true);
console.log(+false);
console.log(-true);
console.log(-false);Output:
10-1-0
Explanation: +true and +false convert to 1 and 0, respectively. -true and -false convert to -1 and -0.
console.log("" + 0);
console.log(0 + "");
console.log("" - 0);
console.log(0 - "");Output:
"0""0"00
Explanation:
'' + 0and0 + ''result in'0'due to string concatenation.'' - 0results in0due to type coercion to numbers.
console.log([] + {});Output: "[object Object]"
Explanation: [] coerces to an empty string "", and {} coerces to [object Object], so the result is "[object Object]".
console.log({} + []);Output: 0
Explanation: {} is treated as an empty block, so {} + [] is equivalent to 0 + [], resulting in 0.
console.log(!!null);
console.log(!!undefined);
console.log(!!NaN);
console.log(!!0);Output:
falsefalsefalsefalse
Explanation: All these values are falsy, so !! converts them to false.
console.log([] == ![]);
console.log([] === ![]);Output:
truefalse
Explanation: ![] is false, and [] == false evaluates to true due to type coercion. [] === ![] is false because they are different types.
console.log("a" + +"b" + "c");Output: "aNaNc"
Explanation: + 'b' coerces 'b' to NaN, so 'a' + NaN is 'aNaN', and 'aNaN' + 'c' is 'aNaNc'.
console.log("1" == 1);
console.log("1" === 1);
console.log("1" != 1);
console.log("1" !== 1);Output:
truefalsefalsetrue
Explanation:
==performs type coercion, while===does not.'1' == 1istruedue to coercion.'1' === 1isfalsedue to strict equality.
console.log("1" + 1);
console.log("1" - 1);
console.log(1 + "1");
console.log(1 - "1");Output:
"11"0"11"0
Explanation:
'1' + 1and1 + '1'result in string concatenation.'1' - 1and1 - '1'result in numeric operations.
console.log([2] == [2]);
console.log([2] === [2]);
console.log({} == {});Output:
falsefalsefalse
Explanation:
- Arrays and objects are compared by reference, so different instances are not equal.
console.log([] == ![]);
console.log([] === ![]);Output:
truefalse
Explanation:
![]evaluates tofalse, and[] == falseistruedue to type coercion.[] === ![]isfalseas[]andfalseare different types.
console.log("5" - 3);
console.log("5" * 2);
console.log("5" / 2);Output:
2102.5
Explanation:
-converts'5'to a number before subtraction.*and/also coerce'5'to a number.
console.log(0.1 + 0.2 === 0.3);Output: false
Explanation: Due to floating-point precision issues, 0.1 + 0.2 does not exactly equal 0.3.
console.log(typeof NaN);
console.log(typeof Infinity);
console.log(typeof -Infinity);Output:
"number""number""number"
Explanation: NaN and Infinity are both of type number in JavaScript.
console.log(!!(1 + 1));
console.log(!!(0 + 1));
console.log(!!(0 - 1));
console.log(!!0);Output:
truetruetruefalse
Explanation:
!!converts truthy values totrueand falsy values tofalse.
console.log("1" + 1);
console.log(1 + "1");
console.log(1 - "1");Output:
"11""11"0
Explanation:
+with a string converts numbers to strings for concatenation.-converts the string to a number before performing subtraction.
console.log([] == ![]);
console.log([] === ![]);Output:
truefalse
Explanation:
![]converts tofalse, so[] == falseistruedue to type coercion.[] === ![]isfalseas they are different types.
console.log({} + []);
console.log([] + {});Output:
0"[object Object]"
Explanation:
{}is treated as a block, so{} + []results in0 + [].[] + {}results in an empty string concatenated with the string representation of the object.
console.log(+"1" + 1);
console.log(+"1" - 1);
console.log(+"1" * 2);
console.log(+"1" / 2);Output:
2020.5
Explanation: + '1' converts '1' to the number 1. The subsequent operations use this number.
console.log([1] == [1]);
console.log([1] === [1]);
console.log([] == false);
console.log([] === false);Output:
falsefalsefalsefalse
Explanation:
- Arrays and objects are compared by reference. Different instances with the same content are not equal.
[]coerces tofalsein comparisons, but strict equality===isfalsefor different types.
console.log(1 + "1" - 1);
console.log(1 - "1" + 1);Output:
101
Explanation:
1 + '1'results in'11',
and subtracting 1 coerces it back to 10.
1 - '1'results in0, adding1results in1.
console.log(!!undefined);
console.log(!!NaN);
console.log(!!0);
console.log(!!"");Output:
falsefalsefalsefalse
Explanation: All these values are falsy, so !! converts them to false.
console.log(typeof (1 + "1"));
console.log(typeof (1 - "1"));
console.log(typeof (1 * "1"));
console.log(typeof (1 / "1"));Output:
"string""number""number""number"
Explanation:
1 + '1'results in a string.1 - '1',1 * '1', and1 / '1'result in numbers.
console.log([2] == [2]);
console.log([2] === [2]);
console.log({} == {});
console.log({} === {});Output:
falsefalsefalsefalse
Explanation: Arrays and objects are compared by reference, so different instances are not equal.
console.log(!!"false");
console.log(!!false);
console.log(!!"0");
console.log(!!0);Output:
truefalsetruefalse
Explanation: Non-empty strings and false are falsy, while empty strings and 0 are falsy.
console.log([] + {} + []);Output: "[object Object]"
Explanation: [] coerces to an empty string, {} to [object Object], and the final result is [object Object].
console.log(+[] + 1);
console.log(+{} + 1);
console.log(+null + 1);Output:
1NaN1
Explanation:
+[]is0, so0 + 1is1.+{}isNaNbecause{}cannot be coerced to a number.+nullis0, so0 + 1is1.
console.log([] == false);
console.log([] === false);
console.log(false == []);
console.log(false === []);Output:
falsefalsefalsefalse
Explanation:
[]is not strictly equal tofalseor equal tofalsewith type coercion.
console.log([1] + 1);
console.log([1] - 1);
console.log(1 + [1]);
console.log(1 - [1]);Output:
"11"0"11"0
Explanation:
+with a string converts numbers to strings for concatenation.-converts the array to a number for subtraction.
console.log(!!" " === !!"");
console.log(!!"0" === !!0);Output:
falsetrue
Explanation:
' 'is a non-empty string and''is an empty string.'0'and0both convert totruewhen using!!.
console.log(1 + [1] + 1);
console.log([1] + 1 + 1);Output:
"111""111"
Explanation: Both expressions result in concatenation of "1" strings.
console.log(1 + "1" + 1);
console.log(1 + 1 + "1");Output:
"111""21"
Explanation:
1 + '1'results in'11', and adding1results in'111'.1 + 1results in2, and adding'1'results in'21'.
console.log(+[] + 1);
console.log(+{} + 1);
console.log(+null + 1);Output:
1NaN1
Explanation:
+[]is0, so0 + 1is1.+{}isNaNbecause{}cannot be coerced to a number.+nullis0, so0 + 1is1.
console.log([] == false);
console.log([] === false);
console.log(false == []);
console.log(false === []);Output:
falsefalsefalsefalse
Explanation: Arrays and booleans are different types, so neither == nor === will be true.
console.log("1" - -"1");
console.log("1" + -"1");Output:
2'0'
Explanation:
'1' - - '1'is equivalent to1 - (-1), which is2.'1' + - '1'is'1' + -1, resulting in'0'.
console.log([] == ![]);
console.log([] === ![]);Output:
truefalse
Explanation:
![]evaluates tofalse, and[] == falseistruedue to type coercion.[] === ![]isfalsebecause they are different types.
console.log([] + {} + []);
console.log([{}] + []);Output:
"[object Object]""[object Object]"
Explanation:
[]coerces to an empty string"",{}to[object Object].[{}] + []results in[object Object].
console.log([1] == 1);
console.log([1] === 1);
console.log([1] == [1]);
console.log([1] === [1]);Output:
falsefalsefalsefalse
Explanation:
- Arrays are compared by reference, so different instances are not equal.
console.log([] + []);
console.log([] - []);Output:
""NaN
Explanation:
[] + []results in an empty string.[] - []results inNaNdue to the subtraction operation with arrays.
console.log(0 == "0");
console.log(0 === "0");
console.log("0" == 0);
console.log("0" === 0);Output:
truefalsetruefalse
Explanation:
==performs type coercion, so0 == '0'istrue.===checks for strict equality.
console.log("1" == 1);
console.log("1" === 1);
console.log("1" != 1);
console.log("1" !== 1);Output:
truefalsefalsetrue
Explanation:
==coerces types, while===does not.
console.log([1, 2] == [1, 2]);
console.log([1, 2] === [1, 2]);Output:
falsefalse
Explanation: Arrays are compared by reference, so different instances are not equal.
console.log(null == undefined);
console.log(null === undefined);
console.log(null == 0);
console.log(undefined == 0);Output:
truefalsefalsefalse
Explanation:
nullandundefinedare loosely equal but not strictly equal.nullandundefinedare not equal to0.
console.log("5" - 3);
console.log("5" * 2);
console.log("5" / 2);Output:
2102.5
Explanation:
-converts'5'to a number for subtraction.*and/also coerce'5'to a number for operations.
console.log([] == ![]);
console.log([] === ![]);Output:
truefalse
Explanation:
![]evaluates tofalse, so[] == falseistrue.[] === ![]isfalsedue to different types.
console.log(0.1 + 0.2 === 0.3);Output: false
Explanation: Due to floating-point precision issues, 0.1 + 0.2 does not exactly equal 0.3.
console.log([] + {} + []);
console.log([{}] + []);Output:
"[object Object]""[object Object]"
Explanation:
[] + {} + []results in the empty string and object coercion to[object Object].[{}] + []results in[object Object].
-
What does this code print?
console.log([1] + [2]);
Output:
"12"Explanation: Arrays are coerced into strings and concatenated. -
What is the result of this code?
console.log([1, 2, 3].slice(1, 2));
Output:
[2]Explanation:sliceextracts elements from index 1 to 2 (exclusive). -
What will this code output?
console.log([1, 2, 3].map((x) => x * x));
Output:
[1, 4, 9]Explanation:mapapplies the function to each element. -
What does this code print?
console.log([1, 2, 3].filter((x) => x > 1));
Output:
[2, 3]Explanation:filterkeeps elements greater than 1. -
What is the result of this code?
console.log([1, 2, 3].reduce((a, b) => a + b));
Output:
6Explanation:reducesums up the elements. -
What will this code print?
console.log([1, 2, 3].concat([4, 5]));
Output:
[1, 2, 3, 4, 5]Explanation:concatmerges arrays. -
What does this code return?
console.log([1, 2, 3].includes(2));
Output:
trueExplanation:includeschecks if the element exists in the array. -
What is the output?
console.log([1, [2, [3]]].flat(2));
Output:
[1, 2, 3]Explanation:flatflattens nested arrays. -
What will this code print?
console.log([1, 2, 3].find((x) => x > 1));
Output:
2Explanation:findreturns the first element that satisfies the condition. -
What does this code return?
console.log([1, 2, 3].findIndex((x) => x === 2));
Output:
1Explanation:findIndexreturns the index of the first element that satisfies the condition.
-
What does this code print?
const obj = { a: 1, b: 2 }; console.log(Object.keys(obj));
Output:
["a", "b"]Explanation:Object.keysreturns the keys of an object. -
What is the result of this code?
const obj = { a: 1, b: 2 }; console.log(Object.values(obj));
Output:
[1, 2]Explanation:Object.valuesreturns the values of an object. -
What will this code print?
const obj = { a: 1 }; obj.a = 2; console.log(obj);
Output:
{a: 2}Explanation: The value ofais updated. -
What does this code return?
console.log({ a: 1 } instanceof Object);
Output:
trueExplanation:{a: 1}is an instance ofObject. -
What will this code print?
const obj1 = { a: 1 }; const obj2 = Object.create(obj1); console.log(obj2.a);
Output:
1Explanation:Object.createcreates an object withobj1as its prototype. -
What does this code return?
console.log({ ...{ a: 1 } });
Output:
{a: 1}Explanation: The spread operator creates a shallow copy of the object. -
What is the output?
const obj = { a: 1 }; delete obj.a; console.log(obj);
Output:
{}Explanation:deleteremoves a property from an object. -
What does this code print?
console.log({ a: 1, a: 2 });
Output:
{a: 2}Explanation: Duplicate keys in objects are overwritten. -
What will this code output?
console.log(Object.entries({ a: 1, b: 2 }));
Output:
[["a", 1], ["b", 2]]Explanation:Object.entriesreturns an array of key-value pairs. -
What does this code return?
console.log(Object.assign({}, { a: 1 }, { b: 2 }));
Output:
{a: 1, b: 2}Explanation:Object.assignmerges objects.
-
What does this code print?
function foo() { return; { bar: 1; } } console.log(foo());
Output:
undefinedExplanation: The function implicitly returnsundefinedbecause of the newline. -
What is the result of this code?
function foo(a, b) { console.log(a, b); } foo(1);
Output:
1 undefinedExplanation:bisundefinedbecause it was not provided. -
What will this code print?
const add = (a, b = 2) => a + b; console.log(add(3));
Output:
5Explanation: The default value forbis used. -
What does this code print?
function foo(a, b = () => a) { return b(); } console.log(foo(1));
Output:
1Explanation:bis a function returninga. -
What will this code return?
function add(a, ...rest) { return a + rest.reduce((acc, num) => acc + num, 0); } console.log(add(1, 2, 3, 4));
Output:
10Explanation:...restcollects remaining arguments into an array. -
What does this code print?
const obj = { a: 1 }; function bar() { console.log(this.a); } bar.call(obj);
Output:
1Explanation:callsetsthistoobj. -
What will this code output?
const obj = { a: 1 }; function bar() { console.log(this.a); } bar.bind(obj)();
Output:
1Explanation:bindsetsthispermanently. -
What does this code print?
function foo(a, b = (a = 2) => a) { return b(); } console.log(foo(1));
Output:
2Explanation: The default function parameter modifiesa. -
What is the output?
const add = (a, b) => a + b; console.log(add(2, 3));
Output:
5Explanation: Arrow function returns the sum ofaandb. -
What does this code print?
const multiply = (a, b = 1) => a * b; console.log(multiply(5));
Output:
5Explanation: Default value forbis used.
- What does this code print?
Output:
function foo() { console.log("foo"); } function bar() { foo(); } bar();
fooExplanation:barcallsfoo, which printsfoo.
32
. What will this code output?
js function baz() { console.log('baz'); foo(); } function foo() { console.log('foo'); } baz();
Output:
baz foo
Explanation: baz prints baz, then calls foo.
-
What does this code print?
function a() { b(); } function b() { console.log("b"); } a();
Output:
bExplanation:acallsb, which printsb. -
What will this code output?
function one() { setTimeout(() => console.log("one"), 0); } function two() { console.log("two"); } one(); two();
Output:
two oneExplanation:
twoprints first, thensetTimeoutexecutes. -
What does this code print?
function foo() { console.log("foo"); } function bar() { console.log("bar"); } foo(); bar();
Output:
foo barExplanation:
fooandbarare called sequentially. -
What will this code output?
function foo() { bar(); console.log("foo"); } function bar() { console.log("bar"); } foo();
Output:
bar fooExplanation:
foocallsbar, then printsfoo. -
What does this code print?
function a() { console.log("a"); } function b() { console.log("b"); a(); } b();
Output:
b aExplanation:
bprintsb, then callsa. -
What will this code output?
function foo() { bar(); } function bar() { console.log("bar"); } foo();
Output:
barExplanation:foocallsbar. -
What does this code print?
function foo() { console.log("foo"); setTimeout(() => console.log("foo timeout"), 0); } foo();
Output:
foo foo timeoutExplanation:
setTimeoutexecutes after the stack is clear. -
What will this code print?
function foo() { console.log("foo"); bar(); } function bar() { console.log("bar"); } foo();
Output:
foo barExplanation:
fooprintsfoo, then callsbar.
-
What does this code print?
new Promise((resolve) => resolve("done")).then((result) => console.log(result) );
Output:
doneExplanation:resolvetriggers thethencallback. -
What is the result of this code?
new Promise((resolve, reject) => reject("error")).catch((err) => console.log(err) );
Output:
errorExplanation:catchhandles rejected promises. -
What will this code output?
const promise = new Promise((resolve) => resolve(1)); promise.then((x) => x + 1).then((x) => console.log(x));
Output:
2Explanation: Chained promises processxsequentially. -
What does this code print?
new Promise((resolve) => setTimeout(() => resolve("done"), 1000)).then( (result) => console.log(result) );
Output:
done(after 1 second) Explanation:setTimeoutdelays the promise resolution. -
What will this code output?
const promise = Promise.resolve("resolved"); promise.then(console.log).catch(console.error);
Output:
resolvedExplanation:Promise.resolveimmediately resolves. -
What does this code print?
new Promise((resolve, reject) => resolve("done")) .then(() => { throw new Error("error"); }) .catch((err) => console.log(err.message));
Output:
errorExplanation: Error thrown in thethenis caught bycatch. -
What will this code output?
Promise.all([Promise.resolve(1), Promise.resolve(2)]).then((results) => console.log(results) );
Output:
[1, 2]Explanation:Promise.allresolves when all promises resolve. -
What does this code print?
Promise.race([ Promise.resolve(1), new Promise((resolve) => setTimeout(() => resolve(2), 1000)), ]).then((result) => console.log(result));
Output:
1Explanation:Promise.racereturns the result of the first resolved promise. -
What will this code output?
const promise = new Promise((resolve, reject) => { setTimeout(() => resolve("done"), 500); setTimeout(() => reject("error"), 100); }); promise.then(console.log).catch(console.error);
Output:
errorExplanation: The firstsetTimeoutrejects the promise before the second resolves. -
What does this code print?
const p1 = new Promise((resolve, reject) => setTimeout(resolve, 1000)); const p2 = new Promise((resolve, reject) => setTimeout(resolve, 2000)); Promise.all([p1, p2]).then(() => console.log("done"));
Output:
done(after 2 seconds) Explanation:Promise.allwaits for all promises to resolve.
-
What does this code print?
async function foo() { return 1; } foo().then(console.log);
Output:
1Explanation:asyncfunctions return a promise with the resolved value. -
What is the result of this code?
async function foo() { return Promise.resolve(2); } foo().then(console.log);
Output:
2Explanation: The returned promise resolves to2. -
What will this code output?
async function foo() { throw new Error("error"); } foo().catch(console.error);
Output:
Error: errorExplanation: Errors inasyncfunctions are caught incatch. -
What does this code print?
async function foo() { await new Promise((resolve) => setTimeout(() => resolve("done"), 1000)); console.log("foo"); } foo();
Output:
foo(after 1 second) Explanation:awaitwaits for the promise to resolve before printing. -
What will this code output?
async function foo() { const result = await Promise.all([ new Promise((resolve) => setTimeout(() => resolve("a"), 100)), new Promise((resolve) => setTimeout(() => resolve("b"), 200)), ]); console.log(result); } foo();
Output:
['a', 'b']Explanation:Promise.allwaits for all promises to resolve. -
What does this code print?
async function foo() { console.log(await 1); } foo();
Output:
1Explanation:awaitresolves immediately for non-promise values. -
What will this code output?
async function foo() { const x = await 1; console.log(x); } foo();
Output:
1Explanation:awaitreturns the resolved value directly. -
What does this code print?
async function foo() { const x = await new Promise((resolve) => setTimeout(() => resolve("done"), 500) ); console.log(x); } foo();
Output:
done(after 0.5 seconds) Explanation:awaitwaits for the promise to resolve. -
What will this code output?
async function foo() { const x = await Promise.reject("error"); console.log(x); } foo().catch(console.error);
Output:
errorExplanation: Rejected promises are caught incatch. -
What does this code print?
async function foo() { try { const result = await new Promise((resolve, reject) => reject("error")); console.log(result); } catch (e) { console.log(e); } } foo();
Output:
errorExplanation: Errors are caught incatchblock.
-
What does this code print?
document.body.addEventListener("click", () => console.log("clicked"), true); document.body.addEventListener("click", () => console.log("clicked again")); document.body.click();
Output:
clicked clicked againExplanation: The event captures and bubbles through phases.
-
What is the result of this code?
document.addEventListener( "click", function (event) { console.log("Event at document"); }, true ); document.body.addEventListener( "click", function (event) { console.log("Event at body"); }, true ); document.body.click();
Output:
Event at document Event at bodyExplanation: The event is captured at each phase.
-
What will this code output?
document.body.addEventListener("click", () => console.log("body"), false); document.body.addEventListener( "click", () => console.log("body again"), true ); document.body.click();
Output:
body again bodyExplanation:
trueindicates capturing phase,falseis bubbling phase. -
What does this code print?
document.addEventListener( "click", function () { console.log("clicked"); }, false ); document.body.click();
Output:
clickedExplanation: The event is propagated to the document from the body. -
What will this code output?
document.body.addEventListener("click", function () { console.log("body clicked"); }); document.body.addEventListener("click", function (event) { event.stopImmediatePropagation(); console.log("immediate stop"); }); document.body.click();
Output:
immediate stopExplanation:
stopImmediatePropagationprevents further propagation. -
What does this code print?
document.body.addEventListener("click", () => console.log("body")); document.body.removeEventListener("click", () => console.log("body")); document.body.click();
Output: (Nothing) Explanation:
removeEventListenerdoes not remove the listener due to a different function reference. -
What will this code output?
document.body.addEventListener("click", function () { console.log("event handler"); }); document.body.dispatchEvent(new Event("click"));
Output:
event handlerExplanation:dispatchEventtriggers the event handler. -
What does this code print?
document.body.addEventListener( "click", function () { console.log("event fired"); }, true ); document.body.click();
Output:
event firedExplanation: Capturing phase is used, so the event is caught. -
What will this code output?
const handler = () => console.log("handler"); document.body.addEventListener("click", handler); document.body.removeEventListener("click", handler); document.body.click();
Output: (Nothing) Explanation: Event handler is removed before being called.
-
What does this code print?
document.addEventListener( "click", function (event) { event.stopPropagation(); console.log("stop propagation"); }, true ); document.body.addEventListener("click", function () { console.log("body click"); }); document.body.click();
Output:
stop propagationExplanation:
stopPropagationprevents bubbling.
-
What does this code print?
document.body.innerHTML = '<div id="test">Test</div>'; console.log(document.getElementById("test").innerText);
Output:
TestExplanation:innerTextreturns the content of the element. -
What is the result of this code?
const div = document.createElement("div"); div.setAttribute("class", "my-class"); console.log(div.className);
Output:
my-classExplanation:classNamereturns the class attribute. -
What will this code output?
document.body.innerHTML = '<p id="para">Hello</p>'; const p = document.getElementById("para"); p.textContent = "World"; console.log(p.innerHTML);
Output:
WorldExplanation:textContentupdates the text inside the element. -
What does this code print?
document.body.innerHTML = '<button id="btn">Click me</button>'; const button = document.getElementById("btn"); button.onclick = () => console.log("Button clicked"); button.click();
Output:
Button clickedExplanation:onclicktriggers the event handler. -
What will this code output?
const div = document.createElement("div"); div.style.color = "red"; document.body.appendChild(div); console.log(getComputedStyle(div).color);
Output:
rgb(255, 0, 0)Explanation:getComputedStylereturns the computed style. -
What does this code print?
document.body.innerHTML = "<ul><li>Item 1</li><li>Item 2</li></ul>"; const items = document.querySelectorAll("li"); items.forEach((item) => console.log(item.textContent));
Output:
Item 1 Item 2Explanation:
querySelectorAllselects multiple elements. -
What will this code output?
const div = document.createElement("div"); div.textContent = "Hello World"; document.body.appendChild(div); div.remove(); console.log(document.body.contains(div));
Output:
falseExplanation:removedetaches the element from the DOM. -
What does this code print?
document.body.innerHTML = '<input type="text" id="input" value="default">'; const input = document.getElementById("input"); input.value = "changed"; console.log(input.getAttribute("value"));
Output:
defaultExplanation:getAttributereturns the initial attribute value. -
What will this code output?
document.body.innerHTML = '<div id="test"></div>'; const div = document.getElementById("test"); div.setAttribute("data-test", "value"); console.log(div.dataset.test);
Output:
valueExplanation:datasetaccessesdata-*attributes. -
What does this code print?
const p = document.createElement("p"); p.innerHTML = "<strong>Strong</strong>"; document.body.appendChild(p); console.log(p.querySelector("strong").innerHTML);
Output:
StrongExplanation:querySelectorselects nested elements.
-
What does this code print?
console.log(typeof null);
Output:
objectExplanation:nullis considered an object due to a historical bug. -
What is the result of this code?
console.log(0.1 + 0.2 === 0.3);
Output:
falseExplanation: Floating-point arithmetic can lead to precision issues. -
What will this code output?
console.log([1] == [1]);
Output:
falseExplanation: Arrays are compared by reference, not value. -
What does this code print?
console.log(1 + "1");
Output:
11Explanation:1is coerced into a string, resulting in concatenation. -
What will this code output?
console.log("5" - 2);
Output:
3Explanation: The-operator converts the string to a number. -
What does this code print?
console.log(true + 1);Output: 2
Explanation: true is coerced to 1 before addition.
-
What will this code output?
console.log([] + {});
Output:
[object Object]Explanation:[]is coerced to an empty string,{}to[object Object]. -
What does this code print?
console.log({} + []);
Output:
0Explanation:{}is interpreted as a block,[]is coerced to0. -
What will this code output?
console.log(NaN === NaN);
Output:
falseExplanation:NaNis not equal to itself. -
What does this code print?
console.log(typeof typeof 1);
Output:
stringExplanation:typeof 1isnumber,typeofof that isstring. -
What will this code output?
console.log([1, 2] + [3, 4]);
Output:
1,23,4Explanation: Arrays are converted to strings and concatenated. -
What does this code print?
console.log(1 + "2" + 3);
Output:
123Explanation: The+operator performs string concatenation when one operand is a string. -
What will this code output?
console.log(1 - "1");
Output:
0Explanation: The-operator converts the string to a number. -
What does this code print?
console.log(typeof [] === "object");
Output:
trueExplanation: Arrays are objects in JavaScript. -
What will this code output?
console.log([] == ![]);
Output:
trueExplanation:![]isfalse,[]is coerced tofalse. -
What does this code print?
console.log([1] + [2]);
Output:
12Explanation: Arrays are converted to strings and concatenated. -
What will this code output?
console.log({ a: 1 } + { b: 2 });
Output:
[object Object][object Object]Explanation: Objects are coerced to strings and concatenated. -
What does this code print?
console.log(2 + 3 + "4");
Output:
54Explanation: Addition with a string converts the entire result to a string. -
What will this code output?
console.log(0.1 + 0.2);
Output:
0.30000000000000004Explanation: Floating-point arithmetic can cause precision issues.
Hereβs an improved version of the question with a more detailed explanation for your README.md context:
- What does this code print?
console.log([] == false);Output: true
Explanation:
In JavaScript, the == operator performs type coercion, which means it tries to convert both sides to the same type before comparing them. Here's what happens step by step:
-
Array
[]is converted to a primitive:- When comparing an empty array
[]to a boolean, JavaScript tries to convert the array into a primitive value. The empty array is first converted to an empty string''.
- When comparing an empty array
-
Conversion of
[](now'') to a boolean:- After conversion, the
==comparison converts both sides to numbers.falseis converted to0, and''(empty string) is also converted to0.
- After conversion, the
-
Final Comparison:
- The comparison becomes
0 == 0, which istrue.
- The comparison becomes
This behavior stems from JavaScript's type coercion rules when using the == operator. To avoid such quirks, it's recommended to use the strict equality operator ===, which doesn't perform type coercion.
console.log([] === false); // false