Prep Day-1: JavaScript Core with (React + Angular)

Prep Day-1: JavaScript Core with (React + Angular)

JavaScript Fundamentals — How JS Actually Works

Before React, Angular, or any framework — interviews test your JavaScript foundation.

This whole series is not for begineer, Its expected you should have knowledge and some experience in Javascript, Angular/React

We will go gradually from zero, and I will try to jump right into the topic.

For core JS I will do a small recap and then I will show some real world usecase in Angular and React

Let's revise some of the basic JS core concepts

Most developers learn JavaScript by usage, not by understanding.

That works — until interviews ask:

  • “How does JavaScript execute your code?”
  • “Why does hoisting behave differently for let and var?”
  • “What happens behind the scenes when a function runs?”

Senior frontend interviews don’t test what you write, they test what you understand.


JavaScript Runtime: The Big Picture

JavaScript is a single-threaded, synchronous language — but it runs in an environment.

JavaScript Runtime consists of:

  • JS Engine (e.g. V8)
  • Memory Heap (where data lives)
  • Call Stack (where code executes)
  • Web APIs (browser features)
  • Event Loop (task coordination)

JavaScript itself only knows stack + heap. Async behavior comes from the runtime environment, not JS itself.

JS Engine: How Code is Executed

Step-by-step:

  1. The JS engine receives the JS code
  2. JS engine then parse the JS code into tokens. (Tokens are keywords(let,const etc), operators ect ). Then JS engine parses this tokens to AST (Abstract Syntax Tree)
  3. After that JS engine compile the code using JIT(Just In Time) compilation
  4. Then it goes to Execution phase, (Execution contexts are also created) here we can see our result in browser. Here engine starts to interpert or JS code then copiled and display in browser
  5. Garbage Collection, which in a timely manner clean the unused variable etc
  6. Lastly the Event Loop checks call stack for any pending async tasks

Article content

Each execution context has:

  • Variable Environment
  • Lexical Environment
  • this binding


Execution Context (EC)

An Execution Context is the environment in which JavaScript code runs.

Whenever JS runs any code, it does inside an execution context

Think it of as a box that contains:

  • Variables
  • Functions
  • this value
  • Scope chain

Types:

  1. Global Execution Context :

  • Created once when JS file loads
  • Belongs to : Browser window | Node.js → global

  1. Function Execution Context:

  • Created every time a function is called
  • Destroyed after function execution completes

Phases:

1. Memory Creation Phase

  • Variables → undefined
  • Functions → full definition stored
  • this is set

console.log(a) //undefined
var a = 10        

2. Execution Phase

  • Code executes line-by-line
  • Values assigned
  • Functions invoked

var a = 10;

function foo() {
  var b = 20;
  console.log(a + b);
}

foo();        

What happens internally:

  • Global EC created
  • a → undefined (Creation Phase) → 10 (Execution Phase)
  • foo → stored in memory
  • foo() creates a new Function Execution Context
  • b → undefined(Creation Phase) → 20 (Execution Phase)
  • Output: 30

Another example:

var globalVar = 'Hello'; // Global Context

function greet(name) { // Function Context for greet()
  let localVar = 'World';
  console.log(globalVar + ', ' + name + ' ' + localVar);
  innerFunction(); // New Function Context for innerFunction()
}

function innerFunction() { // Function Context for innerFunction()
  console.log('Inside inner.');
}

greet('User'); // Invokes greet(), creating its Function EC        

LEXICAL ENVIRONMENT

A Lexical Environment is a structure that holds:

  1. Variables
  2. Function declarations
  3. Reference to its outer (parent) lexical environment

It defines where variables and functions are accessible in code.

Structure of a Lexical Environment

Each Lexical Environment has two parts:

Lexical Environment = {
  Environment Record,
  Outer Lexical Environment Reference
}        

  • Environment Record stores: a) Variables (let, const, var), b) Function declarations, c) Parameters
  • Outer Lexical Environment Reference Points to the parent scope and enables scope chain

Article content

Types of Lexical Environments

1. Global Lexical Environment

  • Created when JS starts
  • Outer reference → null
  • Contains global variables & functions

2. Function Lexical Environment

  • Created when a function is invoked
  • Outer reference → where the function was defined

3. Block Lexical Environment

  • Created for {} blocks (if, for, while)
  • Used by let & const

Article content

Lexical Scope

