important ES6 interview questions

🔰 Basic ES6 Interview Questions

1. What is ES6?

👉 ES6 (ECMAScript 2015) is the 6th version of JavaScript with modern features like let, const, arrow functions, etc.


2. Difference between var, let, and const?

Featurevarletconst
ScopeFunctionBlockBlock
Reassign
HoistingYesYes (TDZ)Yes (TDZ)

3. What is Temporal Dead Zone (TDZ)?

👉 Time between variable declaration and initialization where access causes error.

console.log(a); // ❌ error
let a = 10;

4. What are arrow functions?

👉 Short syntax for functions and no this binding.


5. Difference between normal function and arrow function?

👉 Arrow functions:

  • No this
  • No arguments
  • Cannot be used as constructor

🔥 Intermediate Questions

6. What is destructuring?

👉 Extract values from arrays/objects.

let {name} = {name: "Aditya"};

7. What is spread operator?

👉 Expands values.

let arr = [...[1,2,3]];

8. What is rest operator?

👉 Collects values.

function sum(...nums) {}

9. Difference between spread and rest?

👉 Spread = expand
👉 Rest = collect


10. What are template literals?

👉 Backticks (`) used for dynamic strings.


11. What are default parameters?

function greet(name = "Guest") {}

12. What are modules in ES6?

👉 Split code using import and export


🚀 Advanced ES6 Questions

13. What is this behavior in arrow functions?

👉 Arrow functions inherit this from parent scope.


14. Can we use arrow function as constructor?

👉 ❌ No


15. What is Symbol in ES6?

👉 Unique and immutable data type.

let id = Symbol("id");

16. What are iterators?

👉 Objects that allow looping (next() method).


17. What are generators?

👉 Functions that pause using yield.

function* gen() {
yield 1;
}

18. What is Map in ES6?

👉 Key-value collection (any type key allowed)


19. What is Set?

👉 Collection of unique values


20. Difference between Map and Object?

MapObject
Any key typeString keys
OrderedNot guaranteed
Better performanceLess efficient

💡 Coding-Based Questions

21. Swap variables using ES6

let a = 1, b = 2;
[a, b] = [b, a];

22. Merge arrays

let arr = [...arr1, ...arr2];

23. Clone object

let newObj = {...oldObj};

🎯 Pro Tip for Interview

👉 Most asked topics:

  • let vs const vs var
  • Arrow functions & this
  • Destructuring
  • Spread vs Rest
  • Modules

ES6 full form

👉 ECMAScript 2015

ECMAScript full form:

👉 European Computer Manufacturers Association Script


Explanation:

  • ECMA = European Computer Manufacturers Association
  • Script = Scripting language specification

👉 ECMAScript is the standard on which JavaScript is based.


Simple Line:

👉 ECMAScript = Standard version of JavaScript defined by ECMA organization

Explanation:

  • ECMAScript (ES) = Standard specification for JavaScript
  • ES6 = 6th version of ECMAScript
  • Released in 2015, so it’s also called ES2015

Simple Line:

👉 ES6 = ECMAScript 6 (ECMAScript 2015)

1️⃣2️⃣ ES6 Modern JavaScript

1️⃣ let & const

🔹 let

  • Block-scoped (only works inside { })
  • Can be reassigned
let age = 25;
age = 30; // ✅ allowed

🔹 const

  • Block-scoped
  • Cannot be reassigned (but objects/arrays can be modified)
const name = "Aditya";
// name = "Rahul"; ❌ errorconst user = { city: "Delhi" };
user.city = "Mumbai"; // ✅ allowed

2️⃣ Arrow Functions (=>)

Shorter way to write functions.

Normal Function

function add(a, b) {
return a + b;
}

Arrow Function

const add = (a, b) => a + b;

With one parameter

const greet = name => "Hello " + name;

3️⃣ Template Literals ( )

Use backticks instead of quotes → allows variables & multi-line strings.

let name = "Aditya";
let msg = `Hello ${name}, welcome!`;console.log(msg);

Multi-line

let text = `Line 1
Line 2
Line 3`;

4️⃣ Destructuring

Extract values from arrays/objects easily.

Array Destructuring

let arr = [10, 20, 30];
let [a, b] = arr;console.log(a); // 10

Object Destructuring

let user = { name: "Aditya", age: 22 };let { name, age } = user;

5️⃣ Spread Operator (...)

Expands elements (used to copy or merge).

Array Example

let arr1 = [1, 2];
let arr2 = [...arr1, 3, 4];console.log(arr2); // [1,2,3,4]

Object Example

let user = { name: "Aditya" };
let updated = { ...user, city: "Delhi" };

6️⃣ Rest Operator (...)

Collects multiple values into one variable.

function sum(...numbers) {
return numbers.reduce((total, num) => total + num);
}console.log(sum(1,2,3,4)); // 10

👉 Difference:

  • Spread → expands
  • Rest → collects

7️⃣ Modules (import / export)

Used to split code into multiple files.


Export (file: math.js)

export const add = (a, b) => a + b;
export const sub = (a, b) => a - b;

Import (file: app.js)

import { add, sub } from './math.js';console.log(add(5, 3));

Default Export

// math.js
export default function multiply(a, b) {
return a * b;
}
// app.js
import multiply from './math.js';

🔥 Quick Summary

FeatureUse
letvariable (changeable)
constfixed variable
Arrow functionshorter functions
Template literalsdynamic strings
Destructuringextract values
Spreadexpand data
Restcollect data
Modulessplit code

1️⃣1️⃣ Working With APIs

1️⃣ What is an API?

API = Application Programming Interface

👉 It allows two applications to communicate with each other.

Example:

  • Your app → requests weather data
  • Weather API → sends response (temperature, city, etc.)

👉 Like a waiter:

  • You (client) → request food
  • Waiter (API) → takes request
  • Kitchen (server) → prepares response

2️⃣ Fetch API

fetch() is used to get data from APIs

Basic Syntax:

fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));

Modern (Async/Await):

async function getData() {
try {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}getData();

3️⃣ JSON (JavaScript Object Notation)

👉 Most APIs return data in JSON format

Example JSON:

{
"name": "Aditya",
"age": 25,
"city": "Delhi"
}

Convert JSON:

let obj = JSON.parse(jsonString);   // JSON → JS Object
let json = JSON.stringify(obj); // JS Object → JSON

4️⃣ Handling API Response

When you call an API, response has:

let response = await fetch(url);console.log(response.status);   // 200, 404, etc.
console.log(response.ok); // true/false

Proper Handling:

if (response.ok) {
let data = await response.json();
console.log(data);
} else {
console.log("Error:", response.status);
}

5️⃣ Error Handling

👉 Always handle errors (network issues, wrong API, etc.)

Example:

async function fetchData() {
try {
let response = await fetch("https://api.example.com/data"); if (!response.ok) {
throw new Error("API Error");
} let data = await response.json();
console.log(data); } catch (error) {
console.log("Something went wrong:", error.message);
}
}

🚀 Practice Project 1: Weather App

Features:

  • Input city name
  • Show temperature, weather condition

API:

👉 https://openweathermap.org/api

Example Code:

async function getWeather() {
let city = document.getElementById("city").value; let url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=YOUR_API_KEY&units=metric`; try {
let res = await fetch(url);
let data = await res.json(); document.getElementById("result").innerHTML =
`🌡 Temp: ${data.main.temp}°C <br>
🌥 Weather: ${data.weather[0].description}`; } catch (err) {
console.log(err);
}
}

