Posted in

Top 30 JavaScript Interview Questions and Answers for All Levels

Basic JavaScript Interview Questions (Freshers)

Question 1: What are the data types in JavaScript?

JavaScript has primitive data types: String, Number, BigInt, Boolean, undefined, null, Symbol, and object types like Array and Object.

Question 2: What is the difference between == and === operators?

The == operator performs type coercion before comparison, while === checks both value and type without coercion.

console.log(5 == '5'); // true
console.log(5 === '5'); // false

Question 3: What is the difference between null and undefined?

undefined means a variable has been declared but not assigned a value, while null is an intentional assignment representing no value.

Question 4: What is hoisting in JavaScript?

Hoisting moves variable and function declarations to the top of their scope before code execution, but only declarations are hoisted, not initializations.

console.log(x); // undefined
var x = 5;

Question 5: Explain the difference between var, let, and const.

var is function-scoped and can be redeclared, let is block-scoped and cannot be redeclared in the same scope, const is block-scoped and cannot be reassigned.

Question 6: What are truthy and falsy values in JavaScript?

Falsy values are false, 0, -0, 0n, “”, null, undefined, NaN. All other values are truthy.

if(0) console.log('Falsy'); // Won't execute
if("hello") console.log('Truthy'); // Will execute

Question 7: What is strict mode in JavaScript?

Strict mode (‘use strict’) enforces stricter parsing and error handling, catching common coding errors and preventing unsafe actions.

Question 8: How do you create an object in JavaScript?

Objects can be created using object literals, Object constructor, Object.create(), or ES6 classes.

const obj = {name: 'John'};
const obj2 = new Object();
const obj3 = Object.create(null);

Question 9: What is the purpose of the ‘this’ keyword?

‘this’ refers to the current execution context, which can be global object, object method context, or explicitly set value.

Question 10: How do you check if a property exists in an object?

Use ‘in’ operator, hasOwnProperty(), or undefined check.

const obj = {name: 'John'};
console.log('name' in obj); // true
console.log(obj.hasOwnProperty('name')); // true

Intermediate JavaScript Interview Questions (1-3 Years Experience)

Question 11: What is variable scope in JavaScript?

Variable scope determines accessibility: global scope, function scope (var), and block scope (let/const).

Question 12: What is the Temporal Dead Zone?

Temporal Dead Zone is the period between entering a block scope and variable initialization where let/const access throws ReferenceError.

console.log(a); // ReferenceError
let a = 10;

Question 13: Explain closures in JavaScript.

A closure is a function that retains access to its outer scope variables even after the outer function has returned.

function outer() {
  let count = 0;
  return function inner() {
    return ++count;
  };
}
const counter = outer();
console.log(counter()); // 1

Question 14: What is a callback function?

A callback is a function passed as an argument to another function, executed after some operation completes.

Question 15: What are arrow functions and their limitations?

Arrow functions provide concise syntax and don’t bind their own ‘this’. They inherit ‘this’ from enclosing scope.

const add = (a, b) => a + b;
console.log(add(2, 3)); // 5

Question 16: Explain the difference between for…in and for…of loops.

for…in iterates over object enumerable properties, for…of iterates over iterable values like arrays.

Question 17: What is the difference between map(), filter(), and find()?

map() transforms each element, filter() selects elements by condition, find() returns first matching element.

const nums = [1, 2, 3];
nums.map(n => n*2); // [2,4,6]
nums.filter(n => n > 1); // [2,3]
nums.find(n => n > 1); // 2

Question 18: How do you add/remove elements from an array?

Use push/pop/shift/unshift for ends, splice() for any position.

const arr = [1, 2];
arr.push(3); // [1,2,3]
arr.pop(); // [1,2]
arr.splice(1, 1); // [1]

Question 19: What are default and named exports?

Default export uses export default, named exports use export {name}. Import matches accordingly.

// Export
export default function() {}
export const name = 'value';

// Import
import func from './module';
import { name } from './module';

Question 20: How do you convert object to JSON string?

Use JSON.stringify() to convert object to JSON string, JSON.parse() to convert back.

const obj = {name: 'John'};
const json = JSON.stringify(obj); // '{"name":"John"}'
const parsed = JSON.parse(json);

Advanced JavaScript Interview Questions (3-6 Years Experience)

Question 21: What is a Promise in JavaScript?

Promise represents eventual completion/failure of async operation with states: pending, fulfilled, rejected.

Question 22: Explain Promise chaining.

Promise chaining uses .then() to sequence async operations, passing results to next .then().

fetchData()
  .then(data => processData(data))
  .then(result => display(result))
  .catch(error => console.error(error));

Question 23: What is Promise.all()?

Promise.all() takes array of promises, returns single promise resolved with array of results when all resolve, or rejected if any rejects.

Question 24: What is async/await?

async/await provides syntactic sugar over promises, making async code look synchronous using async functions and await keyword.

async function fetchData() {
  try {
    const response = await fetch('/api/data');
    return await response.json();
  } catch (error) {
    console.error(error);
  }
}

Question 25: How do you handle errors in async/await?

Use try/catch blocks around await expressions to handle rejected promises.

Question 26: What is variable shadowing?

Variable shadowing occurs when a variable in inner scope has same name as outer scope variable, hiding outer one.

let x = 10;
function test() {
  let x = 20;
  console.log(x); // 20 (shadowed)
}
test();
console.log(x); // 10 (original)

Question 27: Explain event loop in JavaScript.

Event loop processes async callbacks from task queue after call stack empties, enabling non-blocking operations.

Question 28: What is debouncing in JavaScript?

Debouncing delays function execution until after wait time has elapsed since last invocation, useful for search inputs.

function debounce(fn, delay) {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn.apply(this, args), delay);
  };
}

Question 29: How would you implement deep cloning of objects at Zoho?

Use JSON.parse(JSON.stringify()) for simple objects or recursive function for complex objects with functions/dates.

function deepClone(obj) {
  return JSON.parse(JSON.stringify(obj));
}

Question 30: Explain prototypal inheritance in JavaScript.

Prototypal inheritance uses prototype chain where objects inherit properties/methods from prototype object.

function Person(name) {
  this.name = name;
}
Person.prototype.greet = function() {
  return `Hi, ${this.name}`;
};
const john = new Person('John');
console.log(john.greet()); // Hi, John

Leave a Reply

Your email address will not be published. Required fields are marked *