Variables are resolved based on where the function is written, not where it’s called.
let x = 100;

function foo() {
  console.log(x);
}

function bar() {
  let x = 200;
  foo();
}

bar();        

Output : 100

Why?

  • foo()’s lexical environment is global
  • It ignores bar()’s scope


SCOPE CHAIN

When a variable is used, JavaScript looks for it in the current scope, and if not found, it keeps moving outward through parent lexical environments until it finds it or reaches null.

Scope Chain = Current Scope → Parent Scope → Global Scope → null

How Scope Chain Works Internally

Scope Chain is created using:

  • Lexical Environments
  • Outer Lexical Environment References

Each scope knows where it was defined, not where it is executed.

let a = 10;

function outer() {
  let b = 20;

  function inner() {
    let c = 30;
    console.log(a, b, c);
  }

  inner();
}

outer();        

Scope Chain Lookup

inner → outer → global → null        

Output:

10 20 30        

Call Stack: How JS Manages Execution

Call Stack = Stack data structure that tracks execution context. It follows LIFO (Last In First Out)

Rules:

  • Last In → First Out (LIFO)
  • Each function call pushes a new stack frame
  • Function return pops the stack

Example:

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

In stack it will be like this

[
 c()
 b()
 a()
]        


Article content
A simple call stack with exection context

Stack Overflow:

A function calling itself

function infinite(){
 infinite()
}
infinite();        

Real-World Use Case

Understanding execution context helps you:

  • Debug stack overflow errors
  • Avoid infinite recursion
  • Understand async execution order
  • Optimize performance-heavy code

This is critical in:

  • Large React component trees
  • Angular services & interceptors
  • Event-heavy applications


Optimization Tips

Common performance mistakes:

  • Deep recursive calls
  • Large synchronous loops blocking the stack
  • Heavy computations in the main thread

Solutions:

  • Break tasks using async patterns
  • Use Web Workers for CPU-heavy work
  • Memoize expensive functions


Use Case in React

Each render creates a new execution context

function Counter() {
  const [count, setCount] = useState(0);

  console.log('render');

  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}        

Every time React re-renders this component, it calls this function again from scratch.

That means:

A brand-new function execution happens on every render

This new execution is what we call a new execution context.

Every render:

  • value → new random number
  • handleClick → new function reference
  • Old values are discarded

A common issue in React:

❌ Why does my variable reset on re-render?

function Timer() {
  let seconds = 0;

  setTimeout(() => {
    seconds++;
    console.log(seconds);
  }, 1000);

  return null;
}        

Bug seconds resets on every render because it lives in the execution context.

Fix with state or ref

const [seconds, setSeconds] = useState(0);        

or

const secondsRef = useRef(0);        

Think of React renders like this:

Render #1 → Execution Context #1
Render #2 → Execution Context #2
Render #3 → Execution Context #3        

❌ Nothing is shared unless we use any of the following hooks:

  • useState
  • useRef
  • useMemo
  • useCallback

Excessive re-render -> Stack pressure

This is why use:

  • useCallback
  • useMemo

not to “optimize everything”, but to control execution.

Use Case in Angular

1.) Does Change Detection runs inside execution contexts ?

Yes — but indirectly.Angular change detection runs as a result of JavaScript execution contexts, not as a separate thread or engine

Every time JS runs:

  • An execution context is created
  • Code runs on the call stack
  • Async callbacks re-enter via the event loop

Angular lives inside this JavaScript execution model.

Angular uses Zone.js to patch async APIs like:

  • setTimeout
  • Promise.then
  • DOM events
  • HTTP calls

Zone.js detects when an async task finishes.

When Does Change Detection Run?

After an async task completes and control returns to JS:

Async task finishes
→ JS execution context completes
→ Zone.js notifies Angular
→ Angular runs Change Detection        
Change Detection is triggered after JavaScript execution contexts complete, not inside the context itself.

Performance:

Because change detection is tied to JS execution:

  • Every async event can trigger CD
  • Large component trees = expensive checks
  • Uncontrolled async work = unnecessary CD cycles

This explains why:

  • OnPush works
  • runOutsideAngular() exists
  • Signals are faster
  • RxJS async patterns matter


React and Angular execution behavior.

Article content

System Design Perspective

When designing frontend systems:

  • Avoid long-running synchronous tasks
  • Design async-first architectures
  • Push heavy work off the main thread

REACT System Design Perspective:

1) Render = Stateless Function

  • Every render is a fresh function call
  • Local variables & functions are discarded
  • Nothing persists unless explicitly stored

Think serverless function invocation

2) Performance Design

  • Every render creates new function/object references
  • Causes unnecessary re-renders if uncontrolled

Stabilize interfaces, not everything (React.memo, useCallback, useMemo only where needed)

ANGULAR System Design Perspective:

In large Angular systems:

  • Treat change detection as execution cost
  • Minimize async triggers
  • Isolate heavy logic
  • Design predictable data flows

This is frontend execution management at scale.

INTERVIEW QUESTIONS

What is an execution context?

Explain memory creation vs execution phase

How does the call stack work?

How does execution context relate to closures?

Relationship between Execution Context and Call Stack        
REACT BASED :

Q1) Every time a React component renders, does a new JavaScript execution context get created?

My tips: Try to include this points

  • Yes, each function invocation creates a new execution context
  • Render ≠ DOM update
  • Re-render = function re-execution

Q2) Why do inline functions cause unnecessary re-renders?

  • Inline functions are recreated on every render
  • Each render produces a new function reference
  • New references break shallow comparison

Q3) How does React rendering interact with the JavaScript call stack?

  • Rendering is synchronous (unless concurrent mode)
  • Large component trees = deep stack usage
  • Blocking renders delay user interactions

Q4) Why does React require hooks to be called at the top level?

  • React identifies hooks by call order, not by name
  • Hook calls must occur in the same order on every render
  • React stores hook state using an internal index
  • Calling hooks conditionally changes the order
  • Changed order breaks hook–state mapping
  • This causes React to associate wrong state with wrong hooks
  • Top-level calls guarantee consistent execution context

Q5) How can a React app cause a stack overflow?

My tips: Try to include this points

  • Infinite recursive rendering
  • useEffect triggering state update without dependency control
  • Recursive component trees

Q6) How does understanding execution context help optimize React apps?

My tips: Try to include this points:

  • Memoizing functions avoids new execution contexts
  • Avoiding heavy synchronous work in render
  • Using useCallback and useMemo judiciously

ANGULAR BASED:

Q1) How does JavaScript execution affect Angular change detection?

Q2) What role does Zone.js play in Angular execution? (Not for new Angular with zoneless)

  • Patches async APIs
  • Detects task completion
  • Triggers change detection

Q3) Why does every click trigger change detection in Angular?

My tips: Try to include this points:

  • Click = async event
  • Zone.js intercepts it
  • Triggers CD for entire tree (default strategy)


Thats it for Day1. Try to focus in this topics and try to solve the answers.

If you want some more example please comment below, Also please give feedback if anything you want to change.

Every feedback is welcomed.


To view or add a comment, sign in

More articles by Souradip Panja

  • Prep Day-3: Scope Chain & Closures with (React + Angular)

    Have you ever wondered: How does a function remember variables after it finishes execution? Why do React hooks work the…

    1 Comment
  • Prep Day-2: JavaScript Core-2 with (React + Angular)

    Hoisting and are responsible for: Unexpected Broken callbacks Bugs in React event handlers Context loss in Angular…

  • Day 2- How LLMs Actually Think: Tokens, Context, and Temperature Explained Simply

    Before continuing, you can check my previous 2 articles also: Day-0: Basics of GenAI and LLM Day-1 of GenAI:…

    1 Comment
  • Day-1 of GenAI: Setup,Chat, Roles, and OpenAI-Compatible APIs

    If you’ve used ChatGPT before, you might think: “I already know how this works.” Then you open the documentation……and…

  • Day 0 of GenAI

    Today we will start our first GenAI journey. I will try to keep the article simple and engaging.

    2 Comments
  • Learning GenAI From Zero to Production

    Generative AI is no longer a future skill. It’s a present-day necessity.

  • Frontend Security - CSP

    INTRODUCTION Content Security Policy (CSP) is an extra layer of security against attacks such as cross-site scripting…

  • Render Blocking and Prevention

    In our daily web development, we have many faced some delay in rendering UI in the browser. This is generally known as…

    1 Comment
  • Optimizing Angular UI

    Sometime building website using Angular, cause some performance issue because of the bundle size. So for creating an…

  • BASIC INTRODUCTION OF BABEL

    Babel is a compiler which basically solve the problem of browser compatibility of the script. The problem that every…

Others also viewed

Explore content categories