🎬 Practice Project 2: Movie Search App

Features:

  • Search movie by name
  • Show poster, title, year

API:

👉 http://www.omdbapi.com/

Example Code:

async function searchMovie() {
let movie = document.getElementById("movie").value; let url = `https://www.omdbapi.com/?apikey=YOUR_API_KEY&s=${movie}`; try {
let res = await fetch(url);
let data = await res.json(); let output = ""; data.Search.forEach(m => {
output += `
<div>
<h3>${m.Title}</h3>
<img src="${m.Poster}" width="100">
<p>${m.Year}</p>
</div>
`;
}); document.getElementById("result").innerHTML = output; } catch (err) {
console.log(err);
}
}

💡 Teaching Tip

Start students in this order:

  1. JSON basics
  2. fetch()
  3. API testing (Postman / browser)
  4. Small project (Weather)
  5. Bigger project (Movie search)

Add advanced features (loading, debounce, pagination)

20 important interview questions on Asynchronous JavaScript

🔥 Async JavaScript – Interview Questions

🟢 Basic Level (1–7)

1. What is Asynchronous JavaScript?

👉 JavaScript that allows tasks to run in the background without blocking the main thread.


2. Difference between synchronous and asynchronous?

  • Synchronous → Executes line by line (blocking)
  • Asynchronous → Executes without waiting (non-blocking)

