0% found this document useful (0 votes)
43 views45 pages

JavaScript ES6 Interview Preparation Notes

This document serves as comprehensive JavaScript interview preparation notes, covering fundamentals, ES6 features, and advanced topics. It includes sections on variables, data types, operators, control flow, functions, objects, arrays, and closures, along with tricky interview questions. The aim is to provide candidates with a robust understanding of JavaScript's core mechanics and modern capabilities.

Uploaded by

htsingh200
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)
43 views45 pages

JavaScript ES6 Interview Preparation Notes

This document serves as comprehensive JavaScript interview preparation notes, covering fundamentals, ES6 features, and advanced topics. It includes sections on variables, data types, operators, control flow, functions, objects, arrays, and closures, along with tricky interview questions. The aim is to provide candidates with a robust understanding of JavaScript's core mechanics and modern capabilities.

Uploaded by

htsingh200
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
You are on page 1/ 45

Comprehensive JavaScript Notes for Interview Preparation

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.

Section 1: JavaScript Fundamentals


A solid grasp of JavaScript fundamentals is essential before delving into more
advanced features. This section covers the building blocks of the language.

1.1. Variables and Scope


Variables are symbolic names used to store values.1 JavaScript provides three
keywords for variable declaration: var, let, and const.
●​ var: Historically the primary way to declare variables. var declarations are
function-scoped (accessible anywhere within the function they are declared in)
or globally-scoped if declared outside any function.1 Variables declared with var
can be re-declared and updated within their scope.7 They are subject to hoisting,
where the declaration is moved to the top of the scope, but the initialization
remains in place, resulting in an initial value of undefined if accessed before
assignment.1
●​ let: Introduced in ES6, let declares block-scoped variables. A block is any code
enclosed in curly braces ({}), such as within an if statement or a for loop.6 let
variables can be updated but cannot be re-declared within the same scope.7 Like
var, let declarations are hoisted, but they are not initialized and enter a Temporal
Dead Zone (TDZ) until the line of declaration is reached, preventing access before
declaration.1
●​ const: Also introduced in ES6, const declares block-scoped variables that
represent constants.12 They must be initialized at the time of declaration and
cannot be re-assigned or re-declared afterward.1 const declarations are also
hoisted but subject to the TDZ.1 Importantly, const ensures the variable binding is
immutable; if the variable holds an object or array, the contents of that object or
array can still be modified.6
Scope defines the accessibility of variables:
●​ Global Scope: Variables declared outside any function or block are globally
accessible.1 Modifying the global scope is generally discouraged.9
●​ Function Scope: Variables declared with var inside a function are accessible only
within that function.1
●​ Block Scope: Variables declared with let or const inside a block ({...}) are
accessible only within that block.1

Understanding the differences in scoping and hoisting between var, let, and const is
crucial for writing predictable and maintainable code.7

1.2. Data Types


JavaScript is a dynamically typed language, meaning variable types are determined at
runtime, not declared explicitly.16 Data types are categorized into primitives and
objects.6
●​ Primitive Types: Immutable values representing fundamental data.6
○​ String: Sequence of characters (e.g., "hello").6
○​ Number: Represents numeric values, including integers and floating-point
numbers (e.g., 42, 3.14).6 Includes special values like NaN (Not-a-Number) 15
and Infinity.
○​ BigInt: Represents integers of arbitrary precision, exceeding the limits of the
Number type.6
○​ Boolean: Represents logical values true or false.6
○​ Undefined: Represents a variable that has been declared but not assigned a
value.6 It's the default value for uninitialized variables declared with var or let.1
○​ Null: Represents the intentional absence of any object value. It is an
assignment value.6 typeof null paradoxically returns "object".
○​ Symbol: Unique and immutable primitive value, often used as object property
keys to avoid collisions.6
●​ Object Type: Represents complex data structures, collections of key-value pairs
(properties).6 Objects are mutable reference types.9 Arrays, Functions, Maps,
Sets, Dates, etc., are specialized types of objects in JavaScript.6

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

1.4. Control Flow


