JavaScript Interview Questions and Examples 2

JavaScript Interview Questions and Examples 2

What is closure in JavaScript? Give an example. 1

What is the difference between var, let, and const in JavaScript? 2

What is closure in JavaScript? Give an example.

A closure is a function that has access to its outer function’s scope, even after the outer function has returned. This allows you to create private variables and methods in JavaScript. Here is an example:

function outer() {

  const name = ‘John’;

  function inner() {

    console.log(`My name is ${name}`);

  }

  return inner;

}

const myFunction = outer();

myFunction(); // Output: “My name is John”

In the example above, inner has access to the name variable, even though it is defined in the outer function, because inner is a closure.

What is the difference between var, let, and const in JavaScript?

var is function-scoped, whereas let and const are block-scoped. This means that variables declared with var are accessible within the entire function, while variables declared with let and const are only accessible within the block they were defined in.

let and const are also similar, but the difference between them is that let allows you to reassign the variable, while const does not.

Here is an example:

function myFunction() {

  var a = 1;

  let b = 2;

  const c = 3;

  if (true) {

    var a = 4;

    let b = 5;

    const c = 6;

    console.log(a, b, c); // Output: 4, 5, 6

  }

  console.log(a, b, c); // Output: 4, 2, 3

}

myFunction();

In the example above, a is accessible within the entire function, while b and c are only accessible within their respective blocks.