3. What is setTimeout()?

👉 Runs a function once after a specified delay.


4. What is setInterval()?

👉 Runs a function repeatedly after a fixed interval.


5. What is a callback function?

👉 A function passed as an argument to another function and executed later.


6. What is callback hell?

👉 Nested callbacks that make code unreadable and hard to maintain.


7. Is JavaScript synchronous or asynchronous?

👉 Single-threaded but supports asynchronous behavior via event loop + Web APIs.


🟡 Intermediate Level (8–14)

8. What is a Promise?

👉 An object representing the eventual completion or failure of an async operation.


9. What are Promise states?

  • Pending
  • Fulfilled (Resolved)
  • Rejected

10. Difference between .then() and .catch()?

  • .then() → handles success
  • .catch() → handles errors

11. What is finally() in Promise?

👉 Runs after success or failure (cleanup code).


12. What is async/await?

👉 A cleaner way to handle Promises using synchronous-like syntax.


13. Can we use await without async?

👉 ❌ No, only inside async functions.


14. What happens if a Promise is rejected and not handled?

👉 It throws an Unhandled Promise Rejection error.


🔵 Advanced Level (15–20)

15. What is the Event Loop?

👉 It manages execution of asynchronous code (handles call stack + callback queue).


16. What is the Call Stack?

👉 A stack where JS executes function calls.


17. What is the difference between microtask and macrotask?

  • Microtask → Promise callbacks, queueMicrotask
  • Macrotask → setTimeout, setInterval, DOM events

👉 Microtasks execute first.


18. Output-based Question:

console.log("A");setTimeout(() => console.log("B"), 0);Promise.resolve().then(() => console.log("C"));console.log("D");

👉 Output:

A
D
C
B

19. What is Promise.all()?

👉 Runs multiple promises in parallel and resolves when all succeed.


20. Difference between Promise.all() and Promise.race()?

  • Promise.all() → waits for all
  • Promise.race() → returns first completed promise

💡 Bonus Tip (Important for Interviews)

👉 Most asked topics:

  • Event Loop
  • Promise vs async/await
  • Output questions
  • Error handling

🔟 Asynchronous JavaScript

1. Synchronous vs Asynchronous

✅ Synchronous (Blocking)

Code runs line by line, one after another.

console.log("Start");
console.log("Middle");
console.log("End");

👉 Output:

Start
Middle
End

Everything waits for the previous line to finish.


⚡ Asynchronous (Non-blocking)

Some tasks take time (API calls, timers). JS sends them to the background and continues execution.

console.log("Start");setTimeout(() => {
console.log("Middle");
}, 2000);console.log("End");

👉 Output:

Start
End
Middle

👉 JS doesn’t wait for setTimeout.


2. setTimeout()

Runs code once after a delay

setTimeout(() => {
console.log("Hello after 2 seconds");
}, 2000);

📌 2000 = milliseconds (2 seconds)


3. setInterval()

Runs code again and again at intervals

setInterval(() => {
console.log("Running every 1 second");
}, 1000);

