[Go to site: main page, start]

0% found this document useful (0 votes)
4 views29 pages

Java Script

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)
4 views29 pages

Java Script

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

JavaScript is a programming language that runs mostly in web browsers.

It makes web pages


interactive—things like buttons responding to clicks, forms validating input, images changing
on hover, or live updates without refreshing the page.

For example:

• HTML builds the structure of a webpage.


• CSS styles how it looks.
• JavaScript makes it do things (dynamic behavior).

👉 Example in action:
If you press a button and the background color changes—JavaScript is working behind the
scenes.

The <script> Tag


In HTML, JavaScript code is inserted between <script> and </script> tags.
JavaScript is everywhere, it comes installed on every modern web browser and so
to learn JavaScript, you really do not need any special environment setup

JavaScript Variables
JavaScript variables are used to store data that can be changed later on.
Declare the variables in 4 ways −
Without using any keywords. (Not Recommended)
Using the ' var' keyword. (Not Recommended)
Using the ' let' keyword.
Using the ' const' keyword.
**************
let x = 5;
let y = 6;
let z = x + y;
const x = 5;
const y = 6;
const z = x + y;

JavaScript Identifiers
Variables are identified with unique names called identifiers.

• Names can contain letters, digits, underscores, and dollar signs.


• Names must begin with a letter, a $ sign or an underscore (_).
• Names are case sensitive (X is different from x).
• Reserved words (JavaScript keywords) cannot be used as names.

let $ = "Hello World"; let _lastName = "Johnson";


JavaScript const Keyword
The const keyword is introduced in the ES6 version of JavaScript with the let keyword. The const
keyword is used to define the variables having constant reference.

A variable defined with const can't be re-declared, reassigned

const x = 10; // Correct Way


const y; // Incorrect way
y = 20;

COMMENT: // single line comment


/* and */. Multi Line comment

JavaScript Data Types


1. Primitive Data Types (single, immutable values)

• String → Text data ("Hello", 'Hi')


• Number → All numbers (integer, decimal, Infinity, NaN)
• BigInt → Very large integers (12345678901234567890n)
• Boolean → Logical values (true, false)
• Undefined → Variable declared but not assigned a value
• Null → Intentional empty value

2. Non-Primitive (Reference) Data Types

• Object → Collection of key–value pairs ({name: "Alex", age: 25})


• Array → Ordered list ([1, 2, 3]

let name = "John"; // String


let age = 30; // Number
let big = 1234567890n; // BigInt
let isStudent = true; // Boolean
let score; // Undefined
let salary = null; // Null
***********
let person = { name: "John", age: 30 }; // Object
let numbers = [1, 2, 3]; // Array
function greet() { return "Hello"; } // Function

OPERATORS:
The Assignment Operator (=) assigns a value to a variable: let x = 10;
Airthmatic Opearator – PPT
let x = 100 + 50; let x = (100 + 50) * a;
Logical Operators
AND (&&)OR (||)NOT (!)
[Link](true && true); // true [Link](true && false); // false
Nullish Coalescing (??)Returns the right-hand value only if the left-hand value is null or
undefined.
let name = null;
[Link](name ?? "Guest"); // Guest

Template Literals (`backticks`)


Template literals allow you to create strings easily, especially when you need to embed
variables or write multi-line strings.

let name = "Alice";


let age = 21;
// Old way (concatenation)
[Link]("My name is " + name + " and I am " + age + " years old.");
// New way (template literals)
[Link](`My name is ${name} and I am ${age} years old.`);

Spread Operator (...)


It is used to expand elements of an array or object.
Think: "Unpack values".

Example – Arrays:
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];

// Spread: expand arr1 into arr2


let combined = [...arr1, ...arr2];
[Link](combined); // [1, 2, 3, 4, 5, 6]

Example – Objects:
let user = { name: "Alice", age: 21 };
let extra = { country: "India" };
let profile = { ...user, ...extra };
[Link](profile);

Rest Operator (...)


It is used to collect multiple values into an array.
Think: "Pack values".
let [first, ...rest] = [10, 20, 30, 40];
[Link](first); // 10
[Link](rest); // [20, 30, 40]

