99 JavaScript Tricky Questions | Must Have
I am a MERN stack developer. Here to learn and share my knowledge to help other to grow.
Certainly! Here are 10 tricky JavaScript questions:
Variable Declaration and Initialization:
let x = 5, y = 10; console.log(x + y);What is the output, and why?
Truthy or Falsy:
console.log([] == false);What is the output, and why?
Scope and Variable Hoisting:
var a = 10; (function () { console.log(a); var a = 20; })();What is the output, and why?
Type Coercion:
console.log("5" - 2);What is the output, and why?
Closures:
for (var i = 1; i <= 5; i++) { setTimeout(function() { console.log(i); }, 1000); }What is the output, and why?
Prototype Chain:
function Person() {} Person.prototype.walk = function() { console.log("walking"); }; var john = new Person(); john.walk();What is the output, and why?
Async/Await:
async function foo() { console.log(1); await Promise.resolve(); console.log(2); } foo(); console.log(3);What is the output, and why?
thisin Arrow Functions:const obj = { value: 100, getValue: () => console.log(this.value) }; obj.getValue();What is the output, and why?
Strict Mode:
"use strict"; function strictModeExample() { undeclaredVar = 10; console.log(undeclaredVar); } strictModeExample();What is the output, and why?
Event Bubbling:
<div id="parent"> <button id="child">Click me</button> </div> <script> document.getElementById('parent').addEventListener('click', function() { console.log('Parent clicked'); }); document.getElementById('child').addEventListener('click', function(e) { console.log('Child clicked'); e.stopPropagation(); }); </script>What happens when you click the button, and why?
Certainly! Here are 20 more tricky JavaScript questions:
Global Object:
var a = 1; console.log(window.a === a);What is the output, and why?
NaN Comparison:
console.log(NaN === NaN);What is the output, and why?
Array Equality:
console.log([1] == [1]);What is the output, and why?
Hoisting in Functions:
function example() { console.log(bar); var bar = 10; console.log(bar); } example();What is the output, and why?
Default Parameter Value:
function greet(name = "Guest") { console.log("Hello, " + name); } greet(); greet("John");What is the output, and why?
typeofOperator:console.log(typeof null); console.log(typeof undefined);What is the output, and why?
==vs===:console.log(1 == "1"); console.log(1 === "1");What is the output for each line, and why?
instanceofOperator:function Car() {} const myCar = new Car(); console.log(myCar instanceof Car);What is the output, and why?
Object Property Access:
var obj = { x: 10, y: 20 }; var { x, y } = obj; console.log(x, y);What is the output, and why?
setTimeoutandthis:const obj = { count: 0, increment: function() { setTimeout(function() { console.log(this.count); }, 1000); } }; obj.increment();What is the output, and why?
Function Declarations vs Expressions:
console.log(foo()); console.log(bar()); function foo() { return "Hello, I'm foo!"; } var bar = function() { return "Hello, I'm bar!"; };What is the output, and why?
PromiseChaining:Promise.resolve(1) .then((res) => { console.log(res); return 2; }) .catch((err) => console.error(err)) .then((res) => console.log(res));What is the output, and why?
deleteOperator:const obj = { x: 10, y: 20 }; delete obj.x; console.log(obj.x);What is the output, and why?
Template Literals:
const name = "John"; const age = 30; console.log(`My name is ${name} and I am ${age} years old.`);What is the output, and why?
Object.keysand Property Order:const obj = { a: 1, b: 2, c: 3 }; console.log(Object.keys(obj));What is the output, and why?
Function Execution Context:
const a = 10; function example() { console.log(a); const a = 20; } example();What is the output, and why?
-
const arr = [1, 2, 3]; const result = arr.map(function(value) { return value * 2; }); console.log(result);What is the output, and why?
JSON.stringify:const obj = { x: 10, y: undefined, z: function() {} }; console.log(JSON.stringify(obj));What is the output, and why?
Regular Expressions:
const regex = /ab+c/; const str = "abbc"; console.log(regex.test(str));What is the output, and why?
parseIntFunction:console.log(parseInt("10.5"));What is the output, and why?
Function.prototype.bind:const obj1 = { x: 10 }; const obj2 = { x: 20 }; function getX() { return this.x; } const boundGetX1 = getX.bind(obj1); const boundGetX2 = getX.bind(obj2); console.log(boundGetX1(), boundGetX2());What is the output, and why?
Array.isArray:console.log(Array.isArray([])); console.log(Array.isArray({}));What is the output, and why?
Arrow Functions and
this:const obj = { count: 0, increment: function() { setTimeout(() => { console.log(this.count); }, 1000); } }; obj.increment();What is the output, and why?
MapObject Keys:const myMap = new Map(); const key1 = { a: 1 }; const key2 = { b: 2 }; myMap.set(key1, 'value1'); myMap.set(key2, 'value2'); console.log(myMap.get(key1));What is the output, and why?
Event Delegation:
<ul id="list"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> <script> document.getElementById('list').addEventListener('click', function(event) { console.log(event.target.innerText); }); </script>What happens when you click on an item, and why?
Object.create:const person = { greet: function() { console.log('Hello!'); } }; const john = Object.create(person); john.name = 'John'; john.greet();What is the output, and why?
NumberObject:console.log(typeof 42); console.log(typeof new Number(42));What is the output, and why?
IIFE (Immediately Invoked Function Expression):
(function() { var a = b = 5; })(); console.log(b); console.log(a);What is the output, and why?
argumentsObject:function sum() { console.log(arguments.length); } sum(1, 2, 3);What is the output, and why?
setTimeoutandthisin Non-Arrow Function:const obj = { count: 0, increment: function() { setTimeout(function() { console.log(this.count); }.bind(this), 1000); } }; obj.increment();What is the output, and why?
instanceofand Inheritance:function Animal() {} function Dog() {} Dog.prototype = Object.create(Animal.prototype); const myDog = new Dog(); console.log(myDog instanceof Dog); console.log(myDog instanceof Animal);What is the output, and why?
Multiple
catchBlocks:try { throw new Error('Error occurred'); } catch (e) { console.log('Catch block 1:', e.message); } catch (e) { console.log('Catch block 2:', e.message); }What is the output, and why?
WeakMapand Garbage Collection:let obj = {}; const weakMap = new WeakMap(); weakMap.set(obj, 'value'); obj = null; console.log(weakMap.get(obj));What is the output, and why?
Array.prototype.reduce:const numbers = [1, 2, 3]; const sum = numbers.reduce(function(acc, num) { return acc + num; }, 0); console.log(sum);What is the output, and why?
Promise.all:const promise1 = Promise.resolve(1); const promise2 = new Promise((resolve) => setTimeout(() => resolve(2), 1000)); const promise3 = 3; Promise.all([promise1, promise2, promise3]) .then((values) => console.log(values)) .catch((err) => console.error(err));What is the output, and why?
for...ofLoop:const iterable = [1, 2, 3]; for (let value of iterable) { console.log(value); }What is the output, and why?
NaNand Equality:console.log(NaN == NaN); console.log(NaN === NaN);What is the output for each line, and why?
Global Variables and
windowObject:var globalVar = 5; console.log(window.globalVar === globalVar);What is the output, and why?
Closure and
setTimeout:for (var i = 0; i < 5; i++) { setTimeout(function() { console.log(i); }, 1000); }What is the output, and why?
Generator Functions:
function* generatorFunction() { yield 1; yield 2; yield 3; } const generator = generatorFunction(); console.log(generator.next().value); console.log(generator.next().value);What is the output, and why?
Array.prototype.slice:const array = [1, 2, 3, 4, 5]; const newArray = array.slice(2); console.log(newArray);What is the output, and why?
nullandtypeof:console.log(typeof null);What is the output, and why?
Object.freeze:const obj = { prop: 42 }; Object.freeze(obj); obj.prop = 10; console.log(obj.prop);What is the output, and why?
Event Bubbling and Event Capturing:
<div id="parent"> <button id="child">Click me</button> </div> <script> document.getElementById('parent').addEventListener('click', function() { console.log('Parent clicked'); }, true); document.getElementById('child').addEventListener('click', function() { console.log('Child clicked'); }, true); </script>What is the order of log messages when you click the button, and why?
Array.prototype.splice:const array = [1, 2, 3, 4, 5]; const removed = array.splice(2, 2); console.log(array, removed);What is the output, and why?
Function Constructor:
const func = new Function('return 10 + 5'); console.log(func());What is the output, and why?
Object Destructuring:
const { x, y } = { x: 10, y: 20 }; console.log(x, y);What is the output, and why?
Array.prototype.filter:const numbers = [1, 2, 3, 4, 5]; const filtered = numbers.filter(function(num) { return num % 2 === 0; }); console.log(filtered);What is the output, and why?
argumentsObject and Arrow Function:const sum = () => { console.log(arguments.length); }; sum(1, 2, 3);What is the output, and why?
Object.keysand Inherited Properties:function Animal() {} Animal.prototype.legs = 4; const dog = new Animal(); dog.bark = function() { console.log('Woof!'); }; console.log(Object.keys(dog));What is the output, and why?
Object.defineProperty:const obj = {}; Object.defineProperty(obj, 'x', { value: 42, writable: false }); obj.x = 10; console.log(obj.x);What is the output, and why?
Unicode Escape Sequences:
console.log('\u0061'); console.log('\u{1F602}');What is the output, and why?
Array.prototype.concat:const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const result = arr1.concat(arr2); console.log(result);What is the output, and why?
JSON.parsewith Reviver Function:const jsonString = '{"name":"John","age":30,"city":"New York"}'; const obj = JSON.parse(jsonString, function(key, value) { if (key === 'age') return value + 5; return value; }); console.log(obj);What is the output, and why?
String.prototype.replacewith Regular Expression:const str = 'apple orange apple banana'; const result = str.replace(/apple/g, 'fruit'); console.log(result);What is the output, and why?
Object.prototype.toString:const obj = {}; console.log(Object.prototype.toString.call(obj));What is the output, and why?
Object.entries:const obj = { a: 1, b: 2, c: 3 }; const entries = Object.entries(obj); console.log(entries);What is the output, and why?
Array.prototype.mapwiththisArg:const numbers = [1, 2, 3]; const doubled = numbers.map(function(num) { return num * this.multiplier; }, { multiplier: 2 }); console.log(doubled);What is the output, and why?
typeofOperator andSymbol:const sym = Symbol('mySymbol'); console.log(typeof sym);What is the output, and why?
Object.prototype.hasOwnProperty:const obj = { a: 1, b: 2 }; console.log(obj.hasOwnProperty('a')); console.log(obj.hasOwnProperty('toString'));What is the output, and why?
Array.from:const arrayLike = { 0: 'a', 1: 'b', length: 2 }; const newArray = Array.from(arrayLike); console.log(newArray);What is the output, and why?
RegExpObject andexec:const pattern = /a/g; const str = 'abcabc'; let match; while ((match = pattern.exec(str)) !== null) { console.log(match[0], pattern.lastIndex); }What is the output, and why?
Object.setPrototypeOf:const obj1 = { x: 10 }; const obj2 = { y: 20 }; Object.setPrototypeOf(obj2, obj1); console.log(obj2.x);What is the output, and why?
Promise.race:const promise1 = new Promise(resolve => setTimeout(() => resolve('Promise 1'), 1000)); const promise2 = new Promise(resolve => setTimeout(() => resolve('Promise 2'), 500)); Promise.race([promise1, promise2]) .then(value => console.log(value)) .catch(err => console.error(err));What is the output, and why?
Numberand Decimal Representation:console.log(0.1 + 0.2 === 0.3);What is the output, and why?
DateObject and Month Index:const date = new Date(2022, 0, 31); console.log(date.getMonth());What is the output, and why?
String.prototype.slice:const str = 'abcdef'; const sliced = str.slice(-3, -1); console.log(sliced);What is the output, and why?
thisin Arrow Functions and Constructor Functions:function Person() { this.age = 0; setInterval(() => { this.age++; console.log(this.age); }, 1000); } const person = new Person();What is the output, and why?
Array.prototype.every:const numbers = [2, 4, 6, 8]; const allEven = numbers.every(function(num) { return num % 2 === 0; }); console.log(allEven);What is the output, and why?
Promiseandasync/await:async function example() { return Promise.resolve('Hello'); } example().then(value => console.log(value));What is the output, and why?
Array.prototype.findIndex:const numbers = [10, 20, 30, 40, 50]; const index = numbers.findIndex(function(num) { return num > 25; }); console.log(index);What is the output, and why?
for...inLoop and Object Properties:const obj = { a: 1, b: 2, c: 3 }; for (const key in obj) { console.log(key); }What is the output, and why?
Object.createand Inheritance:const parent = { x: 10 }; const child = Object.create(parent); console.log(child.x);What is the output, and why?
Array.prototype.some:const numbers = [1, 3, 5, 7, 9]; const someEven = numbers.some(function(num) { return num % 2 === 0; }); console.log(someEven);What is the output, and why?
PromiseandPromise.resolve:const promise = Promise.resolve('Resolved'); promise.then(value => console.log(value));What is the output, and why?
String.prototype.indexOf:const str = 'hello world'; console.log(str.indexOf('o')); console.log(str.indexOf('o', 5));What is the output for each line, and why?
Array.isArrayandinstanceof:const arr = [1, 2, 3]; console.log(Array.isArray(arr)); console.log(arr instanceof Array);What is the output for each line, and why?
DateObject and Timezone Offset:const date = new Date('2022-03-01T12:00:00Z'); console.log(date.toISOString());What is the output, and why?
JSON.stringifywith Replacer Function:const obj = { a: 1, b: 2, c: 3 }; const jsonString = JSON.stringify(obj, function(key, value) { if (key === 'b') return undefined; return value; }); console.log(jsonString);What is the output, and why?
Array.prototype.reverse:const arr = [1, 2, 3, 4, 5]; const reversed = arr.reverse(); console.log(reversed);What is the output, and why?
RegExpandexecwith Global Flag:const pattern = /a/g; const str = 'abcabc'; let match; while ((match = pattern.exec(str)) !== null) { console.log(match[0], pattern.lastIndex); }What is the output, and why?
NumberandtoString:const num = 42; console.log(num.toString()); console.log((42).toString());What is the output for each line, and why?
Object.keysand Property Order:const obj = { 10: 'a', 2: 'b', 7: 'c' }; console.log(Object.keys(obj));What is the output, and why?
Array.prototype.join:const arr = [1, 2, 3]; const joined = arr.join('-'); console.log(joined);What is the output, and why?
Math.maxandapply:const numbers = [1, 2, 3, 4, 5]; const max = Math.max.apply(null, numbers); console.log(max);What is the output, and why?
JSON.parsewith Reviver Function:const jsonString = '{"a":1,"b":2,"c":3}'; const obj = JSON.parse(jsonString, function(key, value) { if (key === 'b') return value * 10; return value; }); console.log(obj);What is the output, and why?
String.prototype.split:const str = 'apple,orange,banana'; const splitArray = str.split(','); console.log(splitArray);What is the output, and why?
Object.definePropertyand Getter/Setter:const obj = {}; let value = 42; Object.defineProperty(obj, 'x', { get: function() { return value; }, set: function(newValue) { value = newValue; } }); obj.x = 10; console.log(obj.x);What is the output, and why?
DateObject and Day of the Week:const date = new Date('2022-03-01T12:00:00Z'); console.log(date.getDay());What is the output, and why?