👉 Stops only when cleared:

let id = setInterval(() => {
console.log("Hello");
}, 1000);clearInterval(id);

4. Callbacks

A callback is a function passed into another function to run later.

function greet(name, callback) {
console.log("Hi " + name);
callback();
}function sayBye() {
console.log("Bye!");
}greet("Aditya", sayBye);

❌ Callback Problem (Callback Hell)

setTimeout(() => {
console.log("Step 1");
setTimeout(() => {
console.log("Step 2");
setTimeout(() => {
console.log("Step 3");
}, 1000);
}, 1000);
}, 1000);

👉 Hard to read 😵


5. Promises

Promises solve callback problems.

👉 A Promise has 3 states:

  • Pending
  • Resolved (success)
  • Rejected (error)

Example:

let promise = new Promise((resolve, reject) => {
let success = true; if (success) {
resolve("Task completed");
} else {
reject("Task failed");
}
});

Using Promise:

promise
.then(result => console.log(result))
.catch(error => console.log(error));

6. async / await (Modern Way)

Cleaner way to use Promises.


Example:

function getData() {
return new Promise(resolve => {
setTimeout(() => {
resolve("Data received");
}, 2000);
});
}async function fetchData() {
let result = await getData();
console.log(result);
}fetchData();

👉 await pauses function until result comes.


🌐 Practice: API Data Fetch

Using fetch + then()

fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));

Using async/await (BEST WAY)

async function getPosts() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/posts");
let data = await response.json();
console.log(data);
} catch (error) {
console.log("Error:", error);
}
}getPosts();

🧠 Simple Analogy

  • Synchronous = One worker doing tasks one by one
  • Asynchronous = Multiple workers handling tasks in background

🚀 Practice Tasks (Important)

Try these:

  1. Print numbers 1–5 using setTimeout
  2. Create a digital clock using setInterval
  3. Fetch user data from API and display in HTML
  4. Convert callback code into Promise
  5. Convert Promise into async/await

real-style JavaScript questions asked by companies like Google, Amazon, Microsoft

Real Company-Level JavaScript Questions


1️⃣ (Amazon) – Closure + Loop Trap

for (var i = 0; i < 5; i++) {
setTimeout(() => console.log(i), i * 1000);
}

❓ Output:

5 5 5 5 5

💡 Why?

var is function-scoped → same i shared

✅ Fix:

for (let i = 0; i < 5; i++) {
setTimeout(() => console.log(i), i * 1000);
}

2️⃣ (Google) – Event Loop Priority

console.log("A");setTimeout(() => console.log("B"), 0);Promise.resolve().then(() => console.log("C"));console.log("D");

❓ Output:

A
D
C
B

💡 Why?

Microtasks (Promise) run before macrotasks (setTimeout)


3️⃣ (Amazon) – this Binding

const user = {
name: "Aditya",
greet() {
return function () {
console.log(this.name);
};
}
};user.greet()();

❓ Output:

undefined

💡 Why?

Returned function is called independently → this lost

✅ Fix:

return () => console.log(this.name);

4️⃣ (Google) – Hoisting Edge Case

console.log(foo());function foo() {
return "Hello";
}var foo = 10;

❓ Output:

Hello

💡 Why?

Function declaration takes priority over variable


5️⃣ (Microsoft) – Object Key Trick

const obj = {};obj[{}] = "A";
obj[{}] = "B";console.log(obj);

❓ Output:

{ "[object Object]": "B" }

💡 Why?

Objects used as keys are converted to string


6️⃣ (Amazon) – Async/Await Trick

async function test() {
console.log(1);
await Promise.resolve();
console.log(2);
}console.log(3);
test();
console.log(4);

❓ Output:

3
1
4
2

💡 Why?

await pauses → rest runs in microtask queue


7️⃣ (Google) – Prototype Behavior

function Person(name) {
this.name = name;
}Person.prototype.sayHi = function () {
return "Hi " + this.name;
};const p1 = new Person("A");
const p2 = new Person("B");p1.sayHi = function () {
return "Hello";
};console.log(p1.sayHi());
console.log(p2.sayHi());