What is Destructuring?
Destructuring in JavaScript allows you to extract values from arrays or objects and store them
in separate variables easily.

Think of it as “pulling out values” from a structure instead of accessing them one by one.

1️⃣ Array Destructuring


let numbers = [10, 20, 30];

// Extract values into variables


let [a, b, c] = numbers;

[Link](a); // 10
[Link](b); // 20
[Link](c); // 30

✅ You can also skip elements:

let [first, , third] = numbers;


[Link](first, third); // 10 30
Destructuring with Rest

Combine with rest operator to get remaining values.

Array Example:

let [first, ...rest] = [1, 2, 3, 4];


[Link](first); // 1
[Link](rest); // [2, 3, 4]

Object Example:

let { name, ...others } = { name: "Alice", age: 21, country: "India" };


[Link](name); // Alice
[Link](others); // { age: 21, country: "India" }

Conditional Statements
The if else statement
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if the condition1 is false and condition2 is true
} else {
// code to execute if the condition1 is false and condition2 is false
}

Example
let age = 18;
if (age >= 18) {
[Link]("You are eligible to vote.");
} else {
[Link]("You are not eligible to vote.");
}

The switch Statement


switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

Example
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
[Link]("Today is " + dayName);

Ternary operator
The ternary operator ? : is a shorthand way of writing if...else.
condition ? expression1 : expression2
Example
let age = 18;
let result = (age >= 18) ? "You are eligible to vote." : "You are not eligible to vote.";
[Link](result);

FOR LOOP
for (let i = 1; i <= 5; i++) {
[Link]("Number:", i);
}

WHILE LOOP:
let i = 1;
while (i <= 5) {
[Link]("Number:", i);
i++;
}

do...while loop
let i = 6;
do {
[Link]("Number:", i);
i++;
} while (i <= 5);

Type Coercion
JavaScript is a loosely typed language, so it can automatically convert one type to another.
This is called type coercion.
Types of Coercion
Implicit Coercion (automatic by JS)
[Link]('5' + 2); // "52" (number → string)
[Link]('5' - 2); // 3 (string → number)
[Link](1 == '1'); // true (string → number)
Explicit Coercion (done by developer)
[Link](Number('123')); // 123
[Link](String(123)); // "123"
[Link](Boolean(0)); // false

What is Strict Mode?

• It’s a special mode in JavaScript that makes the language more strict.
• Helps you catch errors early instead of letting JS silently do weird things.
• You turn it on with: 'use strict';

Without strict mode, JavaScript sometimes allows mistakes, which can cause bugs.

Example 1: Using undeclared variables


x = 10; // No 'let', 'var', or 'const'
[Link](x);
✅ JavaScript allows this normally.
❌ But it’s dangerous because you might accidentally overwrite a variable.

With strict mode:

'use strict';
x = 10; // ❌ ReferenceError: x is not defined
JS stops you and tells you there’s an error.

Simple Calculator (Addition, Subtraction, Multiplication, Division)


Note: parseFloat() in JavaScript is a function that converts a string into a floating-point number
(decimal number). When you use prompt(), the value you get is always a string.

let num1 = parseFloat(prompt("Enter first number:"));


let num2 = parseFloat(prompt("Enter second number:"));
let operator = prompt("Enter operator (+, -, *, /):");
let result;
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num2 !== 0 ? num1 / num2 : "Cannot divide by zero";
break;
default:
result = "Invalid operator";
}
alert("Result: " + result);

2. Number Guessing Game

// Number Guessing Game


let secretNumber = [Link]([Link]() * 10) + 1; // Random 1–10
let guess;
let attempts = 0;

do {
guess = parseInt(prompt("Guess a number between 1 and 10:"));
attempts++;

if (guess > secretNumber) {


alert("Too high! Try again.");
} else if (guess < secretNumber) {
alert("Too low! Try again.");
} else {
alert(`🎉 Correct! The number was ${secretNumber}. You guessed it in ${attempts}
attempts.`);
}

} while (guess !== secretNumber);

Functions:
With functions you can reuse code

You can use the same code with different arguments, to produce different results.

Function Invocation ()
The code inside the function will execute when "something" invokes (calls) the function:

• When it is invoked (called) from JavaScript code


• When an event occurs (a user clicks a button)
• Automatically (self invoked)

Syntax:
function functionName(parameters) {
// code to run
return value; // optional
}
Example
function add(a, b) {
return a + b;
}
[Link](add(5, 3)); // 8

Note: a,b are paramaters


3,4 are arguments

Function Expression :Function is stored in a variable.


Syntax
const functionName = function(parameters) {
// code
return value;
};

const multiply = function(x, y) {


return x * y;
};
[Link](multiply(4, 5)); // 20

Arrow Functions
Arrow introduced in [Link] functions allow us to write shorter function syntax.
let myFunction = function(a, b) {return a * b} //without arrow
let myFunction = (a, b) => a * b; //with arrow
SCOPE:

1. Global Scope
o Declared outside any function. Accessible anywhere in the code.

let globalVar = "I am global";


function show() {
[Link](globalVar); // accessible here
}
show();
[Link](globalVar); // accessible here too

What is a Callback Function?


A callback function is a function passed as an argument to another function, which is then
called inside that [Link] for delaying execution until a task is done (like events,
timers, or async operations).

function greet(name) {
[Link]("Hello " + name);
}

function processUser(name, callback) {


[Link]("Processing user...");
callback(name); // calling the callback function
}
processUser("Alice", greet);

Callback in Array Methods

let numbers = [1, 2, 3, 4];


// callback function used in map
let squared = [Link](function(num) {
return num * num;
});
[Link](squared); // [1, 4, 9, 16]

What is a Local Variable?

A local variable is a variable that is declared inside a function (or block) and can only be used
inside that [Link] cannot be accessed outside the function.

function greet() {
let message = "Hello, World!"; // local variable
[Link](message); // works here
}
greet();
[Link](message); // ❌ Error: message is not defined

Why use local variables?

1. Keeps variables safe from outside code.


2. Avoids conflicts with other variables with the same name.
3. Helps organize code logic clearly.

Block Scope (ES6): Variables declared with let or const inside { } are also local to that block.
if (true) {
let x = 10; // local to this block
const y = 20;
[Link](x, y); // 10 20
}
[Link](x, y); // ❌ Error

Hoisting in JavaScript
Hoisting is JavaScript’s behavior of moving variable and function declarations to the top of their scope
before code runs.

Function Hoisting: Function declarations can be called before they are defined.
sayHi(); // works!

function sayHi() {
[Link]("Hello!");
}

Hoisted but not initialized → cannot be used before declaration


Accessing them early causes ReferenceError
[Link](b); // ❌ ReferenceError
let b = 10;
[Link](c); // ❌ ReferenceError
const c = 20;

Hands-on: Create utility functions


Function to Check if a Number is Even
const isEven = (num) => num % 2 === 0;
[Link](isEven(4)); // true
[Link](isEven(7)); // false

Function to Calculate Factorial