Control flow statements direct the order of code execution.
●​ Conditional Statements:
○​ if...else...else if: Executes code blocks based on conditions.6
○​ switch: Selects one of many code blocks to execute based on an expression's
value.6 Use break to exit a case.
●​ Loops: Repeat code execution.26
○​ for: Executes a block a specific number of times, controlled by an initializer,
condition, and final expression.6
○​ while: Executes a block as long as a condition remains true.6
○​ do...while: Executes a block once, then repeats as long as a condition is true.6
○​ for...in: Iterates over the enumerable property names (keys) of an object.6 Use
with caution on arrays as it iterates over indices and prototype properties.
○​ for...of (ES6): Iterates over the values of iterable objects like Arrays, Strings,
Maps, Sets.6 Preferred for iterating over array values.26
●​ Loop Control:
○​ break: Exits the current loop or switch statement.6
○​ continue: Skips the current iteration and proceeds to the next.6
1.5. Functions
Functions are fundamental building blocks, allowing code reuse and organization.6 In
JavaScript, functions are first-class citizens: they can be assigned to variables,
passed as arguments, and returned from other functions.17
●​ Function Declaration: Defined using the function keyword followed by a name,
parameters, and body. Function declarations are hoisted entirely.6​
JavaScript​
function add(a, b) {​
return a + b;​
}​

●​ Function Expression: Defined as part of an expression, often assigned to a


variable. Can be named or anonymous. The variable declaration is hoisted (per
var/let/const rules), but the function assignment is not.6​
JavaScript​
const multiply = function(a, b) {​
return a * b;​
};​

●​ 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;​
}​
};​

●​ Properties: Key-value pairs within an object.


○​ Accessing: Dot notation (person.firstName) or bracket notation
(person['lastName']).9 Bracket notation is required for keys with spaces or
special characters, or when using a variable as the key name.
○​ Adding/Modifying: person.country = "UK"; or person['birthYear'] = 1816;.3
○​ Deleting: delete person.birthYear;
●​ Methods: Functions stored as object properties.6 When a method is called (e.g.,
person.calculateAge(2025)), the this keyword typically refers to the object the
method was called on (person in this case). ES6 introduced shorthand syntax for
methods within literals.12
●​ Constructors: Functions used with the new keyword to create multiple object
instances with a similar structure.10 The this keyword inside a constructor refers to
the new object being created.33
●​ this Keyword: Refers to the execution context. Its value depends heavily on how
a function is invoked (e.g., as a method, standalone function, constructor).18 This
is a complex topic detailed in Section 4.

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

1.8. Closures (Introduction)


A closure is the combination of a function and the lexical environment (the
surrounding state, including variables) within which that function was declared.37 This
allows an inner function to access variables from its outer function's scope, even after
the outer function has returned.37 Closures are created every time a function is
defined.37 They are fundamental to many JavaScript patterns, including data privacy
and callbacks.37 This concept is explored further in Section 4.

Section 2: ES6 (ECMAScript 2015) Features


ES6 marked a significant evolution of JavaScript, introducing features that enhance
syntax, improve code organization, and add new capabilities.2 Understanding these
features is crucial for modern JavaScript development and interviews.
2.1. let and const
As detailed in Section 1.1, let and const provide block-scoping for variables, offering
more control and predictability compared to function-scoped var.6 let allows
reassignment, while const creates read-only bindings (though the contents of
objects/arrays assigned to const can still be mutated).6 Their use helps prevent
common errors related to variable hoisting and scope leakage.12

2.2. Arrow Functions


Arrow functions provide a more concise syntax for writing function expressions.6
●​ Syntax: Uses the => operator. Parentheses around parameters are optional for a
single parameter (unless destructuring), and curly braces are optional for a single
expression body (which implies an automatic return).12​
JavaScript​
// Traditional​
const add = function(a, b) { return a + b; };​
// Arrow​
const addArrow = (a, b) => a + b;​
const square = x => x * x; // Single parameter, implicit return​
const greet = () => "Hello!"; // No parameters​
const complexCalc = (a, b) => { // Multiple statements require {} and explicit return​
const result = a * b + 10;​
return result;​
};​

●​ 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

2.3. Template Literals