❓ Output:

Hello
Hi B

💡 Why?

Method override only affects p1


8️⃣ (Amazon) – Chained Promises

Promise.resolve(1)
.then(x => x + 1)
.then(x => { throw new Error("Error"); })
.then(x => console.log(x))
.catch(() => 100)
.then(x => console.log(x));

❓ Output:

100

💡 Why?

Error goes to .catch(), then continues chain


9️⃣ (Google) – typeof Weirdness

console.log(typeof typeof 1);

❓ Output:

string

💡 Why?

typeof 1 → “number” (string), then typeof → string


🔟 (Amazon) – Array Mutation

const arr = [1, 2, 3];arr[10] = 99;console.log(arr.length);

❓ Output:

11

💡 Why?

Array becomes sparse


1️⃣1️⃣ (Google) – Equality Trap

console.log([] == ![]);

❓ Output:

true

💡 Why?

  • ![] → false
  • [] == false → true (coercion)

1️⃣2️⃣ (Amazon) – Function Currying

function add(a) {
return function (b) {
return function (c) {
return a + b + c;
};
};
}console.log(add(1)(2)(3));

❓ Output:

6

1️⃣3️⃣ (Google) – delete Operator

const obj = { name: "Aditya" };delete obj.name;
console.log(obj.name);

❓ Output:

undefined

1️⃣4️⃣ (Amazon) – Floating Precision

console.log(0.1 + 0.2 === 0.3);

❓ Output:

false

💡 Why?

Floating-point precision issue


1️⃣5️⃣ (Google) – setTimeout Order

for (let i = 1; i <= 3; i++) {
setTimeout(() => console.log(i), 0);
}console.log("Done");

❓ Output:

Done
1
2
3

🚀 What Companies Check

They are testing:

  • Deep understanding (not memorization)
  • Event loop mastery
  • Closures & scope
  • this behavior
  • Async handling

🎯 Pro Tip

In interviews:

  1. First predict output
  2. Then explain step-by-step
  3. Then suggest fix/improvement

Tricky JS Output Questions


1️⃣ Hoisting + var

console.log(a);
var a = 10;

Output:

undefined

Why?
var a is hoisted → initialized with undefined


2️⃣ Hoisting + let

console.log(a);
let a = 10;

Output:

ReferenceError

Why?
let is in Temporal Dead Zone


3️⃣ Function vs Variable Hoisting

var a = 10;function a() {
console.log("Hello");
}console.log(a);

Output:

10

Why?
Function is hoisted first, but var a = 10 overrides it


4️⃣ Closure Trick

function test() {
var a = 1;

return function () {
console.log(a);
};
}var fn = test();
test()();
fn();

Output:

1
1

Why?
Closure remembers a


5️⃣ setTimeout + var (Classic 🔥)

for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000);
}

Output:

3
3
3

Why?
var is function-scoped → same i


6️⃣ setTimeout + let

for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000);
}

Output:

0
1
2

Why?
let creates new block scope each iteration


7️⃣ this Keyword

const obj = {
name: "Aditya",
greet: function () {
console.log(this.name);
}
};const fn = obj.greet;
fn();

Output:

undefined (or window.name)

Why?
Function is called without object → this lost


8️⃣ Arrow Function this

const obj = {
name: "Aditya",
greet: () => {
console.log(this.name);
}
};obj.greet();

Output:

undefined

Why?
Arrow function doesn’t have its own this


9️⃣ == vs ===

console.log(0 == false);
console.log(0 === false);

Output:

true
false

🔟 NaN Trick

console.log(NaN == NaN);
console.log(NaN === NaN);

Output:

false
false

👉 Use:

isNaN(NaN); // true

1️⃣1️⃣ typeof null

console.log(typeof null);

Output:

object

👉 This is a JavaScript bug


1️⃣2️⃣ Implicit Coercion

