Fresher JavaScript Interview Questions

What is strict mode in JavaScript?

Strict mode makes JavaScript stricter, so common mistakes throw errors instead of failing silently. Turn it on with "use strict" at the top of a file or function.

"use strict";

x = 10;   // ReferenceError: x is not defined (no var, let or const)

Modules and classes always run in strict mode.

What is the difference between for…in and for…of?

const arr = ["a", "b"];

for (const i in arr) console.log(i);
for (const v of arr) console.log(v);

const obj = { x: 1, y: 2 };
for (const key in obj) console.log(key);

Output:

Tutorials Class - Output Window

0
1
a
b
x
y

Use for...of for arrays, and for...in for the keys of an object. See JavaScript Loops.

What is the difference between function declaration and function expression?

// declaration
sayHi();
function sayHi() {
  console.log("Hi");
}

// expression
const sayBye = function () {
  console.log("Bye");
};
sayBye();

Output:

Tutorials Class - Output Window

Hi
Bye

The declaration is hoisted, so calling it above works. A function expression is not usable before the line where it is assigned: sayBye() above its definition gives an error. See JavaScript Functions.

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

const list = [1, 2];
const obj = { a: 1 };

console.log(typeof list);
console.log(Array.isArray(list));
console.log(Array.isArray(obj));

Output:

Tutorials Class - Output Window

object
true
false

typeof [] is "object", so use Array.isArray(). See Data Types.