Java Script
Java Script
For example:
👉 Example in action:
If you press a button and the background color changes—JavaScript is working behind the
scenes.
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.
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
Example – Arrays:
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
Example – Objects:
let user = { name: "Alice", age: 21 };
let extra = { country: "India" };
let profile = { ...user, ...extra };
[Link](profile);
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.
[Link](a); // 10
[Link](b); // 20
[Link](c); // 30
Array Example:
Object Example:
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.");
}
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
• 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.
'use strict';
x = 10; // ❌ ReferenceError: x is not defined
JS stops you and tells you there’s an error.
do {
guess = parseInt(prompt("Guess a number between 1 and 10:"));
attempts++;
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:
Syntax:
function functionName(parameters) {
// code to run
return value; // optional
}
Example
function add(a, b) {
return a + b;
}
[Link](add(5, 3)); // 8
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.
function greet(name) {
[Link]("Hello " + name);
}
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
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!");
}
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);
******************
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);
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.
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]);
}
};
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;
}
// Old way
let name1 = [Link];
let age1 = [Link];
// Using destructuring
let { name, age, city } = person;
[Link](name); // Alice
[Link](age); // 25
[Link](city); // Delhi
let student = {
fullName: "John Doe",
grade: "A"
};
let { fullName: studentName, grade: studentGrade } = student;
[Link](studentName); // John Doe
[Link](studentGrade); // A
let employee = {
id: 101,
details: {
dept: "IT",
location: "Bangalore"
}
};
// Remove a student by id
function removeStudent(id) {
students = [Link](student => [Link] !== id);
}
removeStudent(2);
[Link]("After Removing Bob:", students);
[Link]("Find Charlie:", findStudent("Charlie"));
[Link]("Grade A Students:", studentsByGrade("A"));
[Link]("Average Age:", averageAge());
*********************
<!DOCTYPE html>
<html>
<body>
<h1 id="title">Hello</h1>
<p>Welcome to DOM!</p>
</body>
</html>
Document
└── html
└── body
├── h1 (id="title")
└── p
[Link]
Change style
[Link]("title").[Link] = "red";
<!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
<script>
const items = [Link](".item");
[Link](el => {
[Link] = "blue"; // change text color of all items
});
</script>
textContent
innerHTML
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:
>
<!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>
[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");
**********
<!DOCTYPE html>
<html>
<body>
<h1 id="title">Hover over me</h1>
<script>
const title = [Link]("title");
*********************
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
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.
✅ Key points:
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
class Person {
constructor(name) {
this._name = name;
}
// getter
get name() {
return this._name;
}
// setter
set name(newName) {
if([Link] > 0) this._name = newName;
}
}
Inheritance
One class can extend another class to reuse properties and methods.
class Car {
constructor(brand) {
[Link] = brand;
}
present() {
return 'I have a ' + [Link];
}
}
• 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
• 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
}
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}`);
}
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}`);
}
myCalculator(5, 5, myDisplayer);
myCalculator(5, 5, mylogger);
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.
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.
function greet() {
[Link]("Good morning!");
}
setTimeout(greet, 3000); // Call greet after 3 sec