0% found this document useful (0 votes)
12 views19 pages

Top 50 JavaScript Interview Questions For Beginners

The document outlines the top 50 JavaScript interview questions for beginners, covering essential topics such as variables, data types, functions, and arrays. Key concepts include the differences between var, let, and const, hoisting, truthy vs. falsy values, and the use of callback functions and closures. It also highlights common mistakes and best practices for each topic to help candidates prepare for interviews.

Uploaded by

asfg6630
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views19 pages

Top 50 JavaScript Interview Questions For Beginners

The document outlines the top 50 JavaScript interview questions for beginners, covering essential topics such as variables, data types, functions, and arrays. Key concepts include the differences between var, let, and const, hoisting, truthy vs. falsy values, and the use of callback functions and closures. It also highlights common mistakes and best practices for each topic to help candidates prepare for interviews.

Uploaded by

asfg6630
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Top 50 JavaScript Interview Questions for

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.

let str = "hello"; // string


let num = 42; // number
let flag = true; // boolean
let nothing = null; // null (intentional absence of value)
let undef; // undefined (no value assigned)

Common mistakes: Confusing null and undefined , or forgetting that arrays are objects (not a
separate primitive type).

2. What is the difference between var , let , and const ?


MDN explains that var is function-scoped while let and const are block-scoped 2 . Also, var
declarations are hoisted and initialized as undefined , whereas let / const are hoisted but not
initialized (they are in a “temporal dead zone” until assigned) 3 . Variables declared with var or let can
be reassigned, but const cannot be reassigned. Additionally, var allows re-declaration in the same
scope, whereas let and const do not 2 .

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.

[Link](x); // undefined (due to hoisting)


var x = 5;

[Link](y); // ReferenceError (y is not initialized yet)


let y = 3;

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 .

4. How do == and === differ?


The double-equals == operator performs type coercion before comparing, while triple-equals ===
compares both value and type without conversion 4 . That is, == might convert the operands to a
common type, but === requires them to be the same type to return true. For example:

[Link](5 == '5'); // true (string '5' is converted to number 5)


[Link](5 === '5'); // false (different types)

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.

5. What are truthy and falsy values?


In JavaScript, a falsy value is one that converts to false in a Boolean context. The falsy values include
false , 0 , -0 , 0n (BigInt zero), "" (empty string), null , undefined , and NaN 6 . Anything not
on that list is truthy. For example:

if (0) [Link]("This won't run"); // 0 is falsy


if ("0") [Link]("This will run"); // "0" (non-empty string) is truthy

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.

6. What is the difference between null and undefined ?


According to MDN, undefined is a primitive value automatically assigned to variables that have been
declared but not given a value 7 , whereas null is a primitive value that represents the intentional

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 .

7. What is the typeof operator and its quirks?


The typeof operator returns a string indicating the type of its operand. For primitive types it returns
"string" , "number" , "boolean" , "undefined" , or "symbol" . For objects (including null ), it
returns "object" . Notably, typeof null is "object" due to historical reasons (MDN calls this a bug)
5 . For example:

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" ).

8. What is NaN and how do you check for it?


NaN stands for “Not-a-Number” and is a special numeric value representing an invalid number result (e.g.
0/0 or parseInt("abc") ). MDN states that NaN is the only value in JavaScript that is not equal to
itself 10 . To check for NaN , you can use [Link](value) or isNaN(value) , keeping in mind
their differences 11 . Example:

[Link](NaN === NaN); // false


[Link]([Link](NaN)); // true
[Link](isNaN("hello")); // true (because "hello" coerces to NaN)
[Link]([Link]("hello")); // false (strict check only for actual NaN)

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:

const add = function(x, y) {


return x + y;
};

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:

const multiply = (a, b) => a * b;

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:

function greet(name = "Guest") {


[Link](`Hello, ${name}!`);
}
greet(); // "Hello, Guest!"
greet("Alice"); // "Hello, Alice!"

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.

12. What is a callback function?


A callback is a function passed as an argument to another function, which is then invoked inside the outer
function. MDN defines it as “a function passed into another function as an argument, which is then invoked
inside the outer function” 17 . Callbacks are used for asynchronous operations (e.g. setTimeout ), event
handlers, or array iteration. Example with forEach :

const nums = [1, 2, 3];


[Link](function(n) {
[Link](n * 2);
});
// 2, 4, 6

Here the function (n) => [Link](n * 2) is a callback to forEach .


Common mistakes: Forgetting to call the callback inside the function, or not handling asynchronous order
correctly. For example, mixing up callback signature or missing an argument can cause unexpected
behavior.