Template literals provide an enhanced way to work with strings, using backticks (`)
instead of single or double quotes.6
●​ String Interpolation: Easily embed expressions (variables, function calls, etc.)
directly within the string using the ${expression} syntax.12​
JavaScript​
const name = "World";​
const score = 100;​
const message = `Hello, ${name}! Your score is ${score * 2}.`;​
// message is "Hello, World! Your score is 200."​

●​ 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.`;​

●​ Tagged Templates: An advanced feature allowing a function (the "tag") to


process a template literal before it's converted to a string.9

2.4. Destructuring Assignment


Destructuring provides a concise syntax to extract values from arrays or properties
from objects into distinct variables.6
●​ Array Destructuring: Extracts values based on their position.​
JavaScript​
const numbers = [2, 3, 4];​
const [first, second] = numbers; // first = 10, second = 20​

// Skip elements​
const [, , third] = numbers; // third = 30​

// Rest syntax​
const [head,...tail] = numbers; // head = 10, tail = [3, 4]​

// Default values​
const [a, b, c, d = 40] = numbers; // d = 40​

●​ Object Destructuring: Extracts values based on property names.​


JavaScript​
const user = { id: 123, name: "Alice", email: "[email protected]" };​
const { name, email } = user; // name = "Alice", email = "[email protected]"​

// Renaming variables​
const { id: userId } = user; // userId = 123​

// Default values​
const { country = "USA" } = user; // country = "USA"​

// Nested destructuring​
const data = { point: { x: 1, y: 2 } };​
const { point: { x, y } } = data; // x = 1, y = 2​

●​ Function Parameters: Destructuring can be used directly in function parameter


lists for easier access to object properties or array elements passed as
arguments.12​
JavaScript​
function displayUser({ name, email }) {​
console.log(`Name: ${name}, Email: ${email}`);​
}​
displayUser(user); // Output: Name: Alice, Email: [email protected]

Destructuring significantly reduces the code needed to access nested data and
improves readability.12

2.5. Default Parameters


ES6 allows specifying default values for function parameters directly in the function
signature. If an argument for that parameter is omitted or explicitly undefined during
the function call, the default value is used.6

JavaScript

function greet(name = "Guest", message = "Hello") {​


console.log(`${message}, ${name}!`);​
}​

greet(); // Output: Hello, Guest!​
greet("Bob"); // Output: Hello, Bob!​
greet("Charlie", "Hi"); // Output: Hi, Charlie!​
greet(undefined, "Welcome"); // Output: Welcome, Guest!​
This simplifies function logic by removing the need for manual checks for undefined
arguments.12 Default parameters can also refer to earlier parameters.45

2.6. Rest Parameters & Spread Syntax


Both use the ellipsis (...) syntax but serve opposite purposes.6
●​ Rest Parameters: Used in function definitions to collect an indefinite number of
remaining arguments into a single array.6 It must be the last parameter in the
function signature. Replaces the need for the older arguments object in many
cases.44​
JavaScript​
function sum(...numbers) { // 'numbers' becomes an array of all arguments​
return numbers.reduce((acc, current) => acc + current, 0);​
}​
console.log(sum(1, 2, 3)); // Output: 6​
console.log(sum(5, 10, 15, 20)); // Output: 50​

●​ 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​

○​ Array Literals: Create new arrays by combining or cloning existing ones


(shallow copy).​
JavaScript​
const arr1 = [1, 6];​
const arr2 = [7, 8];​
const combined = [...arr1, 0,...arr2]; // combined = ​
const arrCopy = [...arr1]; // arrCopy = [1, 6] (shallow copy)​

○​ Object Literals (ES2018+): Merge or clone objects (shallow copy).​


JavaScript​
const obj1 = { a: 1, b: 2 };​
const obj2 = { b: 3, c: 4 };​
const merged = {...obj1,...obj2 }; // merged = { a: 1, b: 3, c: 4 } (later properties overwrite
earlier ones)​
const objCopy = {...obj1 }; // objCopy = { a: 1, b: 2 } (shallow copy)​
2.7. Classes
ES6 introduced the class keyword, providing a cleaner, more familiar syntax for
creating constructor functions and implementing inheritance. However, it's crucial to
remember that this is primarily syntactic sugar over JavaScript's existing prototypal
inheritance mechanism.6
●​ Syntax: Uses the class keyword.​
JavaScript​
class Rectangle {​
// Constructor method for initialization​
constructor(height, width) {​
this.height = height;​
this.width = width;​
}​

// Instance method (added to Rectangle.prototype)​
getArea() {​
return this.height * this.width;​
}​

// Getter​
get area() {​
return this.getArea();​
}​

// Static method (belongs to the class itself)​
{​
static createSquare(side)
return new Rectangle(side, side);​
}​
}​

