Fresher JavaScript Interview Questions

What is JavaScript?

JavaScript is a high-level programming language that makes web pages interactive. It runs in every web browser, and also on servers with Node.js.

console.log("Hello, JavaScript!");

Output:

Tutorials Class - Output Window

Hello, JavaScript!

HTML gives the structure, CSS gives the design, and JavaScript gives the behaviour. See JavaScript Introduction.

What is the difference between Java and JavaScript?

Despite the name, they are two different languages.

PointJavaJavaScript
TypeCompiled, strongly typedInterpreted, dynamically typed
Runs inJVM (Java Virtual Machine)Browser and Node.js
Used forAndroid apps, backend, enterprise softwareWeb pages, web apps, servers with Node.js
Code styleClass-based alwaysPrototype-based, with classes as syntax

JavaScript got the name only because Java was very popular in 1995.

What are the data types in JavaScript?

JavaScript has 7 primitive types and the object type.

TypeExample
String"Hello"
Number42, 3.14
Booleantrue
UndefinedA variable without a value
NullAn empty value on purpose
BigInt10n
SymbolA unique identifier
ObjectArrays, functions, dates and plain objects
console.log(typeof "hi", typeof 5, typeof true, typeof undefined, typeof {});

Output:

Tutorials Class - Output Window

string number boolean undefined object

See JavaScript Data Types.

What is the difference between == and === in JavaScript?

== (loose equality) converts the types before comparing. === (strict equality) compares the value and the type.

console.log(5 == "5");
console.log(5 === "5");
console.log(0 == false);
console.log(0 === false);
console.log(null == undefined);
console.log(null === undefined);

Output:

Tutorials Class - Output Window

true
false
true
false
true
false

Use === and !== to avoid surprising results. See Type Conversion.

What is NaN in JavaScript?

NaN means “Not a Number”. It is the result of a maths operation that has no valid number as result.

console.log(Number("abc"));
console.log(0 / 0);
console.log(NaN === NaN);
console.log(Number.isNaN(NaN));
console.log(typeof NaN);

Output:

Tutorials Class - Output Window

NaN
NaN
false
true
number

NaN is the only value that is not equal to itself, so check it with Number.isNaN(). Its type is number.

What is the difference between null and undefined?

  • undefined: the variable was declared but has no value, or a property or function result is missing. JavaScript sets it.
  • null: an empty value that the programmer sets on purpose.
let a;
let b = null;
console.log(a, b);
console.log(typeof a, typeof b);
console.log(a == b, a === b);

Output:

Tutorials Class - Output Window

undefined null
undefined object
true false

typeof null gives "object", which is an old bug of the language.

What is scope in JavaScript?

Scope is the area of the code where a variable is visible.

  • Global scope: declared outside all functions, visible everywhere.
  • Function scope: declared inside a function, visible only there.
  • Block scope: declared with let or const inside { }, visible only in that block.
let g = "global";
function f() {
  let l = "local";
  console.log(g, l);
}
f();
console.log(typeof l);

Output:

Tutorials Class - Output Window

global local
undefined

See JavaScript Scope.

What are arrow functions in JavaScript?

An arrow function is a shorter way to write a function. It uses =>.

const square = n => n * n;
const add = (a, b) => a + b;

console.log(square(4));
console.log(add(2, 3));
console.log([1, 2, 3].map(n => n * 2));

Output:

Tutorials Class - Output Window

16
5
[ 2, 4, 6 ]

An arrow function has no own this, no arguments, and cannot be used with new. See Arrow Functions.

What is a callback function in JavaScript?

A callback is a function passed as an argument to another function, which calls it later.

function process(name, callback) {
  console.log("Hello " + name);
  callback();
}

process("Robin", () => console.log("Done"));

setTimeout(() => console.log("After 1 second"), 1000);

Output:

Tutorials Class - Output Window

Hello Robin
Done
After 1 second

Callbacks are used for events, timers and array methods like map. Many nested callbacks become hard to read (callback hell), and promises solve that.

What is the DOM in JavaScript?

The DOM (Document Object Model) is a tree of objects that the browser creates from the HTML. Each tag becomes a node. JavaScript can use the DOM to read and change the content, style and structure of the page.

document.getElementById("title").textContent = "New title";