13. What is a closure in JavaScript?


A closure is when a function “remembers” its lexical scope even when executed outside that scope. MDN
defines a closure as “the combination of a function bundled together with references to its surrounding state (the
lexical environment)” 18 . In other words, an inner function keeps access to the variables of its outer function
even after the outer has returned. Example:

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)

Here add5 is a closure that remembers x = 5 .


Common mistakes: Not realizing that each call creates a new closure. Also, using loop variables in closures
can be tricky (often solved with let to get block scope).

14. What is the this keyword in JavaScript?


The value of this depends on how a function is called. In a normal function, this refers to the global
object (or undefined in strict mode), and in a method, it refers to the object owning the method.
However, arrow functions do not have their own this binding; MDN notes that “Arrow functions don’t have
their own bindings to this ” 15 . Instead, an arrow’s this is inherited from the enclosing (lexical) scope.
For example:

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 and Objects


15. What is an array and how do you declare it?
An array is an ordered list-like object in JavaScript. MDN describes arrays as “list-like objects; they are basically
single objects that contain multiple values stored in a list” 19 . You can declare an array using brackets:

const fruits = ["apple", "banana", "cherry"];


const numbers = [1, 2, 3, 4, 5];

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.

16. What is an object and how do you create one?


A JavaScript object is a collection of key-value pairs. GeeksforGeeks notes “JavaScript objects are collections of
properties, where each property is defined as a key-value pair.” 20 . You can create an object using curly braces:

6
const person = { name: "Alice", age: 30 };

You access properties with dot or bracket notation: [Link] or person["name"] .


Common mistakes: Confusing object syntax for arrays ( {} vs [] ), or forgetting to use quotes around
string keys if using bracket notation.

17. What is the difference between arrays and objects?


Arrays are a special kind of object optimized for ordered lists and have numeric indices starting from 0.
Objects are unordered collections of key-value pairs with string (or symbol) keys. In essence, “arrays are
generally described as ‘list-like objects’” 19 , whereas objects have named properties. For example:

const arr = [10, 20, 30]; // arr[1] is 20


const obj = { a: 10, b: 20 }; // obj["b"] is 20

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.

18. How do you add or remove items from an array?


You can use array methods: .push() adds to the end, .pop() removes from the end, .unshift()
adds to the front, and .shift() removes from the front. Example:

let nums = [1, 2, 3];


[Link](4); // [1, 2, 3, 4]
[Link](); // [1, 2, 3] (pop returns 4)
[Link](0); // [0, 1, 2, 3]
[Link](); // [1, 2, 3] (shift returns 0)

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:

for (let i = 0; i < [Link]; i++) {


[Link](nums[i]);
}

ES6 introduced for...of to iterate values directly:

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:

const nums = [1, 2, 3];


const doubled = [Link](n => n * 2);
[Link](doubled); // [2, 4, 6]

Use forEach() when you just want to perform side effects (logging, modifying external variables, etc.):

[Link](n => [Link](n * 2)); // logs 2,4,6

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 ).

21. How do you use destructuring for arrays/objects?


Destructuring syntax unpacks values from arrays or properties from objects into variables. MDN says
destructuring “makes it possible to unpack values from arrays, or properties from objects, into distinct
variables” 23 . Example with arrays:

const coords = [10, 20];


const [x, y] = coords;
[Link](x, y); // 10, 20

Example with objects:

const person = { name: "Bob", age: 25 };


const { name, age } = person;
[Link](name, age); // "Bob", 25

You can also rename or use defaults:

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.

22. What is the spread ( ... ) operator?


The spread operator ... allows an iterable (like an array) to be expanded in places where multiple
arguments or elements are expected 24 . For example, spreading an array into a function call or another
array:

const arr = [1, 2, 3];


[Link]([Link](...arr)); // same as [Link](1,2,3)
const arr2 = [...arr, 4, 5]; // [1,2,3,4,5]

For objects (ES2018+), spreading copies properties into a new object:

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


const obj2 = {...obj, c:3}; // {a:1, b:2, c:3}

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).

23. How do you convert between JSON and objects?


To convert a JavaScript object to a JSON string, use [Link](value) , which “converts a JavaScript
value to a JSON string” 26 . Example:

const data = { result: true, count: 42 };


const jsonStr = [Link](data);
[Link](jsonStr); // '{"result":true,"count":42}'

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:

const parsed = [Link]('{"count":42,"result":true}');


[Link]([Link]); // 42

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).

25. How do you select elements in the DOM?