console.log("5" + 2);
console.log("5" - 2);

Output:

"52"
3

1️⃣3️⃣ Array + Object

console.log([] + []);
console.log([] + {});
console.log({} + []);

Output:

""
"[object Object]"
0 // tricky!

1️⃣4️⃣ Boolean Conversion

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

Output:

true
false

1️⃣5️⃣ Closures in Loop (Fix Version)

for (var i = 0; i < 3; i++) {
(function (i) {
setTimeout(() => console.log(i), 1000);
})(i);
}

Output:

0
1
2

1️⃣6️⃣ Function Inside Block

if (true) {
function test() {
console.log("Hello");
}
}
test();

Output:

Hello

👉 (Behavior can vary in strict mode)


1️⃣7️⃣ Chained Assignment

var a = b = 10;
console.log(b);

Output:

10

👉 b becomes global variable (bad practice)


1️⃣8️⃣ Object Reference

let obj1 = { name: "A" };
let obj2 = obj1;obj2.name = "B";console.log(obj1.name);

Output:

B

👉 Objects are assigned by reference


1️⃣9️⃣ Event Loop Order 🔥

console.log("Start");setTimeout(() => console.log("Timeout"), 0);Promise.resolve().then(() => console.log("Promise"));console.log("End");

Output:

Start
End
Promise
Timeout

2️⃣0️⃣ Function Length

function test(a, b, c = 3) {}
console.log(test.length);

Output:

2

👉 Default params are not counted


🚀 Interview Strategy

If you master these:

  • Hoisting
  • Closures
  • this
  • Event Loop
  • Type coercion

👉 You can clear 90% JS interviews

Advanced JavaScript Interview Q&A


1️⃣ What is Scope in JavaScript?

Answer:
Scope determines where variables are accessible.

  • Global Scope → accessible everywhere
  • Function Scope → inside function
  • Block Scope → inside {} (let, const)
let a = 10;function test() {
let b = 20;
}

👉 b is not accessible outside the function.


2️⃣ What is Hoisting?

Answer:
Hoisting is JavaScript’s default behavior of moving declarations to the top.

console.log(a); // undefined
var a = 5;

👉 var is hoisted with undefined

⚠️ let and const are hoisted but in Temporal Dead Zone


3️⃣ What is a Closure?

Answer:
A closure is a function that remembers variables from its outer scope.

function outer() {
let count = 0; return function () {
count++;
return count;
};
}let fn = outer();
fn(); // 1
fn(); // 2

👉 Used in:

  • Data hiding
  • Private variables
  • Callbacks

4️⃣ What is Execution Context?

Answer:
Execution context is the environment where JavaScript code runs.

Types:

  • Global Execution Context
  • Function Execution Context

Phases:

  1. Memory creation
  2. Code execution

5️⃣ What is Call Stack?

Answer:
Call stack is a structure that keeps track of function calls (LIFO).

function a() { b(); }
function b() { console.log("Hi"); }a();

👉 Stack:
a → b → console.log


6️⃣ What is this keyword?

Answer:
this refers to the object that calls the function.

let obj = {
name: "Aditya",
show() {
console.log(this.name);
}
};

Important cases:

  • Object → refers to object
  • Function → window / undefined
  • Arrow → inherits from parent

7️⃣ Difference between call, apply, and bind?

Answer:

function greet(city) {
console.log(this.name + " from " + city);
}let user = { name: "Aditya" };greet.call(user, "Delhi");
greet.apply(user, ["Delhi"]);let fn = greet.bind(user);
fn("Delhi");

👉 Difference:

  • call → arguments separately
  • apply → arguments as array
  • bind → returns new function

8️⃣ What is Prototype?

Answer:
Prototype is an object from which other objects inherit properties.

function Person(name) {
this.name = name;
}Person.prototype.sayHi = function () {
console.log("Hi " + this.name);
};

9️⃣ What is Prototypal Inheritance?

Answer:
Objects inherit properties from another object.

