JavaScript Interview Questions and Examples 1

JavaScript Interview Questions and Examples 1

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

What are the different data types in JavaScript? 2

What is a closure in JavaScript? 2

What is the difference between null and undefined in JavaScript?

null represents the intentional absence of any object value, while undefined represents the absence of a defined value. In other words, null is an assignment value which means “no value”, while undefined is a default value that JavaScript assigns to variables that have not been assigned a value. For example:

let a;

console.log(a); // undefined

let b = null;

console.log(b); // null

What are the different data types in JavaScript?

JavaScript has 7 primitive data types: number, string, boolean, undefined, null, symbol, and bigint. In addition, JavaScript also has one non-primitive data type: object.

let num = 42;

let str = ‘Hello, world!’;

let bool = true;

let undef = undefined;

let n = null;

let sym = Symbol(‘foo’);

let big = BigInt(123456789);

let obj = { name: ‘John’, age: 30 };

What is a closure in JavaScript?

A closure is a function that has access to variables in its outer lexical scope, even after the outer function has returned. A closure is created when an inner function references a variable in its outer function’s scope.

function outerFunction() {

  const outerVar = ‘Hello’;

  function innerFunction() {

    console.log(outerVar); // can access outerVar from the outer scope

  }

  return innerFunction;

}

const innerFunc = outerFunction();

innerFunc(); // logs “Hello”