Common JavaScript Questions with Code Examples Interview 2023
JavaScript interview questions with code examples:
What is hoisting in JavaScript and how does it work?
console.log(hoistedVariable); // undefined
var hoistedVariable = 'This is a hoisted variable';
console.log(notHoisted); // ReferenceError: notHoisted is not defined
let notHoisted = 'This is not a hoisted variable';
What is closure in JavaScript and how is it useful?
function outerFunction(x) {
return function innerFunction(y) {
return x + y;
};
}
const add5 = outerFunction(5);
console.log(add5(3)); // 8
What is the difference between == and === in JavaScript?
console.log(1 == '1'); // true
console.log(1 === '1'); // false
What is the difference between null and undefined in JavaScript?
let variable1;
console.log(variable1); // undefined
let variable2 = null;
console.log(variable2); // null
How does asynchronous code work in JavaScript?
console.log('Before setTimeout');
setTimeout(function () {
console.log('Inside setTimeout');
}, 1000);
console.log('After setTimeout');
What is the difference between let and var in JavaScript?
if (true) {
var variable1 = 'This is a var variable';
let variable2 = 'This is a let variable';
Recommended by LinkedIn
}
console.log(variable1); // This is a var variable
console.log(variable2); // ReferenceError: variable2 is not defined
How do you declare a variable in JavaScript?
var variable1 = 'This is a var variable';
let variable2 = 'This is a let variable';
const variable3 = 'This is a const variable';
What is the difference between forEach and map in JavaScript?
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function (number) {
console.log(number);
});
const doubledNumbers = numbers.map(function (number) {
return number * 2;
});
console.log(doubledNumbers);
What is the difference between function and arrow function in JavaScript?
function regularFunction(x, y) {
return x + y;
}
const arrowFunction = (x, y) => x + y;
console.log(regularFunction(1, 2)); // 3
console.log(arrowFunction(1, 2)); // 3
How do you declare an object in JavaScript?
const objectLiteral = {
key1: 'value1',
key2: 'value2'
};
const objectConstructor = new Object();
objectConstructor.key1 = 'value1';
objectConstructor.key2 = 'value2';