function factorial(n) {
if (n === 0 || n === 1) return 1;
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
[Link](factorial(5)); // 120
[Link](factorial(0)); // 1
**********************************
ARRAY METHODS
1. push()
let fruits = ["apple", "banana"];
[Link]("mango");
[Link](fruits); // ["apple", "banana", "mango"]

2. pop(): Remove the last element from array


let numbers = [10, 20, 30];
let removed = [Link]();
[Link](numbers); // [10, 20]
[Link](removed); // 30

3. map(): 👉 Creates a new array by applying a function to each element.


let nums = [1, 2, 3, 4];
let squared = [Link](n => n * n);
[Link](squared); // [1, 4, 9, 16]

4. Filter():Creates a new array with elements that pass a condition.


let ages = [12, 18, 25, 30, 15];
let adults = [Link](age => age >= 18);
[Link](adults); // [18, 25, 30]

5. reduce(): 👉 Reduces array to a single value (sum, product, etc.).


let numbers2 = [1, 2, 3, 4, 5];
let sum = [Link]((acc, curr) => acc + curr, 0);
[Link](sum); // 15
for...of
👉 Loops through values of an iterable (like arrays, strings, sets, maps).
👉 Simpler than forEach when you just need values.
let fruits = ["apple", "banana", "mango"];
for (let fruit of fruits) {
[Link](fruit);
}

JavaScript Array forEach(): The forEach() method calls a function (a callback function) once
for each array element.
const numbers = [45, 4, 9, 16, 25];
let txt = "";
[Link](myFunction);

function myFunction(value, index, array) {


txt += value + "<br>";
}

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

// forEach - print square of each


[Link](num => [Link](num * num));

// for...of - stop loop if number is 3


for (let num of arr) {
if (num === 3) break;
[Link](num);
}

******************
HANDS ON
Filter Even Numbers from array:
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let evenNumbers = [Link](num => num % 2 === 0);
[Link]("Even Numbers:", evenNumbers);

Shopping Cart Total


👉 Each item has a name and price.
👉 We’ll use reduce() to calculate the total price.

let cart = [
{ name: "Shirt", price: 500 },
{ name: "Jeans", price: 1200 },
{ name: "Shoes", price: 2000 }
];
let total = [Link]((sum, item) => sum + [Link], 0);
[Link]("Cart Total: ₹" + total);
1. Object Literals: 👉 An object literal is simply an object written directly using { } with key–value pairs.

let person = {
name: "Alice",
age: 25,
city: "Delhi"
};
[Link]([Link]); // Alice
[Link]([Link]); // 25
2. Nested Objects: An object can have another object inside it (this is called nested object).
let student = {
name: "John",
age: 20,
address: {
city: "Mumbai",
pincode: 400001
}
};
[Link]([Link]); // John
[Link]([Link]); // Mumbai
[Link]([Link]); // 400001
3. Nested Objects with Arrays: You can also mix objects and arrays.
let company = {
name: "TechCorp",
employees: [
{ name: "Sara", role: "Developer" },
{ name: "Mike", role: "Designer" }
]
};
[Link]([Link][0].name); // Sara
[Link]([Link][1].role); // Designer

******************THIS
1. this in Global Context: In the browser, this refers to the window [Link] strict mode, it
becomes undefined.

[Link](this); // Window (in browser)

2. this in Object Methods: Inside an object method, this refers to the object itself.
let person = {
name: "Alice",
greet: function() {
[Link]("Hi, I am " + [Link]);
}
};

[Link](); // Hi, I am Alice

3. this in Functions: In a normal function, this refers to the global object (or undefined in strict mode).

function show() {
[Link](this);
}
show(); // Window (in browser) or undefined (strict mode)

4. this in Arrow Functions: Arrow functions do not have their own .They inherit this from their
this

surrounding scope.

let user = {
name: "Bob",
greet: () => {
[Link]("Hi, I am " + [Link]);
}
};

[Link](); // Hi, I am undefined (because arrow function takes 'this' from global)

👉 Solution: Use a normal function inside objects when you need this.

🔹 5. this in Constructors / Classes:In constructor functions or classes, this refers to the newly
created object.
function Person(name) {
[Link] = name;
}

let p1 = new Person("Charlie");


[Link]([Link]); // Charlie

What is Object Destructuring?


👉 It’s a short and easy way to extract values from objects and assign them to variables.
Basic Example
let person = {
name: "Alice",
age: 25,
city: "Delhi"
};

// Old way
let name1 = [Link];
let age1 = [Link];

// Using destructuring
let { name, age, city } = person;

[Link](name); // Alice
[Link](age); // 25
[Link](city); // Delhi

Assigning to Different Variable Names:

let student = {
fullName: "John Doe",
grade: "A"
};
let { fullName: studentName, grade: studentGrade } = student;
[Link](studentName); // John Doe
[Link](studentGrade); // A

Nested Object Destructuring

let employee = {
id: 101,
details: {
dept: "IT",
location: "Bangalore"
}
};

let { details: { dept, location } } = employee;


[Link](dept); // IT
[Link](location); // Bangalore

⃣ Destructuring in Function Parameters

function showUser({ name, age }) {


[Link](`${name} is ${age} years old`);
}

let user1 = { name: "Ravi", age: 30 };


showUser(user1); // Ravi is 30 years old

Student Record System Example


// Student records as an array of objects
let students = [
{ id: 1, name: "Alice", age: 20, grade: "A" },
{ id: 2, name: "Bob", age: 22, grade: "B" },
{ id: 3, name: "Charlie", age: 21, grade: "A" }
];

// Add a new student


function addStudent(id, name, age, grade) {
[Link]({ id, name, age, grade });
}

// Remove a student by id
function removeStudent(id) {
students = [Link](student => [Link] !== id);
}

// Find a student by name


function findStudent(name) {
return [Link](student => [Link] === name);
}

// Get all students with a specific grade


function studentsByGrade(grade) {
return [Link](student => [Link] === grade);
}

// Calculate average age


function averageAge() {
let total = [Link]((sum, s) => sum + [Link], 0);
return (total / [Link]).toFixed(2);
}
[Link]("All Students:", students);

addStudent(4, "David", 23, "C");


[Link]("After Adding David:", students);

removeStudent(2);
[Link]("After Removing Bob:", students);
[Link]("Find Charlie:", findStudent("Charlie"));
[Link]("Grade A Students:", studentsByGrade("A"));
[Link]("Average Age:", averageAge());

*********************

DOM (Document Object Model)


The DOM is a representation of your web page that JavaScript can interact with.

• Think of it as a tree structure where every HTML element is a node.


• It allows JavaScript to read, change, add, or remove elements dynamically.

• Document → your HTML page.


• Object Model → turns HTML tags into JavaScript objects.

<!DOCTYPE html>
<html>
<body>
<h1 id="title">Hello</h1>
<p>Welcome to DOM!</p>
</body>
</html>

Document
└── html
└── body
├── h1 (id="title")
└── p

[Link]

Selecting elements in JavaScript using getElementById and querySelector.


getElementById()
Selects an element by its id.
Returns a single element.
Change content
<!DOCTYPE html>
<html>
<body>
<h1 id="title">Hello</h1>
<p>Welcome to DOM!</p>
<script>
// Change the text of the h1 element
[Link]("title").textContent = "Hi, DOM!";
</script>
</body>
</html>

Change style
[Link]("title").[Link] = "red";

Add or remove elements

let newP = [Link]("p");


[Link] = "New paragraph!";
[Link](newP);

Selecting elements in JavaScript using querySelector.


querySelector()
Selects the first element that matches a CSS selector (#id, .class, tag).
Can select by id, class, or tag name.

<!DOCTYPE html>
<html>
<body>
<p class="message">First message</p>
<p class="message">Second message</p>
<script>
// Select first element with class 'message'
const firstMsg = [Link](".message");
[Link]([Link]); // First message
// Change text
[Link] = "Updated message!";
</script>
</body>
</html>

querySelectorAll()
Selects all elements matching a CSS selector.
Returns a NodeList, which can be looped with forEach

<p class="item">Item 1</p>


<p class="item">Item 2</p>
<p class="item">Item 3</p>

<script>
const items = [Link](".item");

[Link](el => {
[Link] = "blue"; // change text color of all items
});
</script>

innerHTML and classList for DOM manipulation


innerHTML
Used to get or set the HTML content inside an element.
<!DOCTYPE html>
<html>
<body>
<h1 id="title">Hello</h1>
<script>
// Replace text with bold HTML
[Link]("title").innerHTML = "<b>Hi, DOM!</b>";
</script>
</body>
</html>
textContent vs innerHTML

textContent

o Changes only the text.


o Treats everything as plain text (no HTML tags).

innerHTML

o Changes text + HTML.


o If you give it HTML, the browser renders it.

[Link]("title").innerHTML = "<b>Hi, DOM!</b>";


// Output on page: Hi, DOM! (bold text)

classList
• Lets you add, remove, toggle, or check CSS classes.
• Useful for styling dynamically.
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
color: white;
background-color: green;
padding: 5px;
}
</style>
</head>
<body>
<p id="text">This is a paragraph.</p>

<script>
// Add CSS class immediately
[Link]("text").[Link]("highlight");
</script>
</body>

</html>
*****************
Event handling in JavaScript
A JavaScript can be executed when an event occurs, like when a user clicks on an HTML
element.
To execute code when a user clicks on an element, add JavaScript code to an HTML
event attribute:

>

Examples of HTML events:

• When a user clicks the mouse


• When a web page has loaded
• When an image has been loaded
• When the mouse moves over an element
• When an input field is changed
• When an HTML form is submitte

<!DOCTYPE html>
<html>
<body>
<h1 = 'Ooops!'">Click on this text!</h1>
</body>
</html>
****************
<!DOCTYPE html>
<html>
<body>
<h1 on this text!</h1>
<script>
function changeText(id) {
[Link] = "Ooops!";
}
</script>
</body>
</html>

The addEventListener() method

• Used to attach an event (like click, input, mouseover, etc.) to an element.


• Syntax:

[Link](event, function);

<!DOCTYPE html>
<html>
<body>

<h2 id="text">Hello!</h2>
<button id="btn">Click Me</button>

<script>
const button = [Link]("btn");
const text = [Link]("text");

// Attach click event using addEventListener


[Link]("click", function() {
[Link] = "You clicked the button!";
[Link] = "green";
});
</script>
</body>
</html>

**********
<!DOCTYPE html>
<html>
<body>
<h1 id="title">Hover over me</h1>
<script>
const title = [Link]("title");

// Add mouseover event


[Link]("mouseover", function () {
[Link] = "You hovered over me!";
[Link] = "blue";
});

// Add mouseout event


[Link]("mouseout", function () {
[Link] = "Hover over me";
[Link] = "black";
});
</script>
</body>
</html>

*********************
What are Modules?
• Modules allow you to split your code into separate files.
• Each file can export variables, functions, or objects, and other files can import them.
• Helps make code organized and reusable.
Exporting
// Named exports
export function add(a, b) {
return a + b;}
export const pi = 3.14;

Importing
// [Link]
import { add, pi } from './[Link]';

[Link](add(2, 3)); // 5
[Link](pi); // 3.14

What is a Class?
A class is a blueprint for creating objects with properties (data) and methods (functions).
It’s similar to classes in other programming languages like Java or C++.

• Introduced in ES6.
• Makes object-oriented programming easier in JS.
class ClassName {
// constructor
constructor(parameters) {
// initialize object properties
}

// methods
methodName() {
// code
}}

Constructor

• A constructor is a special method inside a class.


• It runs automatically when you create a new object using new.
• Used to initialize properties.

class Student {
constructor(name, age) {
[Link] = name; // object property
[Link] = age;
}

// Method
introduce() {
[Link](`Hi, I am ${[Link]} and I am ${[Link]} years old.`);
}
}

// Create objects
const student1 = new Student("Alice", 15);
const student2 = new Student("Bob", 16);

// Call method
[Link](); // Hi, I am Alice and I am 15 years old.

[Link](); // Hi, I am Bob and I am 16 years old.

✅ Key points:

• [Link] → refers to the property of the current object.


• new Student(...) → creates a new object using the class blueprint.
• introduce() → method available to all objects of the class.

Class Methods
• Methods are functions inside a class.
• Can access object properties using this.

class Calculator {
constructor(a, b) {
this.a = a;
this.b = b;
}
add() {
return this.a + this.b;
}
multiply() {
return this.a * this.b;
}
}
const calc = new Calculator(5, 10);
[Link]([Link]()); // 15
[Link]([Link]()); // 50

Static Methods
• static methods belong to the class itself, not the objects.
• Called directly using the class name, not this.

class MathUtil {
static square(x) {
return x * x;
}
}
[Link]([Link](5)); // 25

Getters and Setters


• Getter → access property like a variable
• Setter → modify property safely

class Person {
constructor(name) {
this._name = name;
}

// getter
get name() {
return this._name;
}

// setter
set name(newName) {
if([Link] > 0) this._name = newName;
}
}

const p = new Person("Alice");


[Link]([Link]); // Alice
[Link] = "Bob";
[Link]([Link]); // Bob

Inheritance
One class can extend another class to reuse properties and methods.

class Car {
constructor(brand) {
[Link] = brand;
}
present() {
return 'I have a ' + [Link];
}
}

class Model extends Car {


constructor(brand, mod) {
super(brand);
[Link] = mod;
}
show() {
return [Link]() + ', it is a ' + [Link];
}
}

let myCar = new Model("Ford", "Mustang");


[Link](myCar)

✅ extends → inherit properties and methods


✅ super() → call the parent class constructor (used in derived class)

What are Getters and Setters?


Getters and Setters are special methods inside a class that let you access and modify object
properties safely.

• Getter (get) → Allows you to read a property like a normal variable, but you can run
some code behind it.
• Setter (set) → Allows you to update a property while performing validation or extra logic

Why getter and setter have the same name?


• In JavaScript, getter and setter are meant to represent the same property.
• You want to read and write the same property ([Link]), but with custom logic.
• That’s why they share the same “public name” (name) even though internally you can
use _name to store the value.

Think of an object property like a bank account balance:

• Getter = reading your balance (you can see it, but cannot change it directly)
• Setter = depositing or withdrawing money (checks if the operation is valid before
changing balance)

class Person {
constructor(name) {
this._name = name; // internal property
}

get name() { // read


return this._name;
}

set name(value) { // write


if([Link] > 0) this._name = value;
else [Link]("Invalid name");
}
}

const p = new Person("Alice");


[Link]([Link]); // getter runs → Alice
[Link] = "Bob"; // setter runs → changes _name
[Link]([Link]);
[Link] = ""; // ❌ invalid
[Link]([Link]); // Bob (unchanged)
********************
JavaScript Callbacks
"I will call back later!"
A callback is a function passed as an argument to another function. This technique allows a function to
call another function
A callback function can run after another function has finished
Normal calling of the Function
function myDisplayer(some) {
[Link](`hello${some}`)
}
function mylogger(some) {
[Link](`hi${some}`)
}

function myCalculator(num1, num2) {


let sum = num1 + num2;
return sum;
}
let result = myCalculator(5, 5);
myDisplayer(result);
mylogger(result);

NOTE: Problem with example above, is that you have to call two functions to display the result.

Call a calculator function (myCalculator), and let the calculator function call the display function
(myDisplayer):
function myDisplayer(some) {
[Link](`hello${some}`)
}
function mylogger(some) {
[Link](`hi${some}`);
}

function myCalculator(num1, num2) {


let sum = num1 + num2;
myDisplayer(sum);
}

myCalculator(5, 5);

Note: The problem with the second example, is that you cannot prevent the calculator function
from displaying the result.

JavaScript Callbacks
A callback is a function passed as an argument to another function.
function myDisplayer(some) {
[Link](`hello${some}`)
}
function mylogger(some) {
[Link](`hi${some}`);
}

function myCalculator(num1, num2, myCallback) {


let sum = num1 + num2;
myCallback(sum);
}

myCalculator(5, 5, myDisplayer);
myCalculator(5, 5, mylogger);

Note: now you can call any function from myCalculator

Asynchronous JavaScript
Functions running in parallel with other functions are called asynchronous
A good example is JavaScript setTimeout()
In the real world, callbacks are most often used with asynchronous functions.
A typical example is JavaScript setTimeout().
setTimeout() is a built-in JavaScript function that allows you to run code after a delay (in
milliseconds).
It is asynchronous → meaning the rest of your code continues to run without waiting.

Why do we need async?


Imagine a website fetching user data from a server.
If it was synchronous, the whole page would freeze until the server replied.
With async, the page stays responsive, and data loads when ready

SYNTAX:
setTimeout(callback, delay, param1, param2, ...);
callback → Function to run after the delay.
delay → Time in milliseconds (1000 ms = 1 second).
param1, param2,... → (optional) values you can pass to the callback.

Example 1: Basic use


[Link]("Start");
setTimeout(() => {
[Link]("Hello after 2 seconds");
}, 2000);
[Link]("End");
Example 2: Passing a function

function greet() {
[Link]("Good morning!");
}
setTimeout(greet, 3000); // Call greet after 3 sec

Example 3: Passing arguments


function greet(name, age) {
[Link](`Hello ${name}, you are ${age} years old`);
}
setTimeout(greet, 2000, "Tulika", 37);

You might also like