Top 50 JavaScript Interview Questions For Beginners
Top 50 JavaScript Interview Questions For Beginners
Beginners
Variables and Data Types
1. What are the JavaScript data types?
JavaScript values can be primitive or objects. According to MDN, there are 7 primitive types: string ,
number , bigint , boolean , undefined , symbol , and null 1 . All other values (arrays,
functions, objects) are reference types (non-primitive). For example, 42 is a number, "hello" is a string,
and {} is an object.
Common mistakes: Confusing null and undefined , or forgetting that arrays are objects (not a
separate primitive type).
if (true) {
var a = 1;
let b = 2;
const c = 3;
}
[Link](a); // 1 (var is not block-scoped)
[Link](b); // ReferenceError (b is not defined outside block)
Common mistakes: Redeclaring a let or const in the same scope causes errors, and forgetting that
const must be initialized at declaration.
1
3. What is hoisting in JavaScript?
Hoisting is JavaScript’s behavior of moving declarations to the top of their scope. For example, a var
declaration is hoisted and initialized to undefined before code execution, whereas let / const are
hoisted but not initialized 3 . This means you can refer to a var -declared variable before its declaration
(it will be undefined ), but doing so with let / const throws a ReferenceError.
Common mistakes: Assuming let / const are not hoisted or that hoisting brings initialization. In reality,
only var gets an initial undefined value on hoist 3 .
MDN notes that NaN is not equal to itself, so comparisons with NaN (like NaN == NaN ) are always false
4 .
Common mistakes: Relying on == can lead to unexpected true results (e.g. null == undefined is
true, but null === undefined is false 5 ). Best practice is to use === to avoid type-coercion
surprises.
Common mistakes: Assuming values like 0 , empty string "" , or NaN are truthy – they are actually falsy
6 . Also, forgetting that objects and non-empty strings are truthy.
2
absence of any object value 8 . Semantically, undefined means “no value assigned” and null means
“no object (value intentionally set to nothing)” 9 . Example:
let a;
[Link](a); // undefined (never assigned)
let b = null;
[Link](b); // null (explicitly set to nothing)
Common mistakes: Using == to compare them: null == undefined is true, but null ===
undefined is false 5 . Also, note that typeof null returns "object" (a long-standing JS quirk) 5 .
typeof 5; // "number"
typeof "hello"; // "string"
typeof true; // "boolean"
typeof {}; // "object"
typeof null; // "object" (quirk)
Common mistakes: Expecting typeof null to be "null" . Also, arrays and functions are "object"
as well ( typeof [] === "object" , typeof function(){} === "function" ).
A common trick is to test value !== value , which is true only for NaN 12 .
Common mistakes: Using == or === to detect NaN (they never match). Also, isNaN() coerces
values, so isNaN("123") is false but isNaN("abc") is true. [Link]() is safer because it
returns true only if the value is actually NaN .
3
Functions
9. How do you declare a function in JavaScript?
JavaScript functions can be declared using a function declaration or function expression. According to MDN,
“Functions are one of the fundamental building blocks in JavaScript” 13 . A function declaration uses the
function keyword with a name:
function greet(name) {
return `Hello, ${name}!`;
}
This type of function is hoisted and can be called before its definition. A function expression defines a
function inside an expression (often anonymous) and assigns it to a variable:
Function expressions are not hoisted in the same way, so calling add(…) before its assignment will cause
an error.
Common mistakes: Forgetting parentheses when calling, or not understanding hoisting differences. For
example, calling a function expression before its definition will throw a ReferenceError.
10. What is an arrow function and how does it differ from a normal function?
Arrow functions are a concise ES6 syntax for function expressions. MDN describes an arrow function as “a
compact alternative to a traditional function expression, with some semantic differences and limitations” 14 .
Syntax uses => , for example:
This is shorter than function(a, b) { return a * b; } . A key difference is that arrow functions do
not have their own this (they inherit this from the surrounding scope) and cannot be used as
constructors 15 . They also do not have their own arguments object or super .
const obj = {
x: 10,
getX: () => this.x
};
[Link]([Link]()); // undefined (because arrow's `this` is not `obj`)
Common mistakes: Using an arrow function as an object method expecting this to refer to the object.
Also, forgetting that arrow functions with one expression implicitly return that expression (no return
needed), but when using block body, you must use return .
4
11. What are default parameters in functions?
ES6 allows specifying default values for function parameters. MDN explains that “default function parameters
allow named parameters to be initialized with default values if no value or undefined is passed” 16 . For
example:
If you call greet(undefined) , it also uses "Guest" . This avoids having to write name = name ||
"Guest"; inside the function.
Common mistakes: Expecting default parameters to apply when passing null or other falsy values. In
reality, the default is used only if the argument is omitted or undefined , not for other falsy values.
function makeAdder(x) {
return function(y) {
return x + y; // `x` is from the outer scope
};
}
5
const add5 = makeAdder(5);
[Link](add5(3)); // 8 (5 from closure + 3)
const obj = {
a: 10,
regularFunc: function() { [Link](this.a); },
arrowFunc: () => [Link](this.a)
};
[Link](); // 10 (this refers to obj)
[Link](); // undefined (this is not obj, but inherited from global
scope)
Common mistakes: Using an arrow function as an object method and expecting this to refer to the
object. Remember that arrow functions are better for callbacks where a consistent this is needed from
outer scope.
Arrays have a .length property and can hold elements of any type.
Common mistakes: Treating arrays like regular objects (for example, using object property syntax). Also,
forgetting that array indices start at 0.
6
const person = { name: "Alice", age: 30 };
Arrays have array-specific methods like .push() and .map() , while objects use keys and methods like
[Link]() .
Common mistakes: Treating an array like an object (e.g. iterating with for..in ) or vice versa. Remember
that typeof [] === "object" , so use [Link]() to check for arrays.
Common mistakes: Using the wrong end (e.g. push vs unshift ), or forgetting that .push() and
.unshift() modify the original array and return the new length (not the array).
19. How can you iterate over an array? (for, forEach, etc.)
There are several ways to loop through array elements. A classic for loop:
7
for (const num of nums) {
[Link](num);
}
Arrays also have built-in methods like .forEach() , .map() , .filter() , etc. For example,
[Link](n => [Link](n)); executes the callback for each element. MDN explains that
forEach() “executes a provided function once for each array element” 21 .
Common mistakes: Modifying the array inside a forEach callback can lead to unexpected results. Also,
forEach returns undefined , so don’t expect a value from it (use map if you need a new array).
20. What is the difference between map() and forEach() for arrays?
Both map() and forEach() execute a function on each element. The key difference is that .map()
returns a new array of the return values, whereas .forEach() returns undefined 21 22 . Use
map() when you want to transform each element and get the new array:
Use forEach() when you just want to perform side effects (logging, modifying external variables, etc.):
Common mistakes: Expecting forEach to produce an array (it doesn’t) or forgetting to return a value in
map() (resulting in an array of undefined ).
8
const { name: n, city = "Unknown" } = person;
Common mistakes: Mixing up array and object syntax. Array destructuring is position-based; object
destructuring uses property names. Also, forgetting that missing values become undefined , unless a
default is provided.
MDN notes that spread “expands” an array into its elements and copies object properties into new objects
24 .
Common mistakes: Using spread on non-iterables (e.g. spreading a plain object in an array literal throws a
TypeError) 25 , or confusing spread with rest syntax (they look the same but serve opposite purposes).
To parse a JSON string back into a JavaScript value or object, use [Link](jsonString) , which
“parses a JSON string, constructing the JavaScript value or object described by the string.” 27 . For example:
Common mistakes: Forgetting that [Link]() can throw an error on invalid JSON (should often be
used inside try/catch ). Also, [Link]() does not serialize functions or symbol properties –
they are omitted.
9
DOM Manipulation
24. What is the DOM (Document Object Model)?
The DOM is a programming interface that represents a web page as a tree of objects, allowing scripts to
read and manipulate the content, structure, and style of the page. MDN explains: “The Document Object
Model (DOM) is a programming interface for web documents. It represents the page so that programs can change
the document structure, style, and content.” 28 . In practice, the browser creates a DOM tree of HTML
elements, and JavaScript can traverse and modify this tree (e.g. adding or changing elements).
Common mistakes: Treating the result of querySelectorAll (a NodeList ) as a regular array (it’s
iterable but lacks some array methods). Also, forgetting that getElementById is case-sensitive to the
exact id .
const p = [Link]("p");
[Link] = "Hello, world!"; // sets plain text
[Link] = "<strong>Bold</strong>"; // sets HTML content
10
[Link]("active"); // removes "active" class
[Link]("active"); // toggles the class on/off
28. How do you create a new DOM element and append it to the document?
Use [Link]() to make a new element, then use methods like appendChild() or
append() to add it. Example:
This creates a new <li> element, sets its text, and appends it as a child of the <ul> .
Common mistakes: Forgetting to append the element, or appending it to the wrong parent. Also, note that
appendChild always appends at the end; use insertBefore if you need to insert at a specific position.
[Link] = firstHandler;
[Link] = secondHandler;
11
// Only secondHandler will run on click
[Link]("click", firstHandler);
[Link]("click", secondHandler);
// Both handlers will run on click
Common mistakes: Using onclick thinking you can register more than one listener (you can’t). Also,
addEventListener is case-sensitive and requires the full event name (e.g. "click" , not "onclick" ).
[Link]("ul").addEventListener("click", function(e) {
[Link]([Link]); // the <li> that was clicked
});
[Link] is useful for identifying which element was clicked when using event delegation. Other
useful properties include [Link] (element with the listener) and [Link] for
keyboard events.
Common mistakes: Confusing target and currentTarget . Also, accessing this inside a normal
event handler is the same as currentTarget , but with arrow functions this may not refer to the
element as expected.
Common mistakes: Forgetting to pass the event object to the handler ( function(e) ), or
misunderstanding that preventDefault() only stops the default action, not event propagation.
12
“prevents further propagation of the current event in the capturing and bubbling phases.” 34 . For example, if
you have nested elements with click handlers, calling stopPropagation() in the inner handler stops the
outer handlers from firing.
Common mistakes: Confusing preventDefault() with stopPropagation() . The former stops
default browser behavior (like navigation), while the latter stops the event from moving up (or down) the
DOM tree.
This initializes i = 0 , checks i < 5 , runs the loop body, then runs i++ after each iteration.
Common mistakes: Forgetting to increment/decrement i , causing infinite loops, or misplacing the
semicolons in the for loop syntax.
This loop goes through each element in nums . for...of works on any iterable, including Map , Set ,
and even strings (yielding each character).
Common mistakes: Trying to use for...of on non-iterables (like plain objects) causes an error. For
objects, use for...in (see next).
13
If used on arrays (not recommended), it iterates over indices as strings.
Common mistakes: Using for...in on arrays can yield unexpected keys (including inherited ones);
prefer for...of or regular for for arrays. Also, do not rely on property order in for...in .
let n = 0;
while (n < 3) {
[Link](n);
n++;
}
This checks conditions in order and runs the first matching block.
Common mistakes: Forgetting the braces {} for multi-line blocks, or omitting the final else (leading to
grade possibly staying undefined if no condition matched).
39. What is the ternary ( ?: ) operator and how do you use it?
The ternary operator is a shorthand for if...else . It has the form condition ? exprIfTrue :
exprIfFalse . Example:
This sets max to a if a > b is true, otherwise to b . It’s useful for simple conditional assignments.
Common mistakes: Trying to put complex logic inside a ternary, which hurts readability. Also, forgetting
the colon or using = inside the expressions will cause errors.
14
40. How does a switch statement work?
A switch evaluates an expression and runs code based on matching cases:
switch(day) {
case "Mon":
[Link]("Start of week");
break;
case "Fri":
[Link]("End of week");
break;
default:
[Link]("Middle of week");
}
Each case compares with === . The break prevents “fall-through” to the next case. The default case
runs if none match.
Common mistakes: Forgetting break causes execution to continue into the next case. Also, using
expressions instead of constant values in case (they should be literal or constant).
15
args = [1, 2, 3]; , you can call func(...args) instead of func(1, 2, 3) . This is effectively the
same as using [Link]() . It is often used to pass array elements as individual
parameters.
Common mistakes: Passing non-array values to spread, or exceeding the maximum call stack size by
spreading a very large array as arguments.
try {
const obj = [Link](invalidJson);
} catch (e) {
[Link]("Invalid JSON:", e);
}
You can also use finally for code that runs regardless of success/failure.
Common mistakes: Forgetting to wrap code that may throw in try . Also, using throw inside try
without a catch causes it to propagate upward unless caught.
function getUser(id) {
if (id < 0) {
throw new Error("ID must be non-negative");
}
// ...
}
16
47. What is the difference between isNaN() and [Link]() ?
isNaN(value) converts the value to a number and then tests if it is NaN , so non-numeric strings will
also return true (e.g. isNaN("foo") is true). [Link](value) is more strict: it returns true only
if the value is already NaN (and of type Number). As MDN shows, [Link]("hello") is false
while isNaN("hello") is true 37 . Use [Link]() when you want to avoid the coercion that
isNaN() does.
Common mistakes: Using isNaN() on things like empty strings or non-numeric values without realizing
they get coerced to NaN .
Common mistakes: Using for...in on arrays and expecting numeric values. Also, for...of does not
work on plain objects (only iterables).
(function() {
[Link]("IIFE runs immediately");
})();
This function runs right away and its variables do not pollute the outer scope. With ES6 modules and block
scope, IIFEs are less common, but they were frequently used to simulate private scope in older JS.
Common mistakes: Forgetting the extra parentheses that turn a function declaration into an expression.
For example, function(){...}() without wrapping parentheses will cause a syntax error.
50. What are common errors when preparing for JavaScript interviews? (Bonus)
Beginners often stumble on scoping issues (misusing var vs let ), hoisting surprises, and event
handling pitfalls. It’s crucial to understand how asynchronous callbacks work and the difference between
assignment ( = ) and comparison ( == / === ). Always test edge cases (e.g., empty arrays, null values)
and practice writing small code snippets to solidify each concept.
Sources: Authoritative documentation from MDN and other resources have been cited throughout for
accuracy (see references). Each answer explanation is supported by official or community-trusted sources as
indicated.
17
1 Primitive - Glossary | MDN
[Link]
18
27 [Link]() - JavaScript | MDN
[Link]
19