JAVASCRIPT
JAVASCRIPT
Program1
<html> Browser
<head></head>
output is :
<body>
<h1>Check the console for the “Check the
message!</h1> console for
<script> the
// This is our first JavaScript
message”
program
[Link]("Hello, World!"); Console
</script> output:
</body> "Hello,
</html>
World!"
Program 2:
Program3:
● ❌ Problem 1: If you call it after the page has finished loading, it will erase
everything on the page and replace it with the new content.
● ❌ Problem 2: It mixes content with JavaScript logic → not good for clean code.
● ❌ Problem 3: Cannot easily update specific parts of the page → it rewrites the
entire page instead.
<!DOCTYPE html>
<html>
<body>
<p id="output"></p>
<script>
var name = "Alice";
let age = 25;
const isStudent = true;
[Link]("output").innerText =
"Name: " + name + "\nAge: " + age + "\nIs Student: " + isStudent;
</script>
</body>
</html>
Benefits of innerText
[Link]("output").innerText = "Hello Alice";
● Keeps your HTML structure safe (it won’t insert <b> or <h1> as
HTML, it will show them as plain text).
Program5:
<!DOCTYPE html>
<html>
<body>
<div id="output"></div>
<script>
var name = "Kim";
let age = 25;
const isStudent = true;
[Link]("output").innerHTML =
"<b>Name:</b> " + name + "<br>" +
"<b>Age:</b> " + age + "<br>" +
"<b>Is Student:</b> " + isStudent;
</script>
</body>
</html>
Benefits of innerHTML
[Link]("output").innerHTML = "<b>Hello
Alice</b>";
Used when you want to design the output, not just show plain
text.
What is a Variable?
A variable is like a container in memory that stores a value
(number, text, boolean, etc.) so you can reuse and modify it
later.
1. Using var
[Link](city);
✔ Can be updated.
Example:
var x = 10;
if (true) {
[Link](x); // 20
✅ 2. Using let
let city = "Mumbai";
[Link](city);
✔ Can be updated.
Example:
let y = 10;
if (true) {
[Link](y); // 20
✅ 3. Using const
const country = "India";
[Link](country);
❌ Cannot be redeclared.
❌ Cannot be reassigned.
✔ Must be initialized when declared.
Example:
const pi = 3.1416;
✅ Allowed:
1.Must begin with a letter, _, or $
❌ Not Allowed:
let for = 10; ❌ Error
//
let return = 20; // ❌ Error
let var = 30; // ❌ Error
✅ (a) Number
Represents integers and floating-point numbers.
✅ (b) String
Represents text inside single ' ', double " ", or backticks `
`.
✅ (c) Boolean
Represents true / false values.
✅ (d) Undefined
A variable declared but not assigned any value is undefined.
let city;
[Link](city); // undefined
✅ (e) Null
Explicitly represents "no value".
✅ (a) Object
A collection of key-value pairs.
let person = {
name: "Vineet",
age: 25,
isStudent: true
};
[Link]([Link], [Link]);
✅ (b) Array
Special type of object, used to store ordered collections.
✅ (c) Function
Functions are first-class objects in JS (can be stored in
variables, passed around).
function greetUser(user) {
return "Hello " + user;
}
[Link](greetUser("Vineet"));
Conditional Statements
Conditional statements in JavaScript let you make decisions in
your code.
👉 They check a condition (true/false) and run different
blocks of code based on the result.
2.if...else statement
4.switch statement
5.Ternary operator (? :)
1. if statement
👉 Runs a block of code only if the condition is true.
2. if...else statement
👉 Runs one block if the condition is true, otherwise runs
another.
<script> Output: Values are not equal
if(1==10){ "use strict";
[Link]("Values are
equal")}
else{
[Link]("Values are not
equal")
}
</script>
OUTPUT:
<script> Grade B
//let percentage=prompt("enter the percentage");
let percentage=78;
-
if(percentage>=90){
[Link]("Grade A");}
else if (percentage>=70 ){
[Link]("Grade B");
}
else if (percentage>=50){
[Link]("Grade C");
}
else if (percentage>=35 ){
[Link]("Grade D");
}
else{
[Link]("Fail");
}
</script>
4. switch statement
👉 Useful when you have many possible values of a variable.
👉 Works like a menu of choices.
Example 1:
switch(day) {
case "Monday":
[Link]("Start of the
week!");
break;
case "Friday":
[Link]("Almost
weekend!");
break;
case "Sunday":
[Link]("Holiday");
break;
default:
[Link]("Normal
day.");
}
Example 2:
Loops in JavaScript
A loop allows you to repeat a block of code multiple times
until a certain condition is met.
This avoids writing the same code again and again.
1. for loop
👉 Used when you know how many times you want to repeat
something.
Syntax:
// code to repeat
<script> OUTPUT: 1
for (let i = 1; i <= 5; 2
i++) { 3
[Link](i); 4
} 5
</script>
2. while loop
👉 Used when you don’t know how many times beforehand, but
want to repeat until a condition becomes false.
let i = 1; OUTPUT:
while (i <= 5) { 1
[Link](i); 2
i++; 3
} 4
5
3. do...while loop
👉 Similar to while, but runs the code at least once, even if
the condition is false.
OUTPUT:
let i = 6; Number:6
Note: Due to do while loop
do {
program will run one time and
[Link]("Number:", i); then control will come out of
the loop.
i++;
4. for...in loop
👉 Used to loop through object properties
let person = {name: "Kip", OUTPUT:
age: 25, city: "Delhi"}; "name → Kip"
"age → 25"
for (let key in person) { "city → Delhi"
[Link](key + " → " +
person[key]);
}
5. for...of loop
👉 Used to loop through arrays, strings, or iterable objects.
OUTPUT:
let fruits = ["Apple", "Apple"
"Banana", "Mango"]; "Banana"
"Mango"
[Link](fruit);
Array in JavaScript
An Array in JavaScript is a special type of object used to
store multiple values in a single variable.
Arrays are ordered (values have indexes) and dynamic (size can
grow/shrink).
a)Creating Arrays
b) Array Indexing
c) Array Methods
Example:
—----------------------------------------------
Functions in JavaScript
a)Syntax of a Function
function functionName(parameters) {
// code to execute
return value; // (optional)
}
b)Why use Functions?
● Avoid repetition of code.
c) Types of Functions
OUTPUT:
function greet() { Hello everyone
[Link]("Hello everyone");
OUTPUT:
function add(a, b) { 30
return a + b;
[Link](result); // 30
OUTPUT: 20
let multiply = function(x, y) NOte: function(x,y) is an
{ anonymous function which is
assigned to a variable
return x * y;
};
[Link](multiply(5, 4));
OUTPUT:
let square = (n) => n * n; 36
[Link](square(6));
};
[Link](greet());
OUTPUT:
Example 2: This message appears after 2
seconds
setTimeout(function() {
[Link]("This message
appears after 2 seconds");
}, 2000);
OUTPUT:
function greet(name = "Guest") { Hello Amit
Hello Guest
[Link]("Hello " + name);
greet("Amit");
greet();
[Link](sum(1, 2, 3, 4));
function test() {
[Link](x);
test();
function outer() {
};
—-------------------------------------------------------------
OBJECTS in JavaScript
● An object is a collection of key-value pairs.
● Keys are called properties (or methods if the value is a
function).
● Values can be anything: numbers, strings, arrays,
functions, or even other objects.
● Think of an object like a real-world object:
Creating an Object
[Link](car);
[Link]([Link]);
[Link](student);
1. map()
Use when you want to change/transform every item in an
[Link] returns a new array with the transformed values.
Example1: OUTPUT:
let numbers = [1, 2, 3, 4]; [2, 4, 6, 8]
[Link](doubled);
Example2: OUTPUT:
let names = ["raj", "manali", "bhumika"]; [“RAJ”,”MANALI”
let upperNames = [Link](name => ,”BHUMIKA”]
[Link]());
[Link](upperNames);
Example3: OUTPUT:
let marks = [85, 42, 63, 30]; ["Pass",
let result = [Link](m => m >= 50 ? "Pass" "Fail", "Pass",
: "Fail"); "Fail"]
[Link](result);
2. filter()
Use when you want only some items from the [Link] returns a
new array with only items that pass a condition.
Example1: OUTPUT:
let numbers = [1, 2, 3, 4, 5, 6]; [2, 4, 6]
// Keep only even numbers
let evens = [Link](num => num % 2 === 0);
[Link](evens);
Example2: OUTPUT:
let names = ["Amit", "John", "Anita", "Ravi", "Arun"]; ["Amit",
let aNames = [Link](name => [Link]("A")); "Anita",
[Link](aNames); "Arun"]
Example3: OUTPUT:
let students = [ [{name:
{ name: "Yajat", marks: 85 }, "Yajat",
{ name: "Yuvraj", marks: 49 }, marks:
{ name: "Shreyas", marks: 72 }, 85},
{ name: "Himanshi", marks: 45 } {name:
]; "Shreyas
", marks:
let passed = [Link](student => [Link] 72}]
>= 50);
[Link](passed);
Example 4: OUTPUT:
let mixed = [0, "Hello", "", null, 42, undefined, ["Hello",
"JS", NaN]; 42, "JS"]
let truthy = [Link](Boolean);
[Link](truthy);
Example1: OUTPUT:
let numbers = [1, 2, 3, 4]; 10
// Add all numbers
let sum = [Link]((acc, num) => acc + num, 0);
[Link](sum);
Example2: OUTPUT:
let numbers = [15, 6, 28, 42, 10]; 42
let max = [Link]((acc, curr) => curr > acc ? curr : Note:
acc, numbers[0]); Numbers[0]
provide initial
[Link](max); value to acc
Curr start from
second element.
Example3: OUTPUT:
let cart = [ 750
{ product: "Book", price: 200 },
{ product: "Pen", price: 50 },
{ product: "Bag", price: 500 }
];
[Link](total);
Example 4: OUTPUT:
let str = "hello"; “olleh”
[Link](reversed);
(a)Common properties
Javascript
const el1 = [Link]('card'); // element or null
const el2 = [Link]('.box'); // element or null
const all = [Link]('.box'); // NodeList (static)
const live = [Link]('box');// HTMLCollection (live)
JAVASCRIPT
Program1
<html> Browser
<head></head>
output is :
<body>
<h1>Check the console for the “Check the
message!</h1> console for
<script> the
// This is our first JavaScript
message”
program
[Link]("Hello, World!"); Console
</script> output:
</body>
"Hello,
</html>
World!"
Program 2:
Program3:
● ❌ Problem 1: If you call it after the page has finished loading, it will erase
everything on the page and replace it with the new content.
● ❌ Problem 2: It mixes content with JavaScript logic → not good for clean code.
● ❌ Problem 3: Cannot easily update specific parts of the page → it rewrites the
entire page instead.
Program4:
<!DOCTYPE html>
<html>
<body>
<p id="output"></p>
<script>
var name = "Alice";
let age = 25;
const isStudent = true;
[Link]("output").innerText =
"Name: " + name + "\nAge: " + age + "\nIs Student: " + isStudent;
</script>
</body>
</html>
● Keeps your HTML structure safe (it won’t insert <b> or <h1> as
HTML, it will show them as plain text).
Program5:
<!DOCTYPE html>
<html>
<body>
<div id="output"></div>
<script>
var name = "Vineet";
let age = 25;
const isStudent = true;
[Link]("output").innerHTML =
"<b>Name:</b> " + name + "<br>" +
"<b>Age:</b> " + age + "<br>" +
"<b>Is Student:</b> " + isStudent;
</script>
</body>
</html>
Used when you want to design the output, not just show plain
text.
What is a Variable?
A variable is like a container in memory that stores a value
(number, text, boolean, etc.) so you can reuse and modify it
later.
1. Using var
[Link](city);
✔ Can be updated.
Example:
var x = 10;
if (true) {
[Link](x); // 20
✅ 2. Using let
let city = "Mumbai";
[Link](city);
✔ Can be updated.
Example:
let y = 10;
if (true) {
[Link](y); // 20
}
[Link](y); // 10 (outer one not affected)
✅ 3. Using const
const country = "India";
[Link](country);
❌ Cannot be redeclared.
❌ Cannot be reassigned.
✔ Must be initialized when declared.
Example:
const pi = 3.1416;
✅ Allowed:
1.Must begin with a letter, _, or $
❌ Not Allowed:
let for = 10; ❌ Error
//
let return = 20; // ❌ Error
let var = 30; // ❌ Error
✅ (a) Number
Represents integers and floating-point numbers.
✅ (c) Boolean
Represents true / false values.
✅ (d) Undefined
A variable declared but not assigned any value is undefined.
let city;
[Link](city); // undefined
✅ (e) Null
Explicitly represents "no value".
✅ (a) Object
A collection of key-value pairs.
let person = {
name: "Vineet",
age: 25,
isStudent: true
};
[Link]([Link], [Link]);
✅ (b) Array
Special type of object, used to store ordered collections.
✅ (c) Function
Functions are first-class objects in JS (can be stored in
variables, passed around).
function greetUser(user) {
return "Hello " + user;
}
[Link](greetUser("Vineet"));
Conditional Statements
2.if...else statement
4.switch statement
5.Ternary operator (? :)
1. if statement
👉 Runs a block of code only if the condition is true.
2. if...else statement
👉 Runs one block if the condition is true, otherwise runs
another.
OUTPUT:
<script> Grade B
//let percentage=prompt("enter the percentage");
let percentage=78;
-
if(percentage>=90){
[Link]("Grade A");}
else if (percentage>=70 ){
[Link]("Grade B");
}
else if (percentage>=50){
[Link]("Grade C");
}
else if (percentage>=35 ){
[Link]("Grade D");
}
else{
[Link]("Fail");
}
</script>
4. switch statement
👉 Useful when you have many possible values of a variable.
👉 Works like a menu of choices.
Example 1:
switch(day) {
case "Monday":
[Link]("Start of the
week!");
break;
case "Friday":
[Link]("Almost
weekend!");
break;
case "Sunday":
[Link]("Holiday");
break;
default:
[Link]("Normal
day.");
}
Example 2:
5. Ternary Operator (? :)
👉 Short form of if...else, used for quick decisions.
Loops in JavaScript
A loop allows you to repeat a block of code multiple times
until a certain condition is met.
This avoids writing the same code again and again.
1. for loop
👉 Used when you know how many times you want to repeat
something.
Syntax:
// code to repeat
<script> OUTPUT: 1
for (let i = 1; i <= 5; 2
i++) { 3
[Link](i); 4
} 5
</script>
2. while loop
👉 Used when you don’t know how many times beforehand, but
want to repeat until a condition becomes false.
let i = 1; OUTPUT:
while (i <= 5) { 1
[Link](i); 2
i++; 3
} 4
5
3. do...while loop
👉 Similar to while, but runs the code at least once, even if
the condition is false.
OUTPUT:
let i = 6; Number:6
Note: Due to do while loop
do {
program will run one time and
[Link]("Number:", i); then control will come out of
the loop.
i++;
4. for...in loop
👉 Used to loop through object properties
5. for...of loop
👉 Used to loop through arrays, strings, or iterable objects.
OUTPUT:
let fruits = ["Apple", "Apple"
"Banana", "Mango"]; "Banana"
"Mango"
[Link](fruit);
Array in JavaScript
An Array in JavaScript is a special type of object used to
store multiple values in a single variable.
Arrays are ordered (values have indexes) and dynamic (size can
grow/shrink).
a)Creating Arrays
b) Array Indexing
● Index starts from 0.
c) Array Methods
Example:
—----------------------------------------------
Functions in JavaScript
a)Syntax of a Function
function functionName(parameters) {
// code to execute
return value; // (optional)
}
c) Types of Functions
[Link]("Hello everyone");
OUTPUT:
function add(a, b) { 30
return a + b;
[Link](result); // 30
OUTPUT: 20
let multiply = function(x, y) NOte: function(x,y) is an
{ anonymous function which is
assigned to a variable
return x * y;
};
[Link](multiply(5, 4));
(iv) Arrow Function (Modern ES6)
OUTPUT:
let square = (n) => n * n; 36
[Link](square(6));
Example 1:
};
[Link](greet());
OUTPUT:
Example 2: This message appears after 2
seconds
setTimeout(function() {
[Link]("This message
appears after 2 seconds");
}, 2000);
OUTPUT:
function greet(name = "Guest") { Hello Amit
Hello Guest
[Link]("Hello " + name);
greet("Amit");
greet();
function sum(...numbers) {
[Link](sum(1, 2, 3, 4));
function test() {
[Link](x);
test();
function outer() {
};
}
let func = outer();
—-------------------------------------------------------------
OBJECTS in JavaScript
● An object is a collection of key-value pairs.
● Keys are called properties (or methods if the value is a
function).
● Values can be anything: numbers, strings, arrays,
functions, or even other objects.
● Think of an object like a real-world object:
Creating an Object
[Link](car);
[Link]([Link]);
[Link](student);
1. map()
Use when you want to change/transform every item in an
[Link] returns a new array with the transformed values.
[Link](doubled);
2. filter()
Use when you want only some items from the [Link] returns a
new array with only items that pass a condition.
Example1: OUTPUT:
let numbers = [1, 2, 3, 4, 5, 6]; [2, 4, 6]
[Link](evens);
Example2: OUTPUT:
let names = ["Amit", "John", "Anita", "Ravi", "Arun"]; ["Amit",
let aNames = [Link](name => "Anita",
[Link]("A")); "Arun"]
[Link](aNames);
Example3: OUTPUT:
let students = [ [{name:
{ name: "Asif", marks: 85 }, "Asif",
{ name: "Prerna", marks: 40 }, marks:
{ name: "Riya", marks: 72 }, 85},
{ name: "Kiran", marks: 35 } {name:
]; "Riya",
marks:72}
let passed = [Link](student => [Link] ]
>= 50);
[Link](passed);
Example4: OUTPUT:
let nums = [10, 20, 30, 40, 50]; 30
let avg = [Link]((a, b) => a + b, 0) / [40,50]
[Link];
[Link](avg);
[Link](aboveAvg);
Example5: OUTPUT:
let mixed = [0, "Hello", "", null, 42, undefined, ["Hello",
"JS", NaN]; 42, "JS"]
let truthy = [Link](Boolean);
[Link](truthy);
Example6: OUTPUT:
let numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10]; [2, 3, 5,
7]
function isPrime(num) {
if (num < 2) return false;
for (let i = 2; i <= [Link](num); i++) {
if (num % i === 0) return false;
}
return true;
}
Example7: OUTPUT:
let fruits = ["Apple", "Banana", "Mango", "Orange", ["Banana"
"Pineapple"]; ,
"Mango",
let search = "an"; "Orange",
let result = [Link](fruit => "Pineappl
[Link]().includes([Link]()) e"]
);
[Link](result);
3. reduce() Use when you want to reduce the whole array
to a single [Link] takes an accumulator and each array item,
and combines them step by step
Example1: OUTPUT:
let numbers = [1, 2, 3, 4]; 10
[Link](sum);
Example2: OUTPUT:
let numbers = [15, 6, 28, 42, 10]; 42
let max = [Link]((acc, curr) => curr > acc ? curr : acc,
numbers[0]);
[Link](max);
Example3: OUTPUT:
let fruits = ["apple", "banana", "apple", "orange", "banana", "apple"]; { apple: 3, banana:
2, orange: 1 }
let count = [Link]((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {});
[Link](count);
Example4: OUTPUT:
let cart = [ 750
{ product: "Book", price: 200 },
{ product: "Pen", price: 50 },
{ product: "Bag", price: 500 }
];
[Link](total);
Example5: OUTPUT:
let str = "hello"; “olleh”
[Link](reversed);
i) Accessing elements:
a)[Link](id)
Example:
<p id="demo">Hello</p>
<script>
let element = [Link]("demo");
[Link]([Link]);
</script>
Console output:
Hello
b)[Link](className)
● Selects all elements with a class name.
Example:
<!DOCTYPE html>
<html>
<body>
<p class="note">First</p>
<p class="note">Second</p>
<script>
let items = [Link]("note");
items[0].[Link] = "red"; // change first one
items[1].[Link] = "green"; // change second one
</script>
</body>
</html>
c)[Link](tagName)
● Selects all elements of a given tag (like <p>, <div>,
<li>).
● Returns an HTMLCollection
Example:
<!DOCTYPE html>
<html>
<body>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<script>
let paras = [Link]("p");
paras[0].[Link] = "bold";
paras[1].[Link] = "blue";
</script>
</body>
</html>
d)[Link](name)
● Selects all elements with a given name attribute.
● Returns a NodeList.
Example:
<!DOCTYPE html>
<html>
<body>
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<script>
let genders = [Link]("gender");
[Link]([Link]); // 2
</script>
</body>
</html>
Example1:
<p id="demo">Hello</p>
<script>
let element = [Link]("demo");
[Link] = "Welcome!"; // changes text
</script>
Webpage output:
Welcome!
Example2:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Hello World!</p>
<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
[Link]("demo").innerText =
"Text has been changed!";
}
</script>
</body>
</html>
Example3:
<!DOCTYPE html>
<html>
<body>
<p id="demo">
Hello
<span style="display:none">Hidden</span>
World
</p>
<script>
let text =
[Link]("demo").innerText;
[Link](text); // "Hello World" (Hidden part
ignored)
</script>
</body>
</html>
What is .innerHTML?
● .innerHTML is a DOM property that allows you to get or set
the HTML content inside an element.
Example1:
<p id="demo">Hello</p>
<script>
[Link]("demo").innerHTML = "<b>Bold text</b>";
</script>
Webpage OUTPUT:
Bold text
Example2:Insert new html tag
<!DOCTYPE html>
<html>
<body>
<div id="container"></div>
<script>
[Link]("container").innerHTML =
"<h2>Welcome!</h2><p>This was added using
JavaScript.</p>";
</script>
</body>
</html>
Webpage OUTPUT:
Welcome!
This was added using JavaScript.
<script>
[Link]("list").innerHTML =
"<li>Apple</li><li>Banana</li><li>Orange</li>";
</script>
</body>
</html>
Webpage OUTPUT:
● Apple
● Banana
● Orange
iv) Changing Style
<script>
let p = [Link]("demo");
[Link] = "blue";
[Link] = "20px";
</script>
Webpage Output:
Change my color // with fontsize 20px
<div id="container"></div>
<script>
let div = [Link]("container");
let newP = [Link]("p"); // make <p>
[Link] = "I am new!";
[Link](newP); // put inside div
</script>
Webpage Output:
I’m new
<script>
[Link]("btn").onclick =
function() {
[Link]("msg").innerText =
"Button clicked!";
};
</script>
Webpage Output:
After clicking
Button clicked!
a)
Color Changer Example
<button id="redBtn">Red</button>
<button id="blueBtn">Blue</button>
<p id="box">Change my color!</p>
<script>
let box = [Link]("box");
[Link]("redBtn").onclick = () => {
[Link] = "red";
};
[Link]("blueBtn").onclick = () => {
[Link] = "blue";
};
</script>
Webpage OUTPUT: Output After clicking red Output After clicking blue