JavaScript Interview Questions and Examples 3

JavaScript Interview Questions and Examples 3

What is the difference between null and undefined in JavaScript? 1

What are closures in JavaScript? 2

How can you check if a variable is an array in JavaScript? 2

Null and undefined are both primitive data types in JavaScript. However, null is an intentional absence of any object value, whereas undefined means that the variable has been declared but has not been assigned any value.

What is the difference between null and undefined in JavaScript?

let a;

console.log(a); // undefined

let b = null;

console.log(b); // null

What are closures in JavaScript?

A closure is a function that has access to variables in its outer function scope, even after the outer function has returned. Closures are created when a function is defined inside another function and the inner function is returned or passed as a parameter to another function.

function outerFunction() {

  let count = 0;

  function innerFunction() {

    count++;

    console.log(count);

  }

  return innerFunction;

}

const increment = outerFunction();

increment(); // 1

increment(); // 2

How can you check if a variable is an array in JavaScript?

You can check if a variable is an array using the Array.isArray() method.

const arr = [1, 2, 3];

console.log(Array.isArray(arr)); // true

const obj = { a: 1, b: 2 };

console.log(Array.isArray(obj)); // false