Get JS Interview Ready

Rajan Lagah
2 min readJan 9, 2024

--

Here I am listing all the JS questions that I have faced in the actual interview. I won't mention the company name but overall its good to practice or do last-minute preparations.

Hoisting

I believe you know hoisting diff in var,let and const. But here is tricky question.

Lexical Scope

let x = 'fog'
function first() {
console.log(x)
}
x = 'pog'
function second(){
let x = 'rog'
first()
}
second()

what will be the output? What I thought was for each function execution context is created. Andsecond function first the function is called so execution context will be created inside second and x is not defined inside first a function so it will try to look up in its lexical scope. So based on that, my output was rog

But that was wrong. Right ans is when function first is getting memory allocated during memory allocation at that time x is pointing to x in global context so it will print value as pog

Functions

const obj = {
name: 'Object',
op:{
methodArrow: () => console.log(this),
methodRegular: function(){console.log(this)}
}
};

Output?

Because the arrow function inherits this from its lexical scope and for regular function this points to where it is called. So output will be

window ( window obj)
{methodArrow: ƒ, methodRegular: ƒ}

Execution Stack


console.log("start");

setTimeout(function() {
console.log("Timeout 1");
}, 0);

new Promise(function(resolve, reject) {
console.log("Promise 1");
resolve();
}).then(function() {
console.log("Promise 2");
});

setTimeout(function() {
console.log("Timeout 2");
}, 0);

console.log("End");

what will be the output of the above? Tricky right?

start
Promise 1
End
Promise 2
Timeout 1
Timeout 2

We know promise takes high priority as compared to setTimeout so this is what we will get as output.

‘this’

Q1.

let name = "Global Name";

function printGlobalName() {
console.log(this.name);
}

// First call - default this is window
printGlobalName(); // ?

The output will not be “Global Name”, why? Yes, you are right that in a function call, this will refer to window/global obj but each function call has its execution context and gets its copy of window/global obj. That is why it will be undefined.

Function implementation

input => {
field1: 1,
field2: undefined,
field3: "value",
field4: {
child: "child",
child4: "child4",
child2: {
child3: "child2"
}
}
};

output => {
field1: 1,
field2: undefined,
field3: "value",
field4.child: "child",
field4.child2.child3: "child2",
field4.child4 : "child4"
}
let ans = {};
function flat(obj, prefix) {
for (let key in obj) {
if (typeof obj[key] == "object") {
flat(obj[key], prefix ? prefix + "." + key : key);
} else {
ans[prefix ? prefix + "." + key : key] = obj[key];
}
}
}
const target = {
field1: 1,
field2: undefined,
field3: "value",
field4: {
child: "child",
child4: "child4",
child2: {
child3: "child2"
}
}
};
flat(target)

I will keep adding more.

--

--