You can select elements by ID, class, tag, or CSS selector. Common methods include
[Link]("myId") , [Link]("myClass") , or using
the more versatile querySelector / querySelectorAll . For example,
[Link]("#myId") returns the first element matching the CSS selector #myId , and
querySelectorAll("p") returns a list of all <p> elements 29 30 . MDN notes querySelector()
“returns the first Element within the document that matches the specified CSS selectors”, or null if none 29 .

const header = [Link]("h1");


const items = [Link](".item"); // NodeList of elements
[Link]([Link]);

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 .

26. How do you change the text or HTML content of an element?


You can use properties like .textContent , .innerText , or .innerHTML . For example:

const p = [Link]("p");
[Link] = "Hello, world!"; // sets plain text
[Link] = "<strong>Bold</strong>"; // sets HTML content

- .textContent and .innerText set the visible text.


- .innerHTML sets HTML markup inside the element.
Common mistakes: Using innerHTML with untrusted content can introduce security issues (XSS). Also,
setting .innerText vs .textContent differences ( innerText is aware of styling and can be slower).

27. How do you add or remove a CSS class on an element?


You can use the classList API. For example:

const btn = [Link]("button");


[Link]("active"); // adds "active" class

10
[Link]("active"); // removes "active" class
[Link]("active"); // toggles the class on/off

Common mistakes: Manually concatenating to [Link] can overwrite existing classes.


classList is the recommended approach for adding/removing/toggling classes cleanly.

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:

const list = [Link]("ul");


const newItem = [Link]("li");
[Link] = "New item";
[Link](newItem);

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.

Events and Event Handling


29. How do you attach an event listener to an element?
Use addEventListener() on the element. MDN describes it as “sets up a function that will be called
whenever the specified event is delivered to the target.” 31 . For example:

const btn = [Link]("button");


[Link]("click", function(event) {
[Link]("Button clicked!");
});

This registers a callback for the "click" event on btn .


Common mistakes: Using the older onclick property only allows one handler per event, whereas
addEventListener can register multiple handlers. Also, forgetting to call [Link]()
inside the listener if you want to stop default behavior.

30. What is the difference between using onclick and addEventListener ?


Setting [Link] = handler overwrites any existing click handler on that element. In contrast,
[Link]("click", handler) allows multiple handlers and offers more control
(options like capturing vs bubbling). MDN actually recommends addEventListener() for flexibility 32 .
For example:

[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" ).

31. How do you use the event object (e.g. [Link] )?


When an event handler is called, it receives an event object containing details. A common property is
[Link] , which is the element that triggered the event. Example:

[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.

32. What does [Link]() do?


Calling [Link]() inside an event handler tells the browser not to perform the element’s
default action. For example, on a link click, it stops navigation; on form submission, it stops the submission.
MDN notes it “tells the user agent that the event is being explicitly handled, so its default action…should not be
taken” 33 . Example:

<a href="[Link] id="link">Click me</a>

const link = [Link]("link");


[Link]("click", function(e) {
[Link]();
[Link]("Navigation prevented.");
});

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.

33. What does [Link]() do?


[Link]() prevents the event from bubbling (or capturing) further. MDN states it

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.

Loops and Conditionals


34. How does a for loop work?
A for loop runs a block of code a certain number of times. Syntax: for (initialization;
condition; afterthought) { /* code */ } . For example:

for (let i = 0; i < 5; i++) {


[Link](i); // 0,1,2,3,4
}

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.

35. How does a for...of loop work?


A for...of loop iterates over iterable objects (like arrays or strings), giving each value in turn. Example:

const nums = [10, 20, 30];


for (const num of nums) {
[Link](num); // 10, 20, 30
}

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).

36. How does a for...in loop work?


A for...in loop iterates over enumerable property keys of an object (or array indices). For example:

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


for (const key in obj) {
[Link](key, obj[key]); // "a" 1, then "b" 2
}

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 .

37. How does a while loop work?


A while loop repeats as long as a condition is true. Syntax:

let n = 0;
while (n < 3) {
[Link](n);
n++;
}

This logs 0, 1, 2. The condition ( n < 3 ) is checked before each iteration.


Common mistakes: Forgetting to update the loop variable ( n++ above) leads to infinite loops. If you want
to guarantee at least one run, use a do...while instead.

38. What is an if...else if...else statement?


Conditional statements execute code based on truthiness.

if (score >= 90) {


grade = "A";
} else if (score >= 80) {
grade = "B";
} else {
grade = "C";
}

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:

const max = a > b ? a : b;

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).

ES6+ (Modern JavaScript) Features


41. What are template literals and how do you use them?
Template literals are string literals using backticks ( ` ) that allow embedded expressions and multi-line
strings. MDN explains that they “are literals delimited with backtick characters, allowing for multi-line strings,
string interpolation with embedded expressions” 35 . Example:

const name = "Charlie";


[Link](`Hello, ${name}!`); // Hello, Charlie!
const multiLine = `Line1
Line2`;
[Link](multiLine);

You can embed any expression inside ${...} .


Common mistakes: Forgetting backticks and using quotes instead. Also, not realizing that template literals
can contain actual newlines without \n .

42. What is the difference between let / const and var ?


This was covered in question 2, but briefly: ES6 let and const introduce block scope, whereas var is
function-scoped 2 . const also forbids reassignment. Remember that var variables are hoisted and
initialized as undefined , while let / const are hoisted but uninitialized (causing a ReferenceError if
accessed too early) 3 .

43. What is the spread operator in function calls?


The spread operator can also expand an array into arguments of a function. For example, given const

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.

44. How do you handle errors in JavaScript? (try/catch)


Use try...catch to handle runtime errors. MDN describes: “The try...catch statement is comprised of a try
block and either a catch block... The code in the try block is executed first, and if it throws an exception, the code in
the catch block will be executed” 36 . Example:

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.

45. How do you throw a custom error?


You can throw errors using throw and the Error constructor:

function getUser(id) {
if (id < 0) {
throw new Error("ID must be non-negative");
}
// ...
}

This will create a TypeError that can be caught by a try/catch .


Common mistakes: Throwing non-Error types (e.g. throwing a string) is allowed but not recommended.
Always throw an Error (or subclass) for consistency.

46. How do parseInt() and parseFloat() work?


parseInt(string, radix) parses a string and returns an integer of the specified radix (base), stopping
at the first non-digit character. For example, parseInt("10px") gives 10 . Always provide the radix (e.g.
parseInt("10", 10) ) to avoid confusion.
parseFloat(string) parses a string and returns a floating-point number, reading up to the first invalid
character. For example, parseFloat("3.14abc") returns 3.14 .
Common mistakes: Not passing the radix to parseInt (it can behave unexpectedly if the string starts
with 0 or 0x ). Also, parseInt("12.34") returns 12 (it stops at the decimal point).

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 .

48. What is the difference between for...in and for...of loops?


(Asked again here for emphasis.) In short, for...in iterates over object keys (including array indices as
strings), whereas for...of iterates over iterable values (like array elements, string characters, etc.). For
arrays, prefer for...of . For objects, use for...in or other methods. Example:

const arr = [1,2,3];


for (let index in arr) { [Link](index); } // 0,1,2
for (let value of arr) { [Link](value); } // 1,2,3

Common mistakes: Using for...in on arrays and expecting numeric values. Also, for...of does not
work on plain objects (only iterables).

49. What is an Immediately Invoked Function Expression (IIFE)?


An IIFE is a function expression that is defined and immediately called. It is often used to create a new
scope. For example:

(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]

2 3 Var, Let, and Const – What's the Difference?


[Link]

4 Equality comparisons and sameness - JavaScript | MDN


[Link]

5 8 9 null - JavaScript | MDN


[Link]

6 Falsy - Glossary | MDN


[Link]

7 Undefined - Glossary | MDN


[Link]

10 11 12 37 NaN - JavaScript | MDN


[Link]

13 Functions - JavaScript | MDN


[Link]

14 15 Arrow function expressions - JavaScript | MDN


[Link]

16 Default parameters - JavaScript | MDN


[Link]

17 Callback function - Glossary | MDN


[Link]

18 Closures - JavaScript | MDN


[Link]

19 Arrays - Learn web development | MDN


[Link]

20 JavaScript Object Properties - GeeksforGeeks


[Link]

21 [Link]() - JavaScript | MDN


[Link]

22 [Link]() - JavaScript | MDN


[Link]

23 Destructuring - JavaScript | MDN


[Link]

24 25 Spread syntax (...) - JavaScript | MDN


[Link]

26 [Link]() - JavaScript | MDN


[Link]

18
27 [Link]() - JavaScript | MDN
[Link]

28 30 Document Object Model (DOM) - Web APIs | MDN


[Link]

29 Document: querySelector() method - Web APIs | MDN


[Link]

31 32 EventTarget: addEventListener() method - Web APIs | MDN


[Link]

33 Event: preventDefault() method - Web APIs | MDN


[Link]

34 Event: stopPropagation() method - Web APIs | MDN


[Link]

35 Template literals (Template strings) - JavaScript | MDN


[Link]

36 try...catch - JavaScript | MDN


[Link]

19

You might also like