let parent = {
greet() {
console.log("Hello");
}
};let child = Object.create(parent);
child.greet();

🔟 What is the difference between == and ===?

Answer:

  • == → compares value (type conversion happens)
  • === → compares value + type
"5" == 5   // true
"5" === 5 // false

1️⃣1️⃣ What is Event Loop? (Bonus 🔥)

Answer:
Event loop handles async operations in JavaScript.

👉 Flow:

  • Call Stack
  • Web APIs
  • Callback Queue
  • Event Loop

1️⃣2️⃣ What is Temporal Dead Zone?

Answer:
Time between variable hoisting and initialization.

console.log(a); // Error
let a = 10;

1️⃣3️⃣ What are Arrow Functions?

Answer:
Short syntax functions that don’t have their own this.

const add = (a, b) => a + b;

1️⃣4️⃣ What is Difference: var vs let vs const?

Featurevarletconst
ScopeFunctionBlockBlock
HoistingYesYes (TDZ)Yes (TDZ)
ReassignYesYesNo

1️⃣5️⃣ What is a Higher Order Function?

Answer:
Function that takes another function as argument or returns a function.

function greet(fn) {
fn();
}

🚀 Pro Tip for Interviews

Focus on:

  • Writing code
  • Explaining output
  • Real-world examples

9️⃣ Advanced JavaScript

1️⃣ Scope

Scope defines where variables are accessible in your code.

Types:

  • Global Scope → accessible everywhere
  • Function Scope → inside a function
  • Block Scope → inside {} (let, const)
let a = 10; // globalfunction test() {
let b = 20; // function scope
if (true) {
let c = 30; // block scope
}
}

👉 c is NOT accessible outside block.


2️⃣ Hoisting

Hoisting means variables and functions are moved to the top of their scope during execution.

console.log(a); // undefined
var a = 5;

Internally becomes:

var a;
console.log(a);
a = 5;

⚠️ Important:

  • var → hoisted with undefined
  • let/const → hoisted but in temporal dead zone

3️⃣ Closures

Closure = function + its lexical environment

A function remembers variables from its outer scope.

function outer() {
let count = 0; return function inner() {
count++;
console.log(count);
};
}let fn = outer();
fn(); // 1
fn(); // 2

👉 inner() remembers count even after outer() is finished.


4️⃣ Execution Context

When JS runs code, it creates an execution context.

Types:

  • Global Execution Context (GEC)
  • Function Execution Context (FEC)

Phases:

  1. Memory Creation Phase
  2. Execution Phase
var x = 10;function test() {
var y = 20;
}

👉 JS first allocates memory, then executes line by line.


5️⃣ Call Stack

Call Stack = how JavaScript manages function calls

function a() {
b();
}
function b() {
console.log("Hello");
}
a();

Stack flow:

a()
b()
console.log()

👉 Last In → First Out (LIFO)


6️⃣ this Keyword

this refers to the object that is calling the function

Examples:

let obj = {
name: "Aditya",
greet: function () {
console.log(this.name);
}
};obj.greet(); // Aditya

Rules:

  • In object → refers to object
  • In function → window (or undefined in strict mode)
  • In arrow function → inherits from parent

7️⃣ Prototype

Every JavaScript object has a prototype, which is another object.

function Person(name) {
this.name = name;
}Person.prototype.sayHello = function () {
console.log("Hello " + this.name);
};let p1 = new Person("Aditya");
p1.sayHello();

👉 sayHello is shared among all objects (memory efficient)


8️⃣ Prototypal Inheritance

Objects can inherit properties from another object

let parent = {
greet() {
console.log("Hello");
}
};let child = Object.create(parent);child.greet(); // Hello

👉 child inherits from parent


🧠 Quick Summary

ConceptMeaning
ScopeWhere variables are accessible
HoistingVariables/functions moved to top
ClosuresFunction remembers outer variables
Execution ContextEnvironment where code runs
Call StackTracks function calls
thisRefers to calling object
PrototypeShared object properties
InheritanceOne object uses another’s properties