Code snippet
Question 1
function Example() { let y; console.log(x, y) if (true) { var x = 10; let y = 10; console.log(x,y) } console.log(x,y)}Example();Answer
undefined unundefined
10,10
10, undefined
var x is function-scoped and hoisted, so x is undefined initially, even before its declaration. let y is block-scoped, so the outer y is separate from the inner y. Outside the block, y remains uninitialized.
Question 2
const obj = { value: 42, showArrow: function () { setTimeout(() => { console.log(this.value); }, 1000); }, showNormal: function () { setTimeout(function () { console.log(this.value); }, 1000); },};
obj.showArrow();obj.showNormal();Answer
42 undefined
In arrFn, the arrow function preserves this from obj. In normalFn, this inside the setTimeout refers to window.
Question 3
var p = 1;function outerFn() { var p = 2; function innterFn() { p++; console.log(p); var p = 3 console.log(p) } innterFn() console.log(p)}outerFn()Answer
NaN 3 2
p to be hoisted and initialized as undefined before incrementing so p++ results in NaN. then p = 3 as var is functional scope for outer function p=2
Question 4
// frequently askedconst arr = [1, 2, 3, 4, 5];
for (var i = 0; i < arr.length; i++) { setTimeout(function () { console.log(i); }, 1000);}Answer
5 5 5 5 5
var is functional scope so it is shared across all iteration, therefore use let to get output 0,1,2,3,4 as it is block scope
Question 5
// frequently askedconst arr = [1, 2, 3, 4, 5];for (var i = 0; i < arr.length; i++) { (function (i) { setTimeout(function () { console.log(i); }, 1000); })(i); // Pass `i` as an argument to the IIFE}Answer
0,1,2,3,4 -> for each IIFE it will create a new context and preserve value of i in its scope
Question 6
//Asked in Amazonvar a = 10;x()y()z()
function x(){ var a = 20; console.log(this.a)}function y(){ console.log(this.a)}const z = () => { console.log(this.a)}Answer
10 10 , ReferenceError
x(), y() -> this share global scope z() -> tried to access before initilization
Question 7
// this is follow up question for above questionlet a = 10;x()y()z()
function x(){ console.log(this.a)}function y(){ console.log(this.a)}const z = () => { console.log(this.a)}Answer
undefined, undefined , ReferenceError
In regular functions (x() and y()), this refers to the global object, which does not have variable a so it return undefined.
Question 8
function func() { try { console.log(1) return } catch (e) { console.log(2) } finally { console.log(3) } console.log(4)}func()Answer
1,3
βfinallyβ block runs even after βreturnβ statement, so console.log(3) is executed
Question 9
let obj = { name: 'John' };let weakMap = new WeakMap();weakMap.set(obj, 'Person');
console.log(weakMap.has(obj));
obj = null;
setTimeout(() => { console.log(weakMap.has(obj));}, 1000);Answer
true false
obj = null -> dereferences the object and grabage collection(GB) remove that object when i
Question 10
const myObject = { name: "Test", getFunctionName: function () { console.log(this.name); }, getArrowFunctionName: () => { console.log(this.name); }, updateArrowFunctionScope: function () { const innerArrowFunction = () => { console.log(this.name); }; innerArrowFunction(); },};
myObject.getFunctionName();myObject.getArrowFunctionName();myObject.updateArrowFunctionScope();Answer
Inner-Test Outer-test Inner-Test
myObject.getFunctionName(): this in a regular function refers myObject myObject.getArrowFunctionName(): Arraow function inherit this from outside scope myObject.updateArrowFunctionScope(): Arraow function inherit this from outside and outside it is wrpeerd under function where this is βmyObjectβ
Question 11
// asked similar question in mindticklefunction outer() { console.log(a); var a = 10; function inner() { console.log(a); return 10; function a () { var a = 10 } } inner();}outer();Answer
undefined, [Function: a]
var a declaration is hoisted so it is undefined for first console
βfunction aβ declaration is hoisted, donβt get confused by return statement
Question 12
//asked in dream 11
var doc = "Soni's frontend doc";const obj = { doc:'soni', printName: function(){ return this.doc }, printNameArrow: () => { return this.doc }, IIFE: (function(){ // console.log(this) return this.doc })(), IIFEArrow: (() => { // console.log(this) return this.doc })()}console.log(obj.printName())console.log(obj.printNameArrow())console.log(obj.IIFE)console.log(obj.IIFEArrow)Answer
soni, Soniβs frontend doc, Soniβs frontend doc, Soniβs frontend doc,
normal function -> this refer to obj Arrow function -> this refer to outer scope: which is window obj obj.IIFE -> this refers to the global obj.IIFEArrow -> this refers to the global
Question 13
function add5(x) { return x + 5;}
function multiplyBy3(x) { return x * 3;}
function compose(f, g) { return function(x) { return f(g(x)); };}
const addThenMultiply = compose(multiplyBy3, add5);console.log(addThenMultiply(2));Answer
21,
self explanatory
Question 14
console.log(typeof null);console.log(typeof undefined);console.log(null === undefined);console.log(null == undefined);console.log(2 * '2');console.log(2 * 'Hello');Answer
object,
undefined,
false,
true,
4,
NaN
Question 15
console.log([1,2,3] + [3,2,1])Answer
1,2,33,2,1When the + operator is used with arrays, they are coerced to strings
Question 16
class Counter { #number = 10
increment() { this.#number++ }
getNum() { return this.#number }}
const counter = new Counter()counter.increment()
console.log(counter.#number)Answer
Error
In ES2020, we can add private variables in classes by using the #. We cannot access these variables outside of the class. When we try to log counter.#number, a SyntaxError gets thrown: we cannot access it outside the Counter class!
Question 17
var name = "test"
function callName() { name= 'test2', console.log(name)}callName()console.log(name)Answer
test2, test2
self explanatory
Question 18
console.log([] == [])console.log({} == {})console.log(2 == "2")console.log({} === {})Answer
false, false, true, false
Question 19
const arr = [10, -1, 2];arr.sort();Answer
[ -1, 10, 2 ], sorts the array elements as considering element strings by default.
Question 20
//asked in Publicis Sapientconsole.log(7 > 6 > 5);Answer
(7 > 6) > 5 -> true > 5 (1 > 5) -> false
Question 21
let a = 0;a = ++a + a++ + --a + a--;console.log(a);Answer
4a = 0; a = 1 + 1 + 1 + 1;
Question 22
What will happen when we will clik on button ?
<div onclick="console.log('first div')"> <div onclick="console.log('second div')"> <button onclick="console.log('button')"> Click! </button> </div></div>Answer
button, second div, first div,
This happens due to event bubbling, where the click event propagates from the innermost element (button) to the outermost parent div
Question 23
async function foo() { console.log(1); await Promise.resolve(); console.log(2);}
foo();console.log(3);Answer
1, 3, 2
await pauses the function execution, allowing the synchronous code to executed first
Question 24
Promise.all([Promise.resolve(1), Promise.resolve(2), Promise.reject("Error")]) .then((values) => console.log("Resolved:", values)) .catch((err) => console.log("Caught:", err));Answer
Caught: Error
Promise.all rejects immediately if any promise in the array is rejected.
Question 25
Promise.all([Promise.resolve(1), undefined, null]) .then((values) => console.log("Resolved:", values)) .catch((err) => console.log("Caught:", err));Answer
Resolved: [1, null, ,undefined]
Promise.all treats undefined and null as resolved values
Question 26
//asked in multiplier
console.log("Start")new Promise((resolve, rej) => { console.log("Promise1") resolve("resolved") console.log("Promise2")}).then(data => console.log(data))console.log("end")Answer
Start, Promise1, Promise2, end, resolved
the promise executor runs synchronously and rest run in asyn fashion
Question 27
console.log('Start');setTimeout(() => { console.log('Timeout');}, 0);Promise.resolve().then(() => { console.log('Promise');});console.log('End');Answer
Start, End, Promise, Timeout
synchronous code runs first, then the microtask (Promise.then) executes, followed by the macrotask (setTimeout) after the event loop processes all microtasks
Question 28
console.log('Start');
setTimeout(() => { console.log('Timeout 1'); Promise.resolve().then(() => { console.log('Promise 1'); }); setTimeout(() => { console.log('Timeout 2'); }, 0);}, 0);
Promise.resolve().then(() => { console.log('Promise 2');});
console.log('End');Answer
Start, End, Promise 2, Timeout 1, Promise 1, Timeout 2,
synchronous code runs first, then the microtask Promise 2 executes, followed by the first macrotask Timeout 1 and its microtask Promise 1, and finally the second macrotask Timeout 2
Question 29
Promise.resolve(1) .then((x) => x + 1) .then((x) => { throw new Error("An error occurred!"); }) .catch((err) => { console.log(err.message); return 5; }) .then((x) => console.log(x));Answer
An error occurred!, 5
The βcatchβ block handles the error and returns 5. This value is passed to the next then.
Question 30
const promise = new Promise((resolve, reject) => { resolve("First"); resolve("Second"); reject("Third");});
promise .then((res) => console.log(res)) .catch((err) => console.log(err));Answer
First
A promise can only resolve/reject once. The subsequent resolve and reject calls are ignored.
Question 31
console.log('Start');
async function foo() { console.log('Foo Start'); await new Promise(resolve => setTimeout(resolve, 0)); console.log('Foo End');}
foo().then(() => { console.log('After Foo');});
console.log('End');Answer
Start, Foo Start, End, Foo End, After Foo
Question 32
Promise.reject("Error") .catch((err) => { console.log("Caught:", err); return "Recovered"; }) .finally(() => { console.log("Finally 2"); }) .then((value) => { console.log("Then:", value); });Answer
Caught: Error, Finally 2, Then: Recovered
The catch handles the rejection and passes βRecoveredβ to the next then. The finally block executes but does not alter the flow.
Question 33
let c = { greeting: 'Hey!' };let d;
d = c;c.greeting = 'Hello';
console.log(d.greeting);Answer
βHelloβ
both c and d are pointing towards same reference.
Question 34
const obj = { value: 10 };
function calculate(add, multiply) { return (this.value + add) * multiply;}
const newObj = { value: 20 };
console.log(calculate.call(obj, 5, 2));console.log(calculate.apply(newObj, [3, 4]));
const boundCalc = calculate.bind(obj, 2);console.log(boundCalc(3));Answer
30, 92, 36
call and apply invoke the function immediately with a specified this and arguments. bind create new function with this which can be called later at any point.
Question 35
const obj = { name: "John", getName: function () { return this.name; },};
const bound1 = obj.getName.bind({ name: "Frank" });const bound2 = bound1.bind({ name: "Grace" });
console.log(bound1());console.log(bound2());Answer
Frank, Frank
bind creates a new function with a permanently bound this. Since bound1 already has this bound to { name: βFrankβ}, further binding (with bound2) has no effect
Question 36
const obj = Object.freeze({ a: 1, b: { c: 2 },});
obj.b.c = 3;obj.d = 4;
console.log(obj);Answer
{ a: 1, b: { c: 3 } }
Object.freeze() makes an object shallowly immutable. This means properties cannot be added or deleted from the object. However, nested objects are not deeply frozen, so obj.b.c can be modified, but obj.d cannot be added.
Question 37
const userDetails = { firstName: "John", lastName: "Doe", age: 25, address: { city: "Bangalore", country: "USA" }}
let cloneUserDetails = { ...userDetails };
//Updating original objectuserDetails.age = 18;userDetails.address.city = "chennai";
console.log(cloneUserDetails.age);console.log(cloneUserDetails.address.city);Answer
25, chennai
cloneUserDetails.age remains 25 because itβs a shallow copy.
Question 38
const obj = { _value: 1, get value() { return this._value * 2; }, set value(val) { this._value = val + 1; },};
obj.value = 5;console.log(obj.value);Answer
12Setting obj.value triggers the setter -> 5 + 1 = 6. The getter then returns 6 * 2 = 12
Question 39
function Animal() { this.species = "Animal";}
Animal.prototype.getSpecies = function() { return this.species;};
function Dog() { this.species = "Dog";}
Dog.prototype = new Animal();
const dog = new Dog();console.log(dog.getSpecies());Answer
βDogβ
this.species in the getSpecies method refers to the dog instance, which has its own species property set to βDogβ
Question 40
function A() {}function B() {}
A.prototype = new B();
const a = new A();console.log(a instanceof A);console.log(a instanceof B);Answer
true, true
a instanceof A returns true -> a inherits from A.prototype a instanceof B -> because A.prototype is an instance of B
Question 41
function Person(name) { this.name = name; return { name: "John" };}
const person = new Person("Alice");console.log(person.name);Answer
John
When a constructor explicitly returns an object, the returned object overrides this.
Question 42
function Person(name) { this.name = name;}
Person.prototype.sayHello = function() { return "Hello, " + this.name;};
function Employee(name, job) { Person.call(this, name); // Call the Person constructor this.job = job;}
Employee.prototype = Object.create(Person.prototype);Employee.prototype.constructor = Employee;
Employee.prototype.sayHello = function() { return "Hello, I am " + this.name + " and I work as a " + this.job;};
const employee = new Employee("Alice", "Developer");console.log(employee.sayHello());Answer
Hello, I am Alice and I work as a Developer
If you will remove sayHelloo method from Employee then it will look into its prototype chain and call Person sayHello method.
Question 43
console.log("10" - "4" + "2");Answer
β62β
β10β - β4β is 6 (numbers), and then 6 + β2β results is β62β β10β - β4β + β2β β β62β
Question 44
const { a: x = 10, b: y = 20 } = { a: undefined, b: null };
console.log(x);console.log(y);Answer
10 -> Default value is used because a is explicitly undefined
null -> Default value is ignored because b is explicitly null.
Question 45
// asked in mindtreeconsole.log(NaN == NaN);Answer
falseNaN is not equal to itself.
Question 46
const obj = { a: 1};
console.log(obj.hasOwnProperty('a'));console.log(obj.hasOwnProperty('b'));Answer
true, false
a is a direct property of obj b is not a direct property of obj
Question 47
const obj1 = { hasOwnProperty: function() { return 'return!'; }, a: 1};
console.log(obj1.hasOwnProperty('a'));Answer
return
the hasOwnProperty method is overridden in obj1, so it doesnβt call the original Object.prototype.hasOwnProperty method
Question 48
const obj1 = { a: 1 };const obj2 = Object.create(obj1);
console.log(obj2.__proto__ === obj1);Answer
true
proto points to the prototype of an object. Since obj2 was created with obj1 as its prototype, obj2.proto points to obj1
Question 49
const obj = { a: 1, b: 2 };delete obj.a;console.log(obj.a);console.log('a' in obj);Answer
undefined, false
Question 50
console.log(a);console.log(b);console.log(c);
var a = 10;let b = 20;const c = 30;Answer
undefined
ReferenceError: Cannot access βbβ before initialization
ReferenceError: Cannot access βcβ before initialization