●​ 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​
}​
}​

●​ Private Fields/Methods: Newer additions allow defining private members using


the # prefix.17

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

2.8. Modules (import/export)


ES6 introduced a standard module system for organizing code into separate, reusable
files, improving maintainability and preventing global namespace pollution.6
●​ export: Used within a module file to make variables, functions, or classes
available to other modules.
○​ Named Exports: Export specific items by name. Multiple named exports are
allowed per module.6​
JavaScript​
// utils.js​
export const PI = 3.14159;​
export function double(x) { return x * 2; }​

○​ 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 { /*... */ }​

●​ import: Used in another module file to bring in exported functionality.


○​ Importing Named Exports: Use curly braces {}.6 Can be renamed using as.6​
JavaScript​
// app.js​
import { PI, double as multiplyByTwo } from './utils.js';​
console.log(PI);​
console.log(multiplyByTwo(5)); // 10​

○​ Importing Default Export: Use any name without curly braces.6​


JavaScript​
// app.js​
import MyComponent from './mainComponent.js';​
const component = new MyComponent();​

○​ Importing Namespace: Import all named exports as properties of a single


object.6​
JavaScript​
// app.js​
import * as utils from './utils.js';​
console.log(utils.PI);​
console.log(utils.double(5)); // 10​

●​ Dynamic import(): Allows loading modules conditionally or on demand. Returns


a Promise that resolves with the module object.6​
JavaScript​
button.addEventListener('click', async () => {​
const module = await import('./heavyModule.js');​
module.doHeavyStuff();​
});​
ES6 modules differ from older systems like CommonJS (used in Node.js:
require/module.exports) and AMD. ES6 modules are statically analyzable
(imports/exports determined at compile time), whereas CommonJS is dynamic
(evaluated at runtime).44

2.9. Promises (Introduction)


Promises provide a standard way to handle asynchronous operations, offering a
cleaner alternative to nested callbacks (callback hell).6 A Promise object represents
the eventual result (fulfillment) or reason for failure (rejection) of an asynchronous
operation.57 They are covered in detail in Section 3.

2.10. Map and Set Data Structures


ES6 introduced two new built-in iterable data structures: Map and Set.18
●​ Map: A collection of key-value pairs where keys can be of any data type
(including objects or functions), unlike plain objects where keys are limited to
strings and Symbols.18 Maps remember the original insertion order of keys.59
○​ Key Methods/Properties: set(key, value), get(key), has(key), delete(key),
clear(), size property.59
○​ Iteration: Maps are iterable. Use keys(), values(), entries(), forEach(), or
for...of loops to iterate over keys, values, or [key, value] pairs.59
JavaScript​
const userRoles = new Map();​
const user1 = { id: 1 };​
userRoles.set(user1, 'Admin');​
userRoles.set('user2', 'Editor');​

console.log(userRoles.get(user1)); // Output: Admin​
console.log(userRoles.size); // Output: 2​
for (const [key, value] of userRoles) {​
console.log(key, value);​
}​

●​ 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

const idSymbol = Symbol('userId');​


user = {​
const
name: 'Alex',​
: 12345 // Using a Symbol as a key​
};​

console.log(user.name); // Output: Alex​
console.log(user); // Output: 12345​
console.log(Object.keys(user)); // Output: ['name'] (Symbol key ignored)​
console.log(Object.getOwnPropertySymbols(user)); // Output:​

Section 3: Asynchronous JavaScript Explained


JavaScript's single-threaded nature necessitates mechanisms for handling operations
that take time (like network requests or timers) without blocking the main execution
thread.

3.1. The Need for Asynchronicity


JavaScript engines typically execute code synchronously on a single thread.11 This
means each line of code blocks the execution of the next line until it completes.53 If a
task takes a long time (e.g., waiting for a response from a server), the entire program,
including the user interface in a browser, becomes unresponsive.55 Asynchronous
programming techniques allow these long-running tasks to be initiated, letting the
main thread continue with other work (like responding to user input). When the
asynchronous task completes, its result is handled later, typically via a callback,
promise, or async/await.13

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

