DEV Community

vivek
vivek

Posted on

JavaScript Interview Questions

Here are some commonly asked JavaScript interview questions along with their answers:


1. What is the difference between var, let, and const?

  • var: Function-scoped, can be redeclared, hoisted but not block-scoped.
  • let: Block-scoped, cannot be redeclared within the same block, hoisted but not initialized.
  • const: Block-scoped, must be initialized at the time of declaration, value cannot be reassigned.

Example:

function example() {
  if (true) {
    var x = 10; // accessible outside this block
    let y = 20; // block-scoped
    const z = 30; // block-scoped and immutable
  }
  console.log(x); // 10
  // console.log(y); // Error
  // console.log(z); // Error
}
Enter fullscreen mode Exit fullscreen mode

2. What is a closure, and how is it used?

  • A closure is when a function "remembers" the variables from its lexical scope even when the function is executed outside that scope.

Example:

function outer() {
  let count = 0;
  return function inner() {
    count++;
    return count;
  };
}

const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
Enter fullscreen mode Exit fullscreen mode

3. Explain the difference between == and ===.

  • ==: Compares values after type coercion.
  • ===: Compares values and types strictly without type coercion.

Example:

console.log(5 == '5');  // true (type coercion)
console.log(5 === '5'); // false (strict comparison)
Enter fullscreen mode Exit fullscreen mode

4. How does the JavaScript Event Loop work?

  • The event loop allows JavaScript to perform non-blocking operations by using a single-threaded model.
  • Call Stack: Executes code.
  • Task Queue: Stores asynchronous callbacks like setTimeout.
  • Microtask Queue: Stores promises (.then, catch).
  • Event Loop: Monitors the stack and pushes tasks from the queue when the stack is empty.

Example:

console.log('Start');

setTimeout(() => console.log('Timeout'), 0);

Promise.resolve().then(() => console.log('Promise'));

console.log('End');

// Output: Start, End, Promise, Timeout
Enter fullscreen mode Exit fullscreen mode

5. What is the purpose of bind(), call(), and apply()?

These methods are used to change the this context of a function:

  • bind(): Returns a new function with the specified this.
  • call(): Invokes the function immediately with a specified this and arguments.
  • apply(): Similar to call() but takes arguments as an array.

Example:

const obj = { name: 'Alice' };

function greet(greeting) {
  return `${greeting}, ${this.name}`;
}

console.log(greet.call(obj, 'Hello')); // Hello, Alice
console.log(greet.apply(obj, ['Hi'])); // Hi, Alice
const boundGreet = greet.bind(obj);
console.log(boundGreet('Hey')); // Hey, Alice
Enter fullscreen mode Exit fullscreen mode

6. Write a function to check if a string is a palindrome.

A palindrome reads the same backward as forward.

function isPalindrome(str) {
  const reversed = str.split('').reverse().join('');
  return str === reversed;
}

console.log(isPalindrome('madam')); // true
console.log(isPalindrome('hello')); // false
Enter fullscreen mode Exit fullscreen mode

7. What is the difference between Object.create() and using the new keyword?

  • Object.create(): Creates a new object with a specified prototype.
  • new keyword: Creates an instance of a constructor function and sets the prototype.

Example:

const parent = { greet: () => 'Hello' };
const child = Object.create(parent);
console.log(child.greet()); // Hello

function Person(name) {
  this.name = name;
}
const person = new Person('John');
console.log(person.name); // John
Enter fullscreen mode Exit fullscreen mode

8. Implement a custom Array.prototype.map function.

Array.prototype.myMap = function(callback) {
  const result = [];
  for (let i = 0; i < this.length; i++) {
    result.push(callback(this[i], i, this));
  }
  return result;
};

const arr = [1, 2, 3];
const doubled = arr.myMap(num => num * 2);
console.log(doubled); // [2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

9. How do debouncing and throttling work?

  • Debouncing: Ensures a function is executed only after a specified delay after the last call.
  • Throttling: Ensures a function is executed at most once in a specified interval.

Debouncing Example:

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

const debouncedFn = debounce(() => console.log('Debounced!'), 300);
debouncedFn();
debouncedFn(); // Will log "Debounced!" only once after 300ms.
Enter fullscreen mode Exit fullscreen mode

Throttling Example:

function throttle(fn, interval) {
  let lastCall = 0;
  return function(...args) {
    const now = Date.now();
    if (now - lastCall >= interval) {
      lastCall = now;
      fn.apply(this, args);
    }
  };
}

const throttledFn = throttle(() => console.log('Throttled!'), 1000);
throttledFn();
throttledFn(); // Will log "Throttled!" at most once per 1000ms.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)