Diving Deeper into
JavaScript
Advanced Concepts & ES6 Foundations
Agenda
1 Stack Overflow
when functions keep calling themselves without stopping 4 we'll learn about the famous error: "Maximum call stack size
exceeded."
2 arguments Object
A special object inside functions that holds all passed arguments, even if they¾re not explicitly defined in parameters.
3 Tips using arguments
How to convert it to an array, differences between arguments and Rest Parameters, and why it doesn't work in arrow
functions.
4 Stack vs Heap (Memory Model)
A simple explanation of how JavaScript stores data: primitive values in the Stack, and objects in the Heap.
5 Scope Chain
The way JavaScript searches for variables: from local to outer to global scope 4 including how
closures work.
6 this Keyword
The mysterious keyword! We'll explore how its value depends on the context: global, function,
object, and arrow functions.
7 Classes (ES6)
A cleaner syntax to create objects using class, with constructor, extends, and super() for
inheritance.
8 Modules(ES6)
Learn how to split code into reusable files using export and import, making your code more
modular and maintainable.
Stack Overflow in JavaScript
What is Stack Overflow?
In JavaScript, Stack Overflow happens when the call stack 4 the place where function calls are tracked 4 becomes too full
because functions keep calling themselves recursively without an end.
This causes the famous error:
Uncaught RangeError: Maximum call stack size exceeded
Example 3 Causing Stack Overflow
function callMe() {
return callMe(); // Recursive call with no base case
}
callMe(); // Stack Overflow
Every time callMe() runs, it adds a new frame to the call stack 4 forever 4 until it crashes!
Why Does It Happen?
Recursive function with no stop condition.
Infinite loop of function calls.
Can happen unintentionally in circular dependencies.
Fixing Stack Overflow: Add a Base Case
function countdown(n) {
if (n <= 0) return; // Base case
[Link](n);
countdown(n - 1); // Recursive step
}
countdown(5);
// Output:
// 5
// 4
// 3
// 2
// 1
Always make sure your recursive function has a base case that stops it eventually.
Use loops instead of recursion when possible 4 they¾re usually safer for deep repetitions in JavaScript, which has a small
stack size compared to other languages.
The arguments Object in JavaScript
What is the arguments Object?
The arguments object is a built-in array-like object available inside regular functions. It holds all the arguments passed to the
function 4 even if the parameters don¾t explicitly declare them.
Only available in:
Regular functions
Not available in:
Arrow functions
Global scope
Example 1 3 Basic Use
function showArgs() {
[Link](arguments);
}
showArgs(10, 20, 30);
// Output: [Arguments] { '0': 10, '1': 20, '2': 30 }
It behaves like an array, but it¾s not a real array.
Useful Properties
Feature Description
[Link] Number of arguments passed
arguments[0] Access individual argument by index
function sum() {
[Link]("First arg:", arguments[0]);
[Link]("Total args:", [Link]);
}
sum(5, 10, 15);
Looping over arguments
function total() {
let sum = 0;
for (let i = 0; i < [Link]; i++) {
sum += arguments[i];
}
[Link]("Sum:", sum);
}
total(1, 2, 3, 4); // Sum: 10
Limitations
It's not a real array 4 no .map(), .forEach(), etc.
Use [Link](arguments) to convert it:
let arr = [Link](arguments);
Arrow Functions DO NOT have arguments
const test = () => {
[Link](arguments); // ReferenceError
};
Alternative (ES6): Rest Parameters
function showAll(...args) {
[Link](args); // real array
}
Tips Using the arguments Object
1. Convert arguments to a Real Array
The arguments object is array-like, but not a true array. You can't use .map(), .filter(), or .reduce() directly.
Use [Link]() or the spread operator to convert it:
function show() {
let arr = [Link](arguments);
[Link]([Link](x => x * 2)); // Now we can use .map()
}
show(1, 2, 3); // [2, 4, 6]
2. Check the Number of Arguments Passed
function logArgs() {
[Link]("Arguments passed:", [Link]);
}
logArgs(10, 20); // Arguments passed: 2
3. Access Specific Argument by Index
function greet() {
[Link]("First name:", arguments[0]);
[Link]("Last name:", arguments[1]);
}
greet("Belal", "Nagy");
4. arguments is Dynamic
Even if the function doesn't define parameters, you can still get the values:
function mystery() {
[Link](arguments[0] + arguments[1]);
}
mystery(5, 7); // Output: 12
5. Not Available in Arrow Functions
const show = () => {
[Link](arguments); // ReferenceError
};
Instead, use rest parameters in ES6:
const show = (...args) => {
[Link](args); // [1, 2, 3]
};
Summary Table
Tip Works With arguments? Notes
[Link](arguments) Yes Convert to real array
[Link] Yes Count number of passed arguments
Access via index arguments[0] Yes Works like array index access
Works in arrow functions No Use rest parameters instead (...args)
Stack vs Heap 3 Memory Model in JavaScript
Why Understand Memory?
JavaScript stores different types of data in different memory locations. Understanding this helps you avoid bugs related to
mutability and reference behavior.
Stack Memory (Fast & Simple)
Used for primitive data types:
Number, String, Boolean, undefined, null, Symbol, BigInt
Stored directly in the stack
Copied by value
Heap Memory (Flexible & Complex)
Used for non-primitive (reference) types:
Object, Array, Function, Date, etc.
Stored in the heap, but variables hold a reference (pointer) Copied by reference
Key Differences
Feature Stack Heap
Speed Very Fast Slower
Data Type Primitive Non-Primitive (Objects, Arrays)
Copy Behavior By Value By Reference
Storage Fixed-size, Sequential Dynamic
Access Direct Indirect via reference
Common Mistake: Misunderstanding Copy Behavior
let arr1 = [1, 2];
let arr2 = arr1;
[Link](3);
[Link](arr1); // [1, 2, 3] Modified!
Both arr1 and arr2 point to the same memory in the heap.
If You Want to Truly Copy an Object/Array
Use spread operator or structured cloning:
let arrCopy = [...arr1]; // Shallow copy
Scope Chain in JavaScript
What is Scope?
Scope is the current context of execution 4 where variables and functions are accessible.
Types of Scope in JavaScript
1. Global Scope 3 accessible anywhere
2. Function Scope 3 available only inside the function
3. Block Scope (ES6) 3 available inside {} when using let or const
What is the Scope Chain?
JavaScript looks for variables using a chain of scopes 4 from local to outer to global.
If a variable is not found in the current scope, JS goes up one level 4 until it finds it or throws an error.
Example 3 Scope Chain in Action
let a = 10;
function outer() {
let b = 20;
function inner() {
let c = 30;
[Link](a); // Found in global ² 10
[Link](b); // Found in outer ² 20
[Link](c); // Found in inner ² 30
}
inner();
}
outer();
JavaScript checks scopes from inside out.
Example 3 Variable Not Found
function show() {
[Link](x); //ReferenceError: x is not defined
}
show();
x doesn't exist in any scope 4 JS can't find it up the chain.
Visual Representation
inner()
±
outer()
±
global()
Each function forms a lexical scope, and JS resolves variables by climbing upward.
Pro Tip
Closures rely on the scope chain to access variables from their outer function even after it returns.
The this Keyword in JavaScript
What is this?
The this keyword refers to the execution context 4 it depends on how the function is called, not where it's written.
Different this Values Based on Context
Context this refers to...
Global scope The window (in browser)
Inside object method The object itself
Inside regular function undefined in strict mode (window in non-strict)
Arrow function Inherits this from its parent
Event handler The DOM element (usually)
call(), apply(), bind() Custom value
Example 1 3 Global Scope
[Link](this); // window (in browser)
Example 2 3 Object Method
const person = {
name: "Belal",
greet: function () {
[Link]("Hello", [Link]); // this = person
}
};
[Link](); // Hello Belal
Example 3 3 Regular Function (Strict Mode)
"use strict";
function show() {
[Link](this); //undefined
}
show();
Example 4 3 Arrow Function
const user = {
name: "Belal",
greet: () => {
[Link]([Link]); //undefined (inherits from parent/global)
}
};
[Link](); // Doesn't work as expected
Example 5 3 Arrow Function Inside Method
const user = {
name: "Belal",
greet: function () {
const inner = () => {
[Link]([Link]); //Belal (inherited from greet())
};
inner();
}
};
[Link](); // Belal
Example 6 3 Using call() to Set this
function sayHello() {
[Link]("Hi", [Link]);
}
const person = { name: "Nagy" };
[Link](person); // Hi Nagy
Common Mistakes
Arrow functions should not be used for object methods if you rely on this.
Don¾t assume this is static 4 it changes based on how the function is called.
JavaScript Classes (ES6)
Why Classes in JavaScript?
Before ES6, we used constructor functions and prototypes to define reusable object templates. ES6 introduced the class syntax 4
a cleaner and more readable way to do OOP in JavaScript.
Basic Class Syntax
class Person {
constructor(name, age) {
[Link] = name;
[Link] = age;
}
greet() {
[Link](`Hello, my name is ${[Link]}`);
}
}
const belal = new Person("Belal", 25);
[Link](); // Hello, my name is Belal
Explanation:
class Person ³ declares a class.
constructor() ³ gets called automatically when you use new.
greet() ³ instance method, shared by all objects created from the class.
Old Way vs ES6 Class
// Old Way (Pre-ES6)
function Person(name) {
[Link] = name;
}
[Link] = function () {
[Link](`Hi, I'm ${[Link]}`);
};
// ES6 Way
class Person {
constructor(name) {
[Link] = name;
}
sayHi() {
[Link](`Hi, I'm ${[Link]}`);
}
}
Both work the same 4 but the class version is more readable and organized.
Inheritance using extends and super()
class Animal {
constructor(name) {
[Link] = name;
}
speak() {
[Link](`${[Link]} makes a sound.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // call the parent constructor
[Link] = breed;
}
speak() {
[Link](`${[Link]} barks.`);
}
}
const dog = new Dog("Rex", "German Shepherd");
[Link](); // Rex barks.
Explanation:
extends ³ creates a subclass that inherits from Animal.
super(name) ³ calls the parent constructor.
You can override parent methods like speak().
Key Features of ES6 Classes
Feature Description
constructor() Special method called when creating an object
Instance Methods Defined inside the class, shared across instances
extends Enables inheritance from another class
super() Calls the parent class¾s constructor
No commas Unlike object syntax, no commas between methods
Important Notes
Classes are syntactic sugar 4 they use prototypes under the hood.
Class declarations are not hoisted like functions.
const p = new Person(); //ReferenceError
class Person {}
JavaScript Modules (ES6)
Why Use Modules?
Before ES6, JavaScript didn¾t support native modules 4 developers had to use patterns like IIFE or tools like Webpack.
With ES6 Modules, you can:
Split code across multiple files
Reuse functions & variables
Keep your code clean, organized, and maintainable
Basic Structure of a Module
// file: [Link]
export function add(a, b) {
return a + b;
}
export const PI = 3.14;
// file: [Link]
import { add, PI } from './[Link]';
[Link](add(2, 3)); // 5
[Link](PI); // 3.14
Default Export vs Named Export
Named Export (multiple per file)
// [Link]
export function sum(a, b) { return a + b; }
export function diff(a, b) { return a - b; }
import { sum, diff } from './[Link]';
Default Export (only one per file)
// [Link]
export default function log(msg) {
[Link]("Log:", msg);
}
import log from './[Link]';
Note: You can rename it on import.
import myLogger from './[Link]';
You Can Combine Both
// [Link]
export const port = 3000;
export default "localhost";
import host, { port } from './[Link]';
Important Notes About Modules
Modules are strict mode by default
Module files must be loaded with type="module" in HTML:
<script type="module" src="[Link]"></script>
Relative paths must include the file extension (.js)
Code inside modules is scoped 4 variables won¾t leak globally
Use Case Example 3 Project Structure
project/
'
=%% [Link] ³ Entry point
=%% [Link] ³ export add(), subtract()
5%% [Link] ³ export default + named config values
This structure helps scale your apps and work as a team.
Recap: Import/Export Syntax
Task Syntax Example
Named Export export function fn() {}
Named Import import { fn } from './[Link]'
Default Export export default fn;
Default Import import fn from './[Link]'
Mixed Import import def, { x, y } from './[Link]'
ES6 Modules 3 Execution & Behavior
How JavaScript Loads Modules
Traditional Script Tags
<script src="[Link]"></script>
Scripts block the HTML parser
Loaded and executed immediately
Execution is synchronous
async vs defer in Script Loading
Attribute When Loaded When Executed Order Preserved?
async In background As soon as it's ready No
defer In background After HTML is parsed Yes
<script async src="[Link]"></script>
<script defer src="[Link]"></script>
Modules Are Like defer by Default
<script type="module" src="[Link]"></script>
Loaded asynchronously
Executed after the HTML is fully parsed
Behaves like defer You don¾t need to add defer manually
Exporting & Importing from Modules
// [Link]
export const name = "Belal";
export function greet() {
[Link]("Hello");
}
// [Link]
import { name, greet } from "./[Link]";
All Module Variables Are Scoped
Every module has its own private scope
Variables inside a module are not global
Other scripts cannot access them unless explicitly exported
Imported Members Are Read-Only
import { name } from "./[Link]";
name = "Nagy"; //Error: Assignment to constant variable
You can¾t reassign an imported binding 4 it¾s read-only.
You Must Use Full Path for Module Imports
Example Path What It Means
"./[Link]" Current folder
"../[Link]" One level up
"/[Link]" Root directory
import { greet } from "./utils/[Link]";
Always include the .js extension!
Modules Run in Browser or Server Environment
In the browser, use <script type="module">
In [Link], use .mjs or "type": "module" in [Link]
Modules Are Strict Mode by Default
// Inside a module
x = 10; //Error: x is not defined
No need to write "use strict" 4 it¾s automatically applied in modules.
Recap
Topic Key Point
Stack Overflow Infinite recursion without base case
arguments Array-like object in regular functions
Memory Stack for primitives, Heap for objects
Scope Chain Lexical resolution of variables
this Depends on how the function is called
Classes Clean OOP syntax with inheritance support
Modules Scoped, async, strict, import/export system