See JavaScript HTML DOM.

How do you select elements in the DOM?

MethodReturns
getElementById("id")One element
querySelector("css")First match of a CSS selector
querySelectorAll("css")All matches (NodeList)
getElementsByClassName("c")Live HTMLCollection of a class
const a = document.getElementById("title");
const b = document.querySelector(".note");
const all = document.querySelectorAll("p.note");

querySelector and querySelectorAll are the most flexible, because they use CSS selectors. See HTML DOM.

What are events and event listeners in JavaScript?

An event is something that happens on the page, like a click, a key press or a form submit. An event listener is a function that runs when the event happens.

button.addEventListener("click", (event) => {
  console.log("Clicked: " + event.target.id);
});

You can add many listeners to one event. See DOM EventListener.

What is JSON?

JSON (JavaScript Object Notation) is a light text format for data. It is used by almost all web APIs.

const obj = { name: "Robin", age: 25 };
const text = JSON.stringify(obj);
console.log(text);
console.log(JSON.parse(text).name);

Output:

Tutorials Class - Output Window

{"name":"Robin","age":25}
Robin

Keys and strings must use double quotes. See JavaScript JSON.

What are template literals in JavaScript?

const name = "Robin";
const age = 25;

console.log(`Name: ${name}, age next year: ${age + 1}`);
console.log(`Line 1
Line 2`);

Output:

Tutorials Class - Output Window

Name: Robin, age next year: 26
Line 1
Line 2

Backticks give string interpolation with ${ } and allow multi-line strings. See JavaScript Strings.

What is the difference between map and forEach?

const nums = [1, 2, 3];

const doubled = nums.map(n => n * 2);
const result = nums.forEach(n => console.log(n));

console.log(doubled);
console.log(result);

Output:

Tutorials Class - Output Window

1
2
3
[ 2, 4, 6 ]
undefined

Use map when you want a new array. Use forEach when you only want to do something for each item. See Array Methods.

What is the difference between slice and splice?

const a = [1, 2, 3, 4, 5];
console.log(a.slice(1, 3));
console.log(a);

const removed = a.splice(1, 2);
console.log(removed);
console.log(a);

Output:

Tutorials Class - Output Window

[ 2, 3 ]
[ 1, 2, 3, 4, 5 ]
[ 2, 3 ]
[ 1, 4, 5 ]

slice(start, end) is non-destructive. splice(start, count, ...items) changes the array. See JavaScript Arrays.

What is the difference between var, let and const?

Pointvarletconst
ScopeFunctionBlockBlock
ReassignYesYesNo
RedeclareYesNoNo
HoistingHoisted, value undefinedHoisted, but unusable before declarationSame as let
if (true) {
  var a = 1;
  let b = 2;
}
console.log(a);
console.log(b);

Output:

Tutorials Class - Output Window

1
ReferenceError: b is not defined

Use const by default, let if the value must change, and avoid var. See JavaScript Variables and Scope.

What is hoisting in JavaScript?

Hoisting means that declarations are moved to the top of their scope before the code runs.

console.log(x);   // undefined (var is hoisted, value is not)
var x = 5;

sayHi();           // works: function declarations are fully hoisted
function sayHi() {
  console.log("Hi");
}

Output:

Tutorials Class - Output Window

undefined
Hi

let and const are hoisted too, but using them before the declaration throws a ReferenceError (the temporal dead zone). See JavaScript Scope.

What are truthy and falsy values in JavaScript?

In a condition JavaScript treats every value as true or false. The falsy values are: false, 0, "", null, undefined and NaN. Everything else is truthy.

console.log(Boolean(""));
console.log(Boolean("0"));
console.log(Boolean([]));
console.log(Boolean(0));

Output:

Tutorials Class - Output Window

false
true
true
false

See Type Conversion.

What is the difference between localStorage, sessionStorage and cookies?

PointlocalStoragesessionStorageCookies
LifetimeUntil deletedUntil the tab closesUntil the expiry date
SizeAbout 5 MBAbout 5 MBAbout 4 KB
Sent to serverNoNoYes, with every request
localStorage.setItem("theme", "dark");
console.log(localStorage.getItem("theme"));

Output:

Tutorials Class - Output Window

dark

Do not store passwords in any of them. See JavaScript Local Storage.