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