function fetchData(url, callback) {​


// Simulate network request​
console.log(`Fetching data from ${url}...`);​
setTimeout(() => {​
const data = { message: "Data received!" };​
callback(null, data); // Pass null for error, then data​
}, 1000);​
}​

fetchData('/api/data', (error, data) => {​
if (error) {​
console.error('Error:', error);​
} else {​
console.log('Success:', data.message);​
}​
});​
console.log("Request initiated.");​

Callback Hell: When multiple asynchronous operations depend on each other,


nesting callbacks leads to deeply indented, hard-to-read code structures often called
"Callback Hell" or the "Pyramid of Doom".2 Error handling also becomes complex
within nested callbacks.54

JavaScript

// Conceptual Callback Hell​


asyncOperation1(data1, (err1, result1) => {​
if (err1) { /* handle error */ } else {​
asyncOperation2(result1, (err2, result2) => {​
if (err2) { /* handle error */ } else {​
asyncOperation3(result2, (err3, result3) => {​
if (err3) { /* handle error */ } else {​
//...and so on...​
}​
});​
}​
});​
}​
});​
3.3. Promises Deep Dive
Promises were introduced in ES6 to provide a more structured and manageable way
to handle asynchronous operations, specifically addressing the issues of callback
hell.6
●​ Concept: A Promise object represents the eventual outcome (completion or
failure) of an asynchronous operation and its resulting value.7 It acts as a
placeholder for a future value.57 An asynchronous function returns a promise
immediately, allowing the caller to attach handlers to it.54
●​ States: A promise exists in one of three states 15:
○​ pending: Initial state; the operation is not yet complete.
○​ fulfilled (or resolved): The operation completed successfully, and the promise
has a resulting value.
○​ rejected: The operation failed, and the promise has a reason (error). A
promise is considered "settled" once it is either fulfilled or rejected.57
●​ Creating Promises: Use the new Promise((resolve, reject) => {... }) constructor.
The executor function receives two arguments: resolve and reject. Call
resolve(value) when the operation succeeds, and reject(reason) when it fails.57​
JavaScript​
function delay(ms) {​
return new Promise((resolve, reject) => {​
if (ms < 0) {​
reject(new Error("Delay cannot be negative"));​
}​
setTimeout(() => resolve(`Delayed for ${ms}ms`), ms);​
});​
}​

●​ 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."​
});​

Promises represent a significant improvement by standardizing asynchronous


handling. Instead of passing callbacks into an asynchronous function 53, the function
returns a promise object.54 The caller then attaches handlers (.then, .catch) to this
object.54 This "inversion of control," combined with the composability of .then()
returning new promises 54, leads to more robust and readable asynchronous code
compared to callbacks.13

3.4. Promise Composition


The Promise object provides static methods for managing multiple promises
concurrently.
●​ Promise.all(iterable): Accepts an iterable (e.g., an array) of promises. It returns a
single promise that:
○​ Fulfills when all promises in the iterable have fulfilled. The fulfillment value is
an array of the fulfillment values from the input promises, in the same order.17
○​ Rejects immediately if any promise in the iterable rejects, with the rejection
reason of the first promise that rejected.17
○​ Use Case: Execute multiple independent async tasks and wait for all of them
to succeed before proceeding.
●​ Promise.race(iterable): Accepts an iterable of promises. It returns a single
promise that:
○​ Settles (fulfills or rejects) as soon as the first promise in the iterable settles.17
The returned promise adopts the state and value/reason of that first settled
promise.
○​ Use Case: Run multiple operations and take the result of the fastest one, or
implement timeouts for asynchronous operations.54
●​ Promise.allSettled(iterable) (ES2020): Accepts an iterable of promises. It
returns a single promise that:
○​ Fulfills when all promises in the iterable have settled (either fulfilled or
rejected).45
○​ The fulfillment value is an array of objects, each describing the outcome of
the corresponding input promise (e.g., {status: 'fulfilled', value:...} or {status:
'rejected', reason:...}).
○​ Use Case: Wait for multiple independent tasks to complete, regardless of
whether they succeeded or failed, often useful for cleanup or logging.
●​ Promise.any(iterable) (ES2021): Accepts an iterable of promises. It returns a
single promise that:
○​ Fulfills as soon as any promise in the iterable fulfills, with the fulfillment value
of that first fulfilled promise.
○​ Rejects only if all promises in the iterable reject. The rejection reason is an
AggregateError object containing all the individual rejection reasons.
○​ Use Case: Get the result from the first successful operation among several
alternatives.

3.5. async/await Syntax


Introduced in ES2017, async/await provides syntactic sugar built on top of Promises,
making asynchronous code look and feel more synchronous, thus improving
readability and maintainability.7
●​ async Keyword: When placed before a function declaration or expression, it
signifies that the function is asynchronous. An async function always implicitly
returns a Promise.18 If the function explicitly returns a value, that value becomes
the fulfillment value of the returned promise. If it returns a promise, that promise
is returned. If it throws an error, the returned promise is rejected with that error.52​
JavaScript​
async function myAsyncFunction() {​
return "Done!"; // Implicitly returns Promise.resolve("Done!")​
}​
async function anotherAsync() {​
throw new Error("Failed!"); // Implicitly returns Promise.reject(new Error("Failed!"))​
}​

●​ 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.");​
}​
}​

●​ Readability: Comparing the async/await version with an equivalent Promise chain


often demonstrates significantly improved clarity, especially for sequential
asynchronous steps.7

While async/await doesn't introduce fundamentally new asynchronous capabilities


beyond Promises, it drastically improves the developer experience.7 It allows
developers to structure asynchronous logic using familiar synchronous control flow
patterns (try/catch, sequential statements), reducing the cognitive load often
associated with .then() chaining and making complex asynchronous flows easier to
write, read, and debug.

Section 4: Advanced JavaScript Concepts


Beyond the fundamentals and ES6 features, several core concepts dictate how
JavaScript behaves in more complex scenarios. Understanding these is vital for
debugging and writing sophisticated code.

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.2. The this Keyword


The this keyword is a special identifier in JavaScript whose value is determined by the
execution context in which it is used.7 Unlike variables whose scope is lexically
determined, the value of this for regular functions is dynamically bound based on how
the function is called.34
●​ Global Context: Outside any function, this refers to the global object (window in
browsers, global in Node.js), unless in strict mode or an ES module, where it's
undefined.34
●​ Regular Function Call:
○​ Non-Strict Mode: When a function is called directly (e.g., myFunction()), this
defaults to the global object (window/global).22 If called with call/apply/bind
with null or undefined, it also defaults to the global object; primitives are
wrapped in their object equivalents.34
○​ Strict Mode: When called directly, this is undefined.22 If called with
call/apply/bind, this is exactly the value passed, even if it's null, undefined, or a
primitive.34
●​ Method Call: When a function is called as a property of an object (e.g.,
obj.method()), this refers to the object the method was called on (obj).17
●​ Arrow Function: Arrow functions (=>) do not have their own this binding. They
inherit this lexically from the surrounding scope where the arrow function was
defined.7 The value of this inside an arrow function cannot be changed using
bind, call, or apply.34
●​ Constructor Call: When a function is called with the new keyword (e.g., new
MyClass()), this is bound to the newly created object instance being
constructed.18
●​ DOM Event Handlers: Typically, this refers to the HTML element that triggered
the event, although this can be altered by how the handler is attached or if an
arrow function is used.51
●​ Explicit Binding:
○​ function.call(thisArg, arg1, arg2,...): Invokes the function immediately with this
set to thisArg and arguments passed individually.8
○​ function.apply(thisArg, [argsArray]): Invokes the function immediately with
this set to thisArg and arguments passed as an array.8
○​ function.bind(thisArg, arg1,...): Returns a new function where this is
permanently bound to thisArg. Optional arguments can also be pre-bound
(currying).8

The dynamic binding of this in regular functions is a frequent source of confusion,


particularly within callbacks where the context might be lost.34 Arrow functions, with
their lexical this, were introduced partly to alleviate this complexity and provide more
predictable behavior.22 Mastering the rules for determining this in each context is
essential for accurate JavaScript programming and interview success.

4.3. Prototypal Inheritance & The Prototype Chain


JavaScript employs prototypal inheritance, where objects inherit directly from other
objects.7 This contrasts with classical inheritance found in languages like Java or C++.
●​ [[Prototype]]: Every JavaScript object has an internal property, denoted as
[[Prototype]] in the specification, which is a link to another object or null.27 This
linked object is called the object's prototype.
●​ Prototype Chain: The [[Prototype]] link forms a chain. If an object's prototype
has its own prototype, the chain continues, eventually ending with an object
whose [[Prototype]] is null.73 Object.prototype is typically near the top of the
chain for most objects, and its [[Prototype]] is null.27
●​ Property Lookup: When you try to access a property or method on an object,
JavaScript first looks for it on the object itself (as an "own property"). If not
found, it follows the [[Prototype]] link to the object's prototype and searches
there. This continues up the chain until the property is found or the chain ends
(null).27 If the property is never found, accessing it yields undefined.
●​ Accessing/Setting the Prototype:
○​ Object.getPrototypeOf(obj): Standard way to get an object's prototype.73
○​ Object.setPrototypeOf(obj, prototype): Standard way to set an object's
prototype.73 Use with caution as it can impact performance.
○​ obj.__proto__: A legacy getter/setter for [[Prototype]]. Discouraged due to
performance and complexity issues.27
○​ Object.create(prototype): Creates a new object with its [[Prototype]] set to
the provided prototype object.73
●​ Constructor Functions and .prototype: Functions in JavaScript have a special
prototype property. When a function is used as a constructor with new (e.g., new
Person()), the newly created object's [[Prototype]] is automatically set to the
constructor function's prototype property (Person.prototype).18 This is how
instances created from the same constructor share methods defined on the
constructor's prototype.
●​ Inheriting Methods and this: When a method is called on an object, and that
method is inherited from its prototype, the this keyword inside the method still
refers to the object the method was called on, not the prototype object where the
method resides.27 This allows inherited methods to operate correctly on the
specific instance's data.
●​ Property Shadowing: If an object has an own property with the same name as a
property on its prototype chain, the own property "shadows" the prototype
property. Accessing the property will yield the value from the object itself.73
Writing to a property generally creates an own property on the object, rather than
modifying the prototype (unless the prototype property is a setter).27
●​ Classes and Prototypes: ES6 classes, while providing a different syntax, are built
upon this prototypal inheritance mechanism.2 Defining a class MyClass creates a
constructor function MyClass, and methods defined in the class body are added
to MyClass.prototype. The extends keyword manages the [[Prototype]] links
between subclass and superclass prototypes.47

Understanding the prototype chain is fundamental because it's JavaScript's core


inheritance model.73 It explains how objects access shared methods, how instanceof
works, how this behaves in inherited methods, and provides the foundation upon
which features like ES6 classes are built.

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​

○​ Event Handlers and Callbacks: Closures allow event handlers or


asynchronous callbacks to access variables that were present when the
handler was defined, maintaining state across asynchronous operations or
events.13
○​ Function Factories: Functions that create and return other functions, often
customized based on the arguments passed to the factory (e.g.,
makeAdder(5) returning a function that adds 5).37
○​ Currying and Partial Application: Techniques facilitated by closures where
functions are created that remember some arguments for later invocation.10
○​ Memoization: Caching function results based on arguments, often using
closures to store the cache.10
●​ Closures in Loops: A common interview scenario involves closures created inside
loops using var. Because var is function-scoped, a single variable binding is
shared across all loop iterations. Closures created within the loop (e.g., inside a
setTimeout callback) will all reference this single, final value of the loop variable
after the loop completes.8​
JavaScript​
// Problematic example​
for (var i = 0; i < 3; i++) {​
setTimeout(function() {​
console.log(i); // Logs 3, three times​
}, 100);​
}​
Solutions:
1.​ Use let or const: These have block scope, creating a new variable binding for
each iteration. The closure captures the specific binding for that iteration.8
This is the modern and preferred solution.​
JavaScript​
for (leti = 0; i < 3; i++) { // Use let​
setTimeout(function() {​
console.log(i); // Logs 0, 1, 2​
}, 100);​
}​

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.

4.5. The Event Loop


JavaScript achieves concurrency (handling multiple things seemingly at once) despite
being single-threaded through an event loop mechanism, typically provided by the
host environment (browser or Node.js).13
●​ Concurrency Model: A single thread executes JavaScript code. Asynchronous
operations are offloaded to the environment (Web APIs in browsers, system kernel
in Node.js). When these operations complete, their associated callback functions
are queued to be executed later by the main thread.62
●​ Components:
○​ Call Stack: Tracks function calls. Code execution happens here (Last-In,
First-Out).17
○​ Heap: Memory area for storing objects and variables.62
○​ Web APIs / Background Tasks: Environment features that handle
asynchronous tasks (e.g., setTimeout, DOM event listeners, fetch, file system
operations) outside the main JavaScript thread.31
○​ Callback Queue (Task Queue / Macrotask Queue): A queue (First-In,
First-Out) holding callbacks for completed macrotasks (e.g., setTimeout,
setInterval, I/O, UI rendering, user interaction events) ready to be executed.31
○​ Microtask Queue: A separate queue holding callbacks for completed
microtasks (e.g., Promise .then/.catch/.finally callbacks, queueMicrotask,
MutationObserver, process.nextTick in Node.js).13 This queue has higher
priority than the macrotask queue.31
●​ Execution Flow (Simplified):
1.​ The main script (synchronous code) executes completely, pushing function
calls onto and popping them off the Call Stack ("Run-to-completion" 64).
Asynchronous operations are initiated and handed off to Web APIs.
2.​ When the Call Stack becomes empty, the Event Loop first checks the
Microtask Queue.
3.​ If the Microtask Queue is not empty, the Event Loop takes all currently queued
microtasks, one by one, pushes their callbacks onto the Call Stack, and
executes them until the Microtask Queue is empty.18 Note: If executing a
microtask queues another microtask, that new microtask is added to the
queue and will also run in this same cycle before any macrotasks are
processed.79
4.​ Once the Microtask Queue is empty, the Event Loop checks the Macrotask
Queue (Task Queue).
5.​ If the Macrotask Queue is not empty, the Event Loop takes the oldest task
(one task only), pushes its callback onto the Call Stack, and executes it.62
6.​ After the macrotask finishes and the Call Stack is empty again, the loop
repeats from Step 2 (checking the Microtask Queue).

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.

Section 5: Tricky Interview Questions & Answers


This section presents common but potentially tricky interview questions designed to
test a deeper understanding of the concepts discussed previously.

Question 1: Closure & Loop Scope (var vs let)


Code:

JavaScript

const arr = [2, 9, 10, 11];​


for (var i = 0; i < arr.length; i++) {​
setTimeout(function() {​
console.log('Index: ' + i + ', element: ' + arr[i]);​
}, 100); // Delay added for clarity, behavior same with 0 or 3000​
}​

Question: What is the output and why?

Answer:
The output will be:

Index: 4, element: undefined​


Index: 4, element: undefined​
Index: 4, element: undefined​
Index: 4, element: undefined​

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

Question 2: this Keyword Context (Regular vs. Arrow)


Code:

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();​

Question: What is the output and why?

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.

Question 3: Hoisting Differences & TDZ


Code:
JavaScript

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();​

Question: What is the output and why?

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.

Question 4: Event Loop Order (Microtasks vs. Macrotasks)


Code:

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

Question 5: Prototypal Inheritance Nuance (Shadowing & this)


Code:

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:

Buddy says Woof! I am a Generic Dog.​


Lucy says Woof! I am a Labrador.​

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.

Question 6: Equality (== vs ===) and Type Coercion


Code:

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));​

Question: What is the result (true/false) of each comparison and why?

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.

A thorough understanding of these topics is paramount not only for success in


technical interviews but also for writing effective, maintainable, and robust JavaScript
applications. While memorizing syntax is helpful, grasping the underlying principles –
why let differs from var, how this is determined, the mechanics of the prototype chain,
the nature of closures, and the flow of the event loop – provides the foundation for
tackling complex problems. Continued practice, building projects 80, and consulting
authoritative resources like MDN 81 and javascript.info 17 are encouraged for further
mastery.

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/

You might also like