JavaScript ES6 Interview Preparation Notes
JavaScript ES6 Interview Preparation Notes
Introduction
This document provides a comprehensive overview of the JavaScript programming
language, designed to serve as preparatory notes for technical interviews. It
systematically covers fundamental concepts, key features introduced in ECMAScript
2015 (ES6), asynchronous programming paradigms, advanced topics often
encountered in complex applications, and concludes with a selection of tricky
interview questions with detailed explanations. The aim is to equip candidates with a
robust understanding of JavaScript's core mechanics and modern capabilities.
Understanding the differences in scoping and hoisting between var, let, and const is
crucial for writing predictable and maintainable code.7
Type Coercion: JavaScript often implicitly converts values from one type to another
(e.g., string to number) during operations, a process called type coercion.10 This can
lead to unexpected results, especially with the loose equality operator (==).22 Explicit
type conversion can be done using functions like Number(), String(), Boolean().18
1.3. Operators
Operators perform actions on values (operands).
● Arithmetic Operators: +, -, *, /, % (remainder), ** (exponentiation).6
● Assignment Operators: =, +=, -=, *=, /=, %=, **=.6
● Comparison Operators:
○ Strict Equality: === (checks value and type), !== (checks value and type).6
Generally preferred to avoid type coercion issues.7
○ Loose Equality: == (checks value, performs type coercion), != (checks value,
performs type coercion).6
○ Relational: >, <, >=, <=.6
● Logical Operators: && (AND), || (OR), ! (NOT).6 Used for combining boolean
expressions or for short-circuiting.
● Bitwise Operators: Operate on binary representations (&, |, ^, ~, <<, >>, >>>).6
● Conditional (Ternary) Operator: condition? valueIfTrue : valueIfFalse.6 A concise
alternative to simple if...else statements.
● typeof Operator: Returns a string indicating the type of an operand.11
● instanceof Operator: Checks if an object is an instance of a particular
constructor or class.18
● Arrow Functions (ES6): Provide a concise syntax, especially for simple functions.
They do not have their own this binding (lexical this) and lack the arguments
object.6 Covered further in Section 2.
JavaScript
const subtract = (a, b) => a - b;
● Parameters vs. Arguments: Parameters are the names listed in the function
definition; arguments are the actual values passed to the function when called.6
Arguments are passed by value.28
● Return Value: Functions implicitly return undefined unless a return statement
specifies a value.3
● Immediately Invoked Function Expression (IIFE): A function expression that is
defined and executed immediately. Often used to create a private scope.16
JavaScript
(function() {
// Code runs immediately, creates a private scope
var privateVar = "secret";
console.log("IIFE executed!");
})();
1.6. Objects
Objects are collections of key-value pairs, where keys are usually strings (or Symbols)
and values can be any data type, including other objects or functions (methods).6
● Object Literals: A common way to create objects using curly braces {}.6
JavaScript
const person = {
firstName: "Ada",
lastName: "Lovelace",
birthYear: 1815,
calculateAge: function(currentYear) {
return currentYear - this.birthYear;
}
};
1.7. Arrays
Arrays are ordered, zero-indexed lists of values.35 They are a specialized type of
object.
● Creation: Using array literals `` (most common) or the Array constructor.
JavaScript
const fruits =;
const numbers = new Array(1, 2, 3);
● Accessing Elements: Using bracket notation with the index fruits (returns
"Apple").3
● Modifying Elements: fruits1 = "Blueberry";.3
● Properties & Methods:
○ length: Returns the number of elements.3
○ push() / pop(): Add/remove element from the end.3
○ shift() / unshift(): Add/remove element from the beginning.3
○ indexOf(): Find the index of an element.3
○ slice(): Returns a shallow copy of a portion of an array.4
○ splice(): Changes the contents of an array by removing or replacing existing
elements and/or adding new elements in place.4
○ join(): Joins elements into a string.3
○ forEach(): Executes a provided function once for each array element.8
○ map(): Creates a new array populated with the results of calling a provided
function on every element.8
○ filter(): Creates a new array with all elements that pass the test implemented
by the provided function.8
○ reduce(): Executes a reducer function on each element, resulting in a single
output value.36
○ some() / every(): Test whether at least one/all elements pass a test.13
○ includes() (ES6): Checks if an array contains a certain value.20
● Lexical this: Arrow functions do not have their own this binding. Instead, they
inherit this from the surrounding (enclosing) lexical scope at the time they are
defined.6 This simplifies scenarios involving callbacks or methods where
traditional functions would require .bind(this) or storing this in another variable.12
● No arguments Object: Arrow functions do not have their own arguments object.
Use rest parameters (...args) instead if you need to capture all arguments.30
● Not Suitable for Methods (Usually): Because of lexical this, arrow functions are
often unsuitable as object methods if the method needs to refer to the object
itself using this.32
● Cannot be used as Constructors: Arrow functions cannot be called with new.7
● Multi-line Strings: Template literals allow strings to span multiple lines without
needing special characters like \n.12
JavaScript
const multiLine = `This is line one.
This is line two.`;
Destructuring significantly reduces the code needed to access nested data and
improves readability.12
JavaScript
● Spread Syntax: Used in function calls, array literals, or object literals to expand
an iterable (like an array, string, or object) into individual elements or properties.6
○ Function Calls: Pass array elements as individual arguments.
JavaScript
constnums = [1, 5, 6];
console.log(Math.max(...nums)); // Equivalent to Math.max(1, 5, 2) -> Output: 5
● constructor: A special method for initializing instances created with new. Only
one constructor is allowed per class.47
● Methods: Functions defined within the class body become methods on the
class's prototype (Rectangle.prototype in the example).47
● static Methods/Properties: Belong to the class itself, not instances. Called using
ClassName.staticMethod().18
● Getters & Setters: Special methods for defining computed properties or
controlling access to properties.6
● Inheritance (extends and super): Use extends to create a subclass that inherits
from a superclass. Use super() within the subclass constructor to call the parent
constructor (required before using this in the subclass constructor). Use
super.methodName() to call parent methods.18
JavaScript
class Square extends Rectangle {
constructor(side) {
super(side, side); // Call parent constructor
this.side = side;
}
// Override parent method
getArea(){
console.log("Calculating square area...");
return super.getArea(); // Call parent method
}
}
Even though the class syntax provides a convenient abstraction, the underlying
mechanism remains prototypal inheritance.2 When a class Rectangle is defined,
JavaScript essentially creates a constructor function named Rectangle. Methods like
getArea are added to Rectangle.prototype. When new Rectangle() is called, a new
object is created, and its internal [[Prototype]] link is set to Rectangle.prototype.33 The
extends keyword sets up the prototype chain between the subclass prototype
(Square.prototype) and the superclass prototype (Rectangle.prototype).47 Therefore, a
deep understanding of prototypes (Section 4.3) remains essential even when primarily
using class syntax, as interviewers may probe this connection.7
○ Default Export: Export a single primary value from the module. Only one
default export is allowed per module.6
JavaScript
// mainComponent.js
export default class MainComponent { /*... */ }
● Set: A collection of unique values. Values can be of any type. The uniqueness is
determined using the SameValueZero algorithm (similar to ===, but NaN is
considered equal to NaN).18 Sets remember the insertion order of values.60
○ Key Methods/Properties: add(value), has(value), delete(value), clear(), size
property.60
○ Iteration: Sets are iterable. Use keys(), values() (same as keys), entries()
(yields [value, value]), forEach(), or for...of loops to iterate over values.60
○ Use Case: Easily remove duplicates from an array: const uniqueArr =;.36
JavaScript
const tags = new Set();
tags.add('javascript');
tags.add('es6');
tags.add('javascript'); // Ignored, already exists
console.log(tags.has('es6')); // Output: true
console.log(tags.size); // Output: 2
for (const tag of tags) {
console.log(tag);
}
● WeakMap / WeakSet: Special versions where keys (for WeakMap) or values (for
WeakSet) must be objects. They hold weak references, meaning the entries do
not prevent the objects from being garbage collected if they are no longer
referenced elsewhere in the program.18 Useful for associating metadata with
objects without causing memory leaks. They are not iterable.
2.11. Symbols
Symbols are a primitive data type introduced in ES6.6 Each Symbol value returned
from Symbol() is unique.18 An optional description can be provided for debugging
purposes (Symbol('description')).18
● Use Cases:
○ Unique Object Property Keys: Symbols can be used as keys for object
properties, preventing accidental name collisions with string keys or
properties from other libraries/code.6 Symbol-keyed properties are not
enumerated by for...in loops or Object.keys().
○ Well-Known Symbols: JavaScript uses built-in Symbols to represent internal
language behaviors (e.g., Symbol.iterator defines an object's default iteration
behavior for for...of loops 61, Symbol.toStringTag modifies
Object.prototype.toString output).
JavaScript
3.2. Callbacks
The traditional way to handle asynchronous operations in JavaScript was through
callback functions.53 A callback is a function passed as an argument to another
(asynchronous) function, which is then invoked ("called back") when the
asynchronous operation finishes.7
JavaScript
JavaScript
● Consuming Promises:
○ .then(onFulfilled, onRejected): Attaches callbacks to handle the settled
state. onFulfilled runs if the promise is fulfilled (receiving the value), and
onRejected runs if it's rejected (receiving the reason).15 Crucially, .then()
returns a new promise, allowing for chaining.54 The value returned or thrown
by the onFulfilled or onRejected handler determines the state and value of the
promise returned by .then().54 If a handler returns a promise, the chain waits
for that promise to settle.54
○ .catch(onRejected): A more readable way to handle only rejections.
Equivalent to .then(null, onRejected).15 It catches any rejection that occurs in
the preceding chain.56
○ .finally(onFinally): Executes a callback function when the promise settles
(either fulfilled or rejected). It receives no arguments and does not affect the
promise's outcome. Ideal for cleanup tasks like hiding loading indicators.20
● Promise Chaining: By linking .then() calls, sequential asynchronous operations
can be expressed in a flatter, more readable structure than nested callbacks.17
JavaScript
delay(1000)
.then(message1 => {
console.log(message1); // Logs "Delayed for 1000ms"
return delay(500); // Return a new promise
})
.then(message2 => {
console.log(message2); // Logs "Delayed for 500ms"
throw new Error("Something went wrong!"); // Simulate an error
})
.catch(error => {
console.error("Caught error:", error.message); // Logs "Caught error: Something went
wrong!"
})
.finally(() => {
console.log("Operation finished."); // Logs "Operation finished."
});
● await Keyword: Can only be used inside an async function (or at the top level of
ES modules). It pauses the execution of the async function until the Promise
placed after it settles.28
○ If the awaited promise fulfills, the await expression evaluates to the fulfillment
value.52
○ If the awaited promise rejects, the await expression throws the rejection
reason (error).52
○ Crucially, await only pauses the async function it's in; it does not block the
entire JavaScript thread. Other code can run while the async function is
paused.54
● Error Handling: Because rejected promises cause await to throw an error,
standard try...catch blocks can be used for error handling in a way that closely
resembles synchronous code.18
JavaScript
async function fetchDataWithAsyncAwait() {
console.log("Fetching...");
try {
const response = await fetch('/api/data'); // Pause until fetch promise settles
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json(); // Pause until json promise settles
console.log("Data:", data);
return data;
} catch (error) {
console.error("Failed to fetch:", error);
// Handle or re-throw error
} finally {
console.log("Fetch attempt finished.");
}
}
4.1. Hoisting
Hoisting is JavaScript's behavior where declarations of variables, functions, and
classes are conceptually moved to the top of their containing scope (function scope
for var, block scope for let/const/class) during the compilation phase, before the code
is executed.7 However, the initialization (assignment of value) is not hoisted.
● Function Declarations: The entire function (declaration and body) is hoisted.
This means a function declared using the function name() {} syntax can be called
before its physical location in the code.1
JavaScript
hoistedFunc(); // Works! Output: "Hoisted!"
function hoistedFunc() { console.log("Hoisted!"); }
● var Variables: Only the declaration is hoisted, and the variable is automatically
initialized with undefined.1 Accessing a var variable before its assignment line
results in undefined, not an error.
JavaScript
console.log(myVar); // Output: undefined
varmyVar = 10;
console.log(myVar); // Output: 10
● let and const Variables: Declarations are hoisted, but they are not initialized.
They enter a state known as the Temporal Dead Zone (TDZ) from the start of
their block scope until the line where they are declared and initialized.1 Attempting
to access a let or const variable within its TDZ results in a ReferenceError.1
JavaScript
// console.log(myLet); // ReferenceError: Cannot access 'myLet' before initialization
letmyLet = 20;
console.log(myLet); // Output: 20
● Classes: Class declarations (class MyClass {}) are also hoisted but behave like let
and const – they are subject to the TDZ and cannot be used (e.g., instantiated
with new) before their definition.5
● Function Expressions: For var funcExpr = function() {}, the var funcExpr
declaration is hoisted (and initialized to undefined), but the function assignment
is not. For let/const funcExpr = function() {}, the variable declaration is hoisted but
enters the TDZ. In either case, the function expression cannot be called before
the assignment line.9
Hoisting, especially the undefined behavior of var, can lead to confusion and subtle
bugs.67 The introduction of let and const with the TDZ promotes more predictable
code by enforcing declaration before use, making potential errors explicit
(ReferenceError) rather than implicit (undefined).5 Best practice generally involves
declaring all variables at the top of their scope (let/const) to make code clearer and
avoid reliance on hoisting nuances.1
4.4. Closures
A closure is formed when a function "remembers" its lexical scope (the environment in
which it was created), even when the function is executed outside that original
scope.6
● Lexical Environment Capture: Functions are defined within a specific scope
(global, function, or block). When a function is created, it maintains a reference to
the variables available in its containing scopes (its lexical environment).37 This
environment is "closed over" by the function.
JavaScript
function outer() {
letouterVar = "I am outside!";
function inner() {
// inner function closes over outerVar
console.log(outerVar);
}
return inner;
}
constinnerFunc = outer();
innerFunc(); // Output: I am outside! (innerFunc still has access to outerVar)
● Use Cases:
○ Data Encapsulation / Privacy: Closures are the classic way to emulate
private variables and methods in JavaScript before the # syntax in classes.
Variables defined in an outer function are not directly accessible from outside,
but inner functions returned by the outer function retain access and can act
as privileged methods (Module Pattern).22
JavaScript
function createCounter() {
let count = 0; // Private variable
return {
increment: function() { count++; },
getValue: function() { return count; }
};
}
const counter1 = createCounter();
counter1.increment();
console.log(counter1.getValue()); // Output: 1
// console.log(counter1.count); // Error or undefined - count is private
2. Use an IIFE: Create a new scope for each iteration by wrapping the closure
creation in an Immediately Invoked Function Expression and passing the
current loop variable value into it.37
3. Use forEach: Array methods like forEach naturally provide a separate scope
for each iteration's callback.37
Closures are not an optional feature but a fundamental consequence of how lexical
scoping and first-class functions operate in JavaScript.37 Understanding them is
crucial for managing state, creating encapsulated modules, and correctly handling
asynchronous code, especially in loops.
This cycle ensures that the main thread is never blocked by long-running
asynchronous operations and remains responsive to user input. The crucial distinction
is the priority given to microtasks: they always run immediately after the current script
or task completes, before any other tasks like setTimeout callbacks, even those with a
0ms delay.58 This behavior is essential for the timely execution of Promise resolutions
and async/await continuations.
JavaScript
Answer:
The output will be:
Explanation:
1. var Scope: The variable i is declared with var, making it function-scoped (or
global). There's only one i variable shared across all loop iterations.8
2. Loop Completion: The for loop completes its execution quickly. By the time it
finishes, the value of i has become 4 (the condition i < arr.length becomes false).
3. setTimeout Callbacks: The setTimeout function schedules its callback to run
after the specified delay (e.g., 100ms). These callbacks are placed in the
macrotask queue.58
4. Closure Reference: Each callback function is a closure. It closes over the
variable i. However, it captures a reference to the single i variable, not its value at
the time the closure was created.77
5. Callback Execution: After the loop finishes and the delay passes, the callbacks
are executed one by one via the event loop. When they execute, they look up the
current value of i, which is 4 for all of them.42
6. arr8: The code tries to access arr8. Since the array arr only has indices 0, 1, 2, and
3, arr8 is undefined.77
Follow-up: How would you fix this to print the correct index and element for each
iteration?
Answer:
● Using let: Change var i to let i. let has block scope, so a new binding for i is
created for each loop iteration. Each closure captures its own unique i.8
JavaScript
const arr = [2, 9, 10, 11];
for (let i = 0; i < arr.length; i++) { // Changed var to let
setTimeout(function() {
console.log('Index: ' + i + ', element: ' + arr[i]);
}, 100);
}
// Output:
// Index: 0, element: 10
// Index: 1, element: 12
// Index: 2, element: 15
// Index: 3, element: 21
● Using IIFE (Immediately Invoked Function Expression): Wrap the setTimeout
call in an IIFE to create a new scope for each iteration and pass the current value
of i into that scope.37
JavaScript
const arr = [2, 9, 10, 11];
for (var i = 0; i < arr.length; i++) {
(function(index) { // IIFE creates a new scope
setTimeout(function() {
console.log('Index: ' + index + ', element: ' + arr[index]);
}, 100);
})(i); // Pass current i into the IIFE
}
// Output: (Same as 'let' solution)
JavaScript
const myObject = {
value: 'Object Value',
getValueRegular: function() {
console.log(this.value);
},
getValueArrow: () => {
console.log(this.value);
}
};
myObject.getValueRegular();
myObject.getValueArrow();
const regularFunc = myObject.getValueRegular;
const arrowFunc = myObject.getValueArrow;
regularFunc();
arrowFunc();
Answer:
The output will likely be (assuming browser, non-strict mode for the standalone call):
Object Value
undefined
undefined
undefined
Explanation:
1. myObject.getValueRegular(): This is a method call on myObject. Inside
getValueRegular (a regular function), this refers to the object the method was
called on, which is myObject. Therefore, this.value is 'Object Value'.34 Output:
Object Value.
2. myObject.getValueArrow(): This is also a method call on myObject. However,
getValueArrow is an arrow function. Arrow functions inherit this lexically from
their surrounding scope at the time of definition. Here, the arrow function is
defined within the object literal, which itself is in the global scope. Thus, this
inside getValueArrow refers to the global object (window in browsers).
window.value is typically undefined.34 Output: undefined.
3. regularFunc(): Here, getValueRegular is assigned to regularFunc and then called
as a standalone function (not as a method of myObject). In non-strict mode, this
inside a standalone regular function call defaults to the global object (window).
window.value is undefined.34 (In strict mode, this would be undefined, likely
causing a TypeError when accessing this.value). Output: undefined.
4. arrowFunc(): getValueArrow is assigned to arrowFunc and called. Since it's an
arrow function, its this remains bound to what it was during definition (the global
object, as explained in point 2). Calling it standalone doesn't change its this.
window.value is undefined.34 Output: undefined.
function testHoisting() {
console.log("1:", a);
try {
console.log("2:", b);
} catch (e) {
console.log("2:", e.name);
}
try {
console.log("3:", c);
} catch (e) {
console.log("3:", e.name);
}
var a = 'var';
let b = 'let';
const c = 'const';
console.log("4:", a);
console.log("5:", b);
console.log("6:", c);
function innerFunc() {
console.log("Inner func called");
}
innerFunc(); // Call function defined later
}
testHoisting();
Answer:
The output will be:
1: undefined
2: ReferenceError
3: ReferenceError
4: var
5: let
6: const
Inner func called
Explanation:
1. console.log("1:", a);: var a is hoisted to the top of testHoisting. At this point, a is
declared but not yet assigned 'var'. Hoisted var variables are initialized with
undefined.1 Output: 1: undefined.
2. console.log("2:", b);: let b is hoisted, but it enters the Temporal Dead Zone (TDZ).
Accessing b before its declaration line (let b = 'let';) throws a ReferenceError.1
Output: 2: ReferenceError.
3. console.log("3:", c);: const c is also hoisted but enters the TDZ. Accessing c
before its declaration line (const c = 'const';) throws a ReferenceError.1 Output: 3:
ReferenceError.
4. Assignments: The lines var a = 'var';, let b = 'let';, const c = 'const'; are executed.
5. console.log("4:", a);: a now holds the value 'var'. Output: 4: var.
6. console.log("5:", b);: b now holds the value 'let' (past the TDZ). Output: 5: let.
7. console.log("6:", c);: c now holds the value 'const' (past the TDZ). Output: 6:
const.
8. innerFunc();: The function declaration function innerFunc() {...} is fully hoisted
(declaration and body) to the top of testHoisting. Therefore, it can be called
before its physical location in the code.1 Output: Inner func called.
JavaScript
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C')).then(() => console.log('D'));
queueMicrotask(() => console.log('E'));
console.log('F');
Question: What is the exact order of the console logs and why?
Answer:
The output will be:
A
F
C
E
D
B
Explanation:
1. console.log('A');: Synchronous, executes immediately. Output: A.
2. setTimeout(() => console.log('B'), 0);: Schedules the callback (() =>
console.log('B')) to run as a macrotask. It's added to the macrotask queue after
the delay (effectively minimal, but after current script).58
3. Promise.resolve().then(() => console.log('C')).then(() => console.log('D'));:
○ Promise.resolve() creates a resolved promise.
○ The first .then(() => console.log('C')) schedules its callback as a microtask.58
○ The second .then(() => console.log('D')) is chained. Its callback will only be
scheduled as a microtask after the first .then callback completes.
4. queueMicrotask(() => console.log('E'));: Explicitly schedules the callback (() =>
console.log('E')) as a microtask.
5. console.log('F');: Synchronous, executes immediately. Output: F.
6. End of Synchronous Script: The main script finishes. The Call Stack is now
empty.
7. Microtask Queue Processing: The Event Loop checks the microtask queue. It
finds the callbacks for 'C' and 'E'.62
○ The 'C' callback executes. Output: C.
○ Executing the 'C' callback's .then schedules the 'D' callback as a new
microtask.
○ The 'E' callback executes. Output: E.
○ The Event Loop checks the microtask queue again. It finds the 'D' callback.
○ The 'D' callback executes. Output: D.
○ The microtask queue is now empty.
8. Macrotask Queue Processing: The Event Loop checks the macrotask queue. It
finds the setTimeout callback for 'B'.62
○ The 'B' callback executes. Output: B.
9. End: Both queues are empty. The Event Loop waits.
The key is that all microtasks (Promise.then, queueMicrotask) are executed completely
after the current script finishes, before any macrotasks (setTimeout) are processed.58
JavaScript
function Dog(name) {
this.name = name;
}
Dog.prototype.breed = "Generic Dog";
Dog.prototype.speak = function() {
console.log(`${this.name} says Woof! I am a ${this.breed}.`);
}
const dog1 = new Dog("Buddy");
const dog2 = new Dog("Lucy");
dog2.breed = "Labrador"; // Add an 'own' property to dog2
dog1.speak();
dog2.speak();
Question: What is the output and why does dog2.speak() output a different breed?
Answer:
The output will be:
Explanation:
1. Constructor and Prototype: Dog is a constructor function. breed and speak are
added to Dog.prototype. When new Dog(...) is called, new instances (dog1, dog2)
are created whose [[Prototype]] points to Dog.prototype.33 Both instances inherit
breed and speak.
2. dog1.speak():
○ speak is called on dog1. this inside speak refers to dog1.27
○ this.name accesses dog1's own property, which is "Buddy".
○ this.breed is accessed on dog1. dog1 doesn't have an own property named
breed, so JavaScript looks up the prototype chain.73 It finds breed on
Dog.prototype with the value "Generic Dog".
○ Output: Buddy says Woof! I am a Generic Dog.
3. dog2.breed = "Labrador";: This line adds a new own property named breed
directly to the dog2 instance, setting its value to "Labrador".
4. dog2.speak():
○ speak is called on dog2. this inside speak refers to dog2.27
○ this.name accesses dog2's own property, which is "Lucy".
○ this.breed is accessed on dog2. JavaScript finds the own property breed on
dog2 first and uses its value ("Labrador"). It does not continue up the
prototype chain because the property was found directly on the instance.73
This is called property shadowing.
○ Output: Lucy says Woof! I am a Labrador.
This demonstrates how own properties on an instance take precedence over inherited
properties with the same name during property lookup, and how this in an inherited
method correctly refers to the instance it was called on.
JavaScript
console.log("1:", == 0);
console.log("2:", ==!);
console.log("3:", null == undefined);
console.log("4:", null === undefined);
console.log("5:", '5' == 5);
console.log("6:", '5' === 5);
console.log("7:", NaN == NaN);
console.log("8:", Object.is(NaN, NaN));
Answer:
1: true
2: true
3: true
4: false
5: true
6: false
7: false
8: true
Explanation:
1. == 0 -> true: Loose equality (==) involves type coercion.22 The empty array `` is
coerced to a primitive. .toString() is "". Then "" is coerced to a number, which is 0.
So the comparison becomes 0 == 0, which is true.
2. ==! -> true: The ! operator has high precedence. ! evaluates first. An array () is a
truthy value.25 `!true` is `false`. The comparison becomes ` == false`. `false` is
coerced to the number `0`. is coerced to "" then to 0 (as in #1). The comparison
becomes 0 == 0, which is true.
3. null == undefined -> true: Loose equality (==) has a specific rule that treats null
and undefined as equal to each other.23
4. null === undefined -> false: Strict equality (===) checks for both value and type
without coercion.7 null and undefined are different types.
5. '5' == 5 -> true: Loose equality (==) coerces the string '5' to the number 5. The
comparison becomes 5 == 5, which is true.22
6. '5' === 5 -> false: Strict equality (===) checks types. String '5' and number 5 are
different types.7
7. NaN == NaN -> false: NaN (Not-a-Number) is unique in that it is not equal to
anything, including itself, using both == and ===.25
8. Object.is(NaN, NaN) -> true: Object.is() is an ES6 method that determines if two
values are the same value. It behaves similarly to === but treats NaN as equal to
NaN and distinguishes between -0 and +0 (which === treats as equal).11
These examples highlight the often non-intuitive nature of type coercion with loose
equality (==) and emphasize why strict equality (===) is generally recommended for
predictable comparisons.7
Conclusion
This document has provided a structured overview of JavaScript, encompassing its
fundamental building blocks, the significant advancements introduced by ES6, the
critical patterns for handling asynchronous operations, and deeper dives into core
mechanisms like hoisting, the this keyword, prototypal inheritance, closures, and the
event loop. The included tricky interview questions illustrate how these concepts
interrelate and are tested in real-world scenarios.
Works cited
1. Grammar and types - JavaScript - MDN Web Docs - Mozilla, accessed on April
23, 2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_ty
pes
2. JavaScript ES6 Features Every Developer Should Know. - DEV Community,
accessed on April 23, 2025,
https://dev.to/codingcrafts/javascript-es6-features-every-developer-should-kno
w-12ak
3. 6. JavaScript fundamentals | MDN Curriculum, accessed on April 23, 2025,
https://developer.mozilla.org/en-US/curriculum/core/javascript-fundamentals/
4. sudheerj/javascript-interview-questions: List of 1000 JavaScript Interview
Questions - GitHub, accessed on April 23, 2025,
https://github.com/sudheerj/javascript-interview-questions
5. Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms, accessed
on April 23, 2025, https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
6. JavaScript Guide - JavaScript | MDN - MDN Web Docs - Mozilla, accessed on
April 23, 2025, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide
7. JavaScript Developer Interview Questions - Braintrust, accessed on April 23,
2025,
https://www.usebraintrust.com/hire/interview-questions/javascript-developers
8. Top 13 Javascript Interview Questions You Should Answer!.md - GitHub Gist,
accessed on April 23, 2025,
https://gist.github.com/Mohamed-Code-309/12163e62bfd0bbef1a8c78c63d7c79
24
9. yangshun/top-javascript-interview-questions: 200 important ... - GitHub,
accessed on April 23, 2025,
https://github.com/yangshun/top-javascript-interview-questions
10.JavaScript Interview Questions and Answers (2025) - InterviewBit, accessed on
April 23, 2025, https://www.interviewbit.com/javascript-interview-questions/
11. JavaScript - MDN Web Docs - Mozilla, accessed on April 23, 2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript
12.Top 10 Features of ES6: A Comprehensive Guide | Board Infinity, accessed on
April 23, 2025, https://www.boardinfinity.com/blog/top-10-features-of-es6/
13.150 JavaScript Interview Questions & Answers – Nail Your Tech Interview -
WebDevStory, accessed on April 23, 2025,
https://www.webdevstory.com/javascript-interview-questions/
14.Overview of JavaScript ES6 features | Hacker News, accessed on April 23, 2025,
https://news.ycombinator.com/item?id=12778395
15.List of JavaScript Interview Questions for Freshers - GitHub, accessed on April 23,
2025, https://github.com/iamkoushik1999/Javascript-Interview-Questions
16.Introduction - JavaScript - MDN Web Docs - Mozilla, accessed on April 23, 2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Introduction
17.JavaScript Tutorial, accessed on April 23, 2025, https://www.javascripttutorial.net/
18.The Modern JavaScript Tutorial, accessed on April 23, 2025, https://javascript.info/
19.90+ JavaScript Interview Questions and Answers [2025] - Simplilearn.com,
accessed on April 23, 2025,
https://www.simplilearn.com/tutorials/javascript-tutorial/javascript-interview-que
stions
20.ES6 to ES15 - Features list | JS - DEV Community, accessed on April 23, 2025,
https://dev.to/shubhamtiwari909/es6-to-es14-features-list-57am
21.Web development tutorials - MDN Web Docs - Mozilla, accessed on April 23,
2025, https://developer.mozilla.org/en-US/docs/MDN/Tutorials
22.100 Common JavaScript Interview Questions - GitHub, accessed on April 23,
2025, https://github.com/Devinterview-io/javascript-interview-questions
23.JavaScript Interview Questions.md - GitHub Gist, accessed on April 23, 2025,
https://gist.github.com/paulfranco/e000fae23c1ec319fb8baf90066d4f05
24.A first splash into JavaScript - Learn web development | MDN, accessed on April
23, 2025,
https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Scripting
/A_first_splash
25.23+ Advanced JavaScript Interview Questions (ANSWERED) - FullStack.Cafe,
accessed on April 23, 2025,
https://www.fullstack.cafe/blog/advanced-javascript-interview-questions
26.Looping code - Learn web development | MDN, accessed on April 23, 2025,
https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Scripting
/Loops
27.Prototypal inheritance - The Modern JavaScript Tutorial, accessed on April 23,
2025, https://javascript.info/prototype-inheritance
28.Functions - JavaScript - MDN Web Docs, accessed on April 23, 2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions
29.ES6 - Really? This seems so un-intuitive - JavaScript - The freeCodeCamp Forum,
accessed on April 23, 2025,
https://forum.freecodecamp.org/t/es6-really-this-seems-so-un-intuitive/456889
30.A Guide to Exploring JavaScript ES6 Features - Scribbler, accessed on April 23,
2025, https://scribbler.live/2024/04/12/ES6-Features-with-Examples.html
31.Javascript Interview Questions and answers - DEV Community, accessed on April
23, 2025,
https://dev.to/renukapatil/javascript-interview-questions-and-answers-375j
32.rohan-paul/Awesome-JavaScript-Interviews - GitHub, accessed on April 23,
2025, https://github.com/rohan-paul/Awesome-JavaScript-Interviews
33.new - JavaScript - MDN Web Docs - Mozilla, accessed on April 23, 2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/n
ew
34.this - JavaScript | MDN - MDN Web Docs - Mozilla, accessed on April 23, 2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/th
is
35.Dynamic scripting with JavaScript - Learn web development | MDN, accessed on
April 23, 2025,
https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Scripting
36.55 Top JavaScript Interview Questions with Example Answers | Built In, accessed
on April 23, 2025,
https://builtin.com/software-engineering-perspectives/javascript-interview-quest
ions
37.Closures - JavaScript | MDN - MDN Web Docs - Mozilla, accessed on April 23,
2025, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
38.Closure - MDN Web Docs Glossary: Definitions of Web-related terms - Mozilla,
accessed on April 23, 2025,
https://developer.mozilla.org/en-US/docs/Glossary/Closure
39.Articulating what a JavaScript Closure is... : r/webdev - Reddit, accessed on April
23, 2025,
https://www.reddit.com/r/webdev/comments/2u7dsd/articulating_what_a_ javascri
pt_closure_is/
40.What's a closure? - DEV Community, accessed on April 23, 2025,
https://dev.to/kjdowns/what-s-a-closure-184n
41.JavaScript technologies overview - MDN Web Docs, accessed on April 23, 2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/JavaScript_te
chnologies_overview
42.lydiahallie/javascript-questions: A long list of (advanced ... - GitHub, accessed on
April 23, 2025, https://github.com/lydiahallie/javascript-questions
43.ES6 examples - GitHub Pages, accessed on April 23, 2025,
https://gatosnake.github.io/es6-examples/
44.lukehoban/es6features: Overview of ECMAScript 6 features - GitHub, accessed
on April 23, 2025, https://github.com/lukehoban/es6features
45.Master ECMAScript: A comprehensive list with Real-World Examples -
ServiceNow, accessed on April 23, 2025,
https://www.servicenow.com/community/developer-articles/master-ecmascript-
a-comprehensive-list-with-real-world-examples/ta-p/2420283
46.What are your favorite JavaScript ES6 features? - 2ality, accessed on April 23,
2025, https://2ality.com/2015/07/favorite-es6-features.html
47.Classes - JavaScript - MDN Web Docs, accessed on April 23, 2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
48.Using classes - JavaScript - MDN Web Docs - Mozilla, accessed on April 23, 2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_classes
49.Object prototypes - Learn web development | MDN, accessed on April 23, 2025,
https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Ad
vanced_JavaScript_objects/Object_prototypes
50.JavaScript modules - MDN Web Docs - Mozilla, accessed on April 23, 2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
51.10 JavaScript Advanced Interview Questions - Codedamn, accessed on April 23,
2025,
https://codedamn.com/news/javascript/10-javascript-advanced-interview-questi
ons
52.async function - JavaScript | MDN - MDN Web Docs - Mozilla, accessed on April
23, 2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/a
sync_function
53.Async/Await, Promises and Callbacks in JavaScript - Nangialai Stoman, accessed
on April 23, 2025,
https://www.stoman.me/articles/async-await-promises-callbacks-in-javascript
54.Using promises - JavaScript | MDN - MDN Web Docs - Mozilla, accessed on April
23, 2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
55.Introducing asynchronous JavaScript - Learn web development | MDN, accessed
on April 23, 2025,
https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/As
ync_JS/Introducing
56.How to use promises - Learn web development | MDN, accessed on April 23,
2025,
https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/As
ync_JS/Promises
57.Promise - JavaScript - MDN Web Docs, accessed on April 23, 2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Obje
cts/Promise
58.The Most Common JavaScript Event Loop Interview Questions ..., accessed on
April 23, 2025, https://www.explainthis.io/en/swe/js-event-loop-questions
59.Map - JavaScript | MDN - MDN Web Docs - Mozilla, accessed on April 23, 2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Obje
cts/Map
60.Set - JavaScript | MDN - MDN Web Docs - Mozilla, accessed on April 23, 2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Obje
cts/Set
61.Iteration protocols - JavaScript - MDN Web Docs, accessed on April 23, 2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_pro
tocols
62.JavaScript execution model - JavaScript | MDN - MDN Web Docs, accessed on
April 23, 2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Execution_m
odel
63.What is An Event Loop in JavaScript? | GeeksforGeeks, accessed on April 23,
2025, https://www.geeksforgeeks.org/what-is-an-event-loop-in-javascript/
64.Concurrency model and Event Loop - JavaScript | MDN, accessed on April 23,
2025,
https://lia.disi.unibo.it/materiale/JS/developer.mozilla.org/en-US/docs/Web/JavaScr
ipt/EventLoop.html
65.The Node.js Event Loop, accessed on April 23, 2025,
https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick
66.Top 25 Senior JavaScript Developer Interview Questions and Answers -
Anywhere Club, accessed on April 23, 2025,
https://aw.club/global/en/blog/senior-javascript-developer-interview-questions
67.Understanding Hoisting in JavaScript: Building a mental model- part 1 - DEV
Community, accessed on April 23, 2025,
https://dev.to/haastrupea/understanding-hoisting-in-javascript-building-a-mental
-model-part-1-45og
68.JavaScript Hoisting: What It Is And Why It Was Implemented - DEV Community,
accessed on April 23, 2025,
https://dev.to/jwwnz/javascript-hoisting-what-it-is-and-why-it-was-implemented
-51ep
69.Understanding Hoisting in JavaScript - DigitalOcean, accessed on April 23, 2025,
https://www.digitalocean.com/community/tutorials/understanding-hoisting-in-jav
ascript
70.JavaScript Interview Questions and Answers (2025) – Advanced Level -
GeeksforGeeks, accessed on April 23, 2025,
https://www.geeksforgeeks.org/javascript-interview-questions-and-answers-set
-3/
71.JavaScript Hoisting | GeeksforGeeks, accessed on April 23, 2025,
https://www.geeksforgeeks.org/javascript-hoisting/
72.How are javascript variables "hoisted" in these examples from MDN - Stack
Overflow, accessed on April 23, 2025,
https://stackoverflow.com/questions/14806135/how-are-javascript-variables-hois
ted-in-these-examples-from-mdn
73.Inheritance and the prototype chain - JavaScript | MDN, accessed on April 23,
2025,
https://lia.disi.unibo.it/materiale/JS/developer.mozilla.org/en-US/docs/Web/JavaScr
ipt/Inheritance_and_the_prototype_chain.html
74.Inheritance and the prototype chain - JavaScript | MDN, accessed on April 23,
2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_
the_prototype_chain
75.Object.prototype.__proto__ - JavaScript - MDN Web Docs - Mozilla, accessed on
April 23, 2025,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Obje
cts/Object/proto
76.Closures Explained in 100 Seconds // Tricky JavaScript Interview Prep - YouTube,
accessed on April 23, 2025, https://www.youtube.com/watch?v=vKJpN5FAeF4
77.A tricky JavaScript interview question asked by Google - DEV ..., accessed on
April 23, 2025,
https://dev.to/coderbyte/a-tricky-javascript-interview-question-asked-by-google
-3gnf
78.Javascript interview question - Scope and Closures : r/learnjavascript - Reddit,
accessed on April 23, 2025,
https://www.reddit.com/r/learnjavascript/comments/bd6bwe/javascript_interview
_question_scope_and_closures/
79.In depth: Microtasks and the JavaScript runtime environment - Web APIs | MDN,
accessed on April 23, 2025,
https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_gui
de/In_depth
80.Hi asking if you know The modern Javascript tutorial/javascript.info - Reddit,
accessed on April 23, 2025,
https://www.reddit.com/r/learnprogramming/comments/16lskga/hi_asking_if_you_
know_the_modern_ javascript/
81.For beginners, I strongly recommend the MDN (Mozilla) docs as a place to start! -
Reddit, accessed on April 23, 2025,
https://www.reddit.com/r/learnjavascript/comments/1fu8c70/for_beginners_i_stro
ngly_recommend_the_mdn/
82.Learning JS through MDN Documentation? : r/learnjavascript - Reddit, accessed
on April 23, 2025,
https://www.reddit.com/r/learnjavascript/comments/tcq5q9/learning_ js_through_
mdn_documentation/