0% found this document useful (0 votes)
11 views64 pages

JAVASCRIPT

The document provides an overview of JavaScript, covering its role as a client-side programming language for web interactivity, various methods of writing JavaScript code, and the importance of variables, data types, conditional statements, loops, and functions. It emphasizes best practices, such as avoiding the use of document.write() and understanding the differences between innerText and innerHTML for DOM manipulation. Additionally, it explains variable declaration using var, let, and const, as well as the structure and purpose of functions in JavaScript.
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)
11 views64 pages

JAVASCRIPT

The document provides an overview of JavaScript, covering its role as a client-side programming language for web interactivity, various methods of writing JavaScript code, and the importance of variables, data types, conditional statements, loops, and functions. It emphasizes best practices, such as avoiding the use of document.write() and understanding the differences between innerText and innerHTML for DOM manipulation. Additionally, it explains variable declaration using var, let, and const, as well as the structure and purpose of functions in JavaScript.
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

●​ A programming language that makes web pages


interactive.
●​ Runs inside the browser (client-side).
●​ Can change HTML, CSS, and handle events like
clicks.

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:

You can write JavaScript in two main ways:

Inside <script> tags in HTML

<!DOCTYPE html> Note:


<html> alert() → shows a
<head> popup with message
<title>JS Example</title> “This is a popup from
</head> JS!”​
<body>
<h1>Hello JavaScript</h1> [Link]()
→”Hello from
<script> JavaScript!”
[Link]("Hello from JavaScript!");
alert("This is a popup from JS!"); Browser OUTPUT:
</script> “Hello JavaScript!”
</body>
</html>

Program3:

<!DOCTYPE html> OUTPUT in browser:


<html> Name: Alice
<body> Age: 25
<script> Is Student: true
var name = "Alice"; // String
let age = 25; // Number Note:
const isStudent = true; // Boolean This [Link]() is not
recommended for large project
[Link]("Name: " + name + "<br>");
[Link]("Age: " + age + "<br>");
[Link]("Is Student: " + isStudent);
</script>
</body>
</html>

Why not use [Link]() (Problems)


●​ ✅ [Link]() was commonly used in very old HTML/JavaScript
code.​

●​ ❌ 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.​

●​ ❌ Problem 4: Not supported in modern frameworks (React, Angular, Vue, etc.) —


they expect DOM manipulation, not overwriting.
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>

Output: shows inside the <p> tag

Benefits of innerText
[Link]("output").innerText = "Hello Alice";

●​ Replaces only the text of the element.​

●​ Keeps your HTML structure safe (it won’t insert <b> or <h1> as
HTML, it will show them as plain text).​

●​ Automatically respects CSS (for example, if CSS uses display:none,


hidden text won’t be shown).​

●​ Good for showing user-generated content safely → avoids XSS


(cross-site scripting) risks.

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>

This one allows HTML formatting (bold, line breaks, etc.).

Benefits of innerHTML
[Link]("output").innerHTML = "<b>Hello
Alice</b>";

Can insert HTML formatting (bold, italic, headings, lists,


images, etc.).

Very flexible — lets you build rich content dynamically.

Used when you want to design the output, not just show plain
text.

⚠️ Caution: If you insert user input with innerHTML, it can


allow hackers to inject harmful scripts (XSS attack).
Example: if someone enters <script>alert('Hacked')</script> —
it will actually run.
👉 Use innerText if you only need 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

var city = "Delhi";

[Link](city);

✔ Can be redeclared in the same scope.

✔ Can be updated.

❌ Function-scoped (not block-scoped → can cause bugs).

Example:

var x = 10;

if (true) {

var x = 20; // same variable, value overwritten

[Link](x); // 20

👉 Even though we changed x inside if, it overwrote the outer


one.

✅ 2. Using let
let city = "Mumbai";

[Link](city);
✔ Can be updated.

❌ Cannot be redeclared in the same scope.


✔ Block-scoped → stays inside { } only.

Example:

let y = 10;

if (true) {

let y = 20; // new variable inside block

[Link](y); // 20

[Link](y); // 10 (outer one not affected)

👉 Safer than var.

✅ 3. Using const
const country = "India";

[Link](country);

❌ Cannot be redeclared.
❌ Cannot be reassigned.
✔ Must be initialized when declared.
Example:

const pi = 3.1416;

pi = 3.14; // ❌ Error (can't change)

Variable Naming Rules in JavaScript

When you declare variables in JS, rules are:

✅ Allowed:
1.​Must begin with a letter, _, or $

2.​Can contain letters, digits, _, $ (but not spaces or


special symbols like #, @)

3.​Case-sensitive (Name ≠ name)

4.​Cannot be a reserved keyword (if, for, return, etc.)

❌ Not Allowed:
let for = 10; ❌ Error
//
let return = 20; // ❌ Error
let var = 30; // ❌ Error

JavaScript Data Types

JavaScript has two main categories of data types:

Primitive Data Types (simple, immutable values)

Non-Primitive (Reference) Data Types (objects, arrays,


functions, etc.)

1️⃣ Primitive Data Types


These are stored by value (directly in memory) and are
immutable.

✅ (a) Number
Represents integers and floating-point numbers.

JavaScript does not distinguish between int and float.

Special values: Infinity, -Infinity, NaN (Not a Number).

let age = 25; // integer


let pi = 3.14159; // floating-point
let big = 1.5e6; // exponential
let result = "hello" * 2; // NaN
[Link](age, pi, big, result);

✅ (b) String
Represents text inside single ' ', double " ", or backticks `
`.

Strings are immutable.

Backticks allow template literals with interpolation (${ }).

let name = "Alice";


let greet = 'Hello World';
let intro = `My name is ${name}`;
[Link](name, greet, intro);

✅ (c) Boolean
Represents true / false values.

Often used in conditions.


let isStudent = true;
let isAdult = false;
[Link](isStudent, isAdult, 10 > 5); // true, false, true

✅ (d) Undefined
A variable declared but not assigned any value is undefined.

let city;
[Link](city); // undefined

✅ (e) Null
Explicitly represents "no value".

Different from undefined (which means "not assigned").

let job = null;


[Link](job); // null

✅ (f) Symbol (ES6)


Used to create unique identifiers.

Even if two symbols have the same description, they are


unique.

let sym1 = Symbol("id");


let sym2 = Symbol("id");
[Link](sym1 === sym2); // false

✅ (g) BigInt (ES2020)


For numbers larger than Number.MAX_SAFE_INTEGER (2^53 - 1).

Add n at the end to create a BigInt.

let bigNumber = 1234567890123456789012345678901234567890n;


[Link](bigNumber);

2️⃣ Non-Primitive (Reference) Data Types

Stored by reference (not 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.

let numbers = [10, 20, 30];


[Link](numbers[0], [Link]); // 10, 3

✅ (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.

✅ Types of Conditional Statements in JavaScript


1.​if statement

2.​if...else statement

3.​if...else if...else chain

4.​switch statement

5.​Ternary operator (? :)

1. if statement
👉 Runs a block of code only if the condition is true.

<script> Output: Values are equal


if(10==10){
[Link]("Values are
equal")}
</script>

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>

3. if...else if...else chain


👉 Checks multiple conditions one by one.

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:

let day = "Monday"; Output: Start of the week!

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:

<script> OUTPUT: Jumping High


let action="jump";
switch(action) {
case "run": [Link]("Running
fast");break;
case "defend":
[Link]("Defending");break;
case "attack":
[Link]("attacking");break;
case "jump": [Link]("jumping
high");break;
default:[Link]("idle state");
}
</script>
5. Ternary Operator (? :)
👉 Short form of if...else, used for quick decisions.

<script> OUTPUT: Odd


let number = 7; // try changing this number Number
let result = (number % 2 === 0) ? "Even Number "
: "Odd Number ";
[Link](result);
</script>

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:

for (initialization; condition; update) {

// 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++;

} while (i <= 5);

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"

for (let fruit of fruits) {

[Link](fruit);

Array in JavaScript
An Array in JavaScript is a special type of object used to
store multiple values in a single variable.

It can hold numbers, strings, booleans, objects, or even other


arrays.

Arrays are ordered (values have indexes) and dynamic (size can
grow/shrink).
a)Creating Arrays

Using Square Brackets

let students = ["Samrat", "Musab", "Manali"];


[Link](students);

Using new Array()

let numbers = new Array(10, 20, 30);


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

b) Array Indexing

●​ Index starts from 0.​

●​ Last element index = [Link] - 1

let colors = ["Red", "Green", "Blue"]; Output:


[Link](colors[0]); “Red”
[Link](colors[2]); “Blue”
[Link](colors[[Link] - 1]); “Blue”

c) Array Methods

Method Description Example

push() Add element at end [Link]("Orange")

pop() Remove last element [Link]()

unshift() Add at beginning [Link]("Grapes")


shift() Remove first element [Link]()

length Get number of elements [Link]

Example:

let fruits = ["Apple", "Banana"]; OUTPUT:


[Link]("Orange"); ["Apple", "Banana", "Orange"]
[Link](fruits); ["Apple", "Banana"]
[Link](); ["Mango", "Apple", "Banana"]
[Link](fruits); ["Apple", "Banana"]
2
[Link]("Mango");
[Link](fruits);
[Link]();
[Link](fruits);
[Link]([Link]);

—----------------------------------------------

Functions in JavaScript

●​ A function is a reusable block of code that performs a


specific task.
●​ Functions help avoid repetition, make code modular,
readable, and reusable.
●​ Makes debugging easier.

a)​Syntax of a Function

function functionName(parameters) {
// code to execute
return value; // (optional)
}
b)​Why use Functions?
●​ Avoid repetition of code.​

●​ Divide big programs into smaller parts.​

●​ Reuse logic whenever needed.​

●​ Easier to debug and maintain.

c) Types of Functions

(i) Function Declaration (Named Function)

OUTPUT:
function greet() { Hello everyone

[Link]("Hello everyone");

greet(); // Calling the function

(ii) Function with Parameters and Return

OUTPUT:
function add(a, b) { 30

return a + b;

let result = add(10, 20);

[Link](result); // 30

(iii) Function Expression


●​ A function stored inside a variable.

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)

●​ Shorter syntax for functions.

OUTPUT:
let square = (n) => n * n; 36
[Link](square(6));

(v) Anonymous Function

●​ Function without a name, often used with events.


Example 1:

let greet = function() {


OUTPUT:
return "Hello World!"; Hello World!

};

[Link](greet());

OUTPUT:
Example 2: This message appears after 2
seconds
setTimeout(function() {

[Link]("This message
appears after 2 seconds");

}, 2000);

(vi) Default Parameters

OUTPUT:
function greet(name = "Guest") { Hello Amit
Hello Guest
[Link]("Hello " + name);

greet("Amit");

greet();

(vii) Rest Parameters

●​ Accepts multiple arguments as an array.


function sum(...numbers) {

return [Link]((total, num) =>


total + num, 0);

[Link](sum(1, 2, 3, 4));

(d). Function Scope

●​ Variables declared inside a function are local to it.​

●​ They cannot be accessed outside the function.​

function test() {

let x = 10; // local variable

[Link](x);

test();

// [Link](x); ❌ Error (x not defined outside function)

(e). Functions Returning Functions


Yes, functions can return another function.

function outer() {

return function inner() {

[Link]("Inner function executed!");

};

let func = outer();

func(); // Inner function executed!

—-------------------------------------------------------------

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:

Example: A Car has properties like color, brand, speed.

Creating an Object

(a) Using Object Literal (most common)

let car = { OUTPUT:


brand: "Toyota", {brand: "Toyota", color:
color: "Red", "Red", speed: 120}
speed: 120 Toyota
};

[Link](car);
[Link]([Link]);

(b) Using new Object()


let student = new Object(); OUTPUT:
[Link] = "Aman"; {name: "Aman", age: 18}
[Link] = 18;

[Link](student);

(c)Accessing Object Properties

let person = { name: "Ravi", age: 20 }; OUTPUT:


Ravi
[Link]([Link]); 20
[Link](person["age"]);

(d)Adding and Removing Properties

let book = { title: "Math", pages: 200 }; OUTPUT:


{
[Link] = "Ram"; "title": "Math",
[Link](book); "pages": 200,
"author": "Ram"
delete [Link]; }
[Link](book); // {title: "Math", {
author: "Ram"} "title": "Math",
"author": "Ram"
}

(e) Objects with Functions (Methods)

let calculator = { OUTPUT:


add: function(a, b) { 8
return a + b; 24
},
multiply(a, b) { Note:
add: function(a,b)
Is one way to
write function.
[Link]([Link](3, 5)); multiply(a,b) is
[Link]([Link](4, 6)); the modern method
of writing

JavaScript – map, filter, and reduce


These three are array methods. They help in transforming,
filtering, and reducing data easily.

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]

let doubled = [Link](num => num * 2);

[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);

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
// 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 }
];

let total = [Link]((acc, item) => acc + [Link], 0);

[Link](total);

Example 4: OUTPUT:
let str = "hello"; “olleh”

let reversed = [Link]("").reduce((acc, char) => char + acc, "");

[Link](reversed);

DOM(Document Object Model)


The DOM is the bridge between your HTML and
JavaScript: it represents the HTML document as a tree
of nodes that JS can read and change. The document
object is the root entry point you use to access and
manipulate that tree.
●​ The browser parses HTML and builds a tree of
nodes (elements, text nodes, comments, etc.).
●​ Each element becomes a Node (an object) you can
inspect and change with JS.
●​ document is the global object that represents the
whole page (the document node).
1.​ The document object: useful properties &
methods

(a)Common properties

[Link] // <html> element


[Link] // <head>
[Link] // <body>
[Link] // page title
[Link] // current URL
[Link] // HTMLCollection of forms

(b) common methods

[Link](id) // returns single element


[Link](cls) // live HTMLCollection
[Link](tag) // live HTMLCollection
[Link](selector) // first match (CSS selector)
[Link](selector) // NodeList (static)
[Link](tagName) // create a new element
[Link](text) // create a text node
[Link]() // temporary container
//for fast DOM updates

2.​ Selecting elements: examples + important


difference
HTML
<div id="card" class="box">Hello</div>

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

●​ A programming language that makes web pages


interactive.
●​ Runs inside the browser (client-side).
●​ Can change HTML, CSS, and handle events like
clicks.

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:

You can write JavaScript in two main ways:

Inside <script> tags in HTML

<!DOCTYPE html> Note:


<html> alert() → shows a
<head> popup with message
<title>JS Example</title> “This is a popup from
</head> JS!”​
<body>
<h1>Hello JavaScript</h1> [Link]()
→”Hello from
<script> JavaScript!”
[Link]("Hello from JavaScript!");
alert("This is a popup from JS!"); Browser OUTPUT:
</script> “Hello JavaScript!”
</body>
</html>

Program3:

<!DOCTYPE html> OUTPUT in browser:


<html> Name: Alice
<body> Age: 25
<script> Is Student: true
var name = "Alice"; // String
let age = 25; // Number Note:
const isStudent = true; // Boolean This [Link]() is not
recommended for large project
[Link]("Name: " + name + "<br>");
[Link]("Age: " + age + "<br>");
[Link]("Is Student: " + isStudent);
</script>
</body>
</html>

Why not use [Link]() (Problems)


●​ ✅ [Link]() was commonly used in very old HTML/JavaScript
code.​

●​ ❌ 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.​

●​ ❌ Problem 4: Not supported in modern frameworks (React, Angular, Vue, etc.) —


they expect DOM manipulation, not overwriting.

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>

Output: shows inside the <p> tag


Benefits of innerText
[Link]("output").innerText = "Hello Alice";

●​ Replaces only the text of the element.​

●​ Keeps your HTML structure safe (it won’t insert <b> or <h1> as
HTML, it will show them as plain text).​

●​ Automatically respects CSS (for example, if CSS uses display:none,


hidden text won’t be shown).​

●​ Good for showing user-generated content safely → avoids XSS


(cross-site scripting) risks.

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>

This one allows HTML formatting (bold, line breaks, etc.).


Benefits of innerHTML
[Link]("output").innerHTML = "<b>Hello
Alice</b>";

Can insert HTML formatting (bold, italic, headings, lists,


images, etc.).

Very flexible — lets you build rich content dynamically.

Used when you want to design the output, not just show plain
text.

⚠️ Caution: If you insert user input with innerHTML, it can


allow hackers to inject harmful scripts (XSS attack).
Example: if someone enters <script>alert('Hacked')</script> —
it will actually run.
👉 Use innerText if you only need 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

var city = "Delhi";

[Link](city);

✔ Can be redeclared in the same scope.

✔ Can be updated.

❌ Function-scoped (not block-scoped → can cause bugs).

Example:
var x = 10;

if (true) {

var x = 20; // same variable, value overwritten

[Link](x); // 20

👉 Even though we changed x inside if, it overwrote the outer


one.

✅ 2. Using let
let city = "Mumbai";

[Link](city);

✔ Can be updated.

❌ Cannot be redeclared in the same scope.


✔ Block-scoped → stays inside { } only.

Example:

let y = 10;

if (true) {

let y = 20; // new variable inside block

[Link](y); // 20

}
[Link](y); // 10 (outer one not affected)

👉 Safer than var.

✅ 3. Using const
const country = "India";

[Link](country);

❌ Cannot be redeclared.
❌ Cannot be reassigned.
✔ Must be initialized when declared.

Example:

const pi = 3.1416;

pi = 3.14; // ❌ Error (can't change)

Variable Naming Rules in JavaScript

When you declare variables in JS, rules are:

✅ Allowed:
1.​Must begin with a letter, _, or $

2.​Can contain letters, digits, _, $ (but not spaces or


special symbols like #, @)
3.​Case-sensitive (Name ≠ name)

4.​Cannot be a reserved keyword (if, for, return, etc.)

❌ Not Allowed:
let for = 10; ❌ Error
//
let return = 20; // ❌ Error
let var = 30; // ❌ Error

JavaScript Data Types

JavaScript has two main categories of data types:

Primitive Data Types (simple, immutable values)

Non-Primitive (Reference) Data Types (objects, arrays,


functions, etc.)

1️⃣ Primitive Data Types

These are stored by value (directly in memory) and are


immutable.

✅ (a) Number
Represents integers and floating-point numbers.

JavaScript does not distinguish between int and float.

Special values: Infinity, -Infinity, NaN (Not a Number).

let age = 25; // integer


let pi = 3.14159; // floating-point
let big = 1.5e6; // exponential
let result = "hello" * 2; // NaN
[Link](age, pi, big, result);
✅ (b) String
Represents text inside single ' ', double " ", or backticks `
`.

Strings are immutable.

Backticks allow template literals with interpolation (${ }).

let name = "Alice";


let greet = 'Hello World';
let intro = `My name is ${name}`;
[Link](name, greet, intro);

✅ (c) Boolean
Represents true / false values.

Often used in conditions.

let isStudent = true;


let isAdult = false;
[Link](isStudent, isAdult, 10 > 5); // true, false, true

✅ (d) Undefined
A variable declared but not assigned any value is undefined.

let city;
[Link](city); // undefined

✅ (e) Null
Explicitly represents "no value".

Different from undefined (which means "not assigned").


let job = null;
[Link](job); // null

✅ (f) Symbol (ES6)


Used to create unique identifiers.

Even if two symbols have the same description, they are


unique.

let sym1 = Symbol("id");


let sym2 = Symbol("id");
[Link](sym1 === sym2); // false

✅ (g) BigInt (ES2020)


For numbers larger than Number.MAX_SAFE_INTEGER (2^53 - 1).

Add n at the end to create a BigInt.

let bigNumber = 1234567890123456789012345678901234567890n;


[Link](bigNumber);

2️⃣ Non-Primitive (Reference) Data Types

Stored by reference (not 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.

let numbers = [10, 20, 30];


[Link](numbers[0], [Link]); // 10, 3

✅ (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.

✅ Types of Conditional Statements in JavaScript


1.​if statement

2.​if...else statement

3.​if...else if...else chain

4.​switch statement

5.​Ternary operator (? :)

1. if statement
👉 Runs a block of code only if the condition is true.

<script> Output: Values are equal


if(10==10){
[Link]("Values are
equal")}
</script>

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>

3. if...else if...else chain


👉 Checks multiple conditions one by one.

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:

let day = "Monday"; Output: Start of the week!

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:

<script> OUTPUT: Jumping High


let action="jump";
switch(action) {
case "run": [Link]("Running
fast");break;
case "defend":
[Link]("Defending");break;
case "attack":
[Link]("attacking");break;
case "jump": [Link]("jumping
high");break;
default:[Link]("idle state");
}
</script>

5. Ternary Operator (? :)
👉 Short form of if...else, used for quick decisions.

<script> OUTPUT: Odd


let number = 7; // try changing this number Number
let result = (number % 2 === 0) ? "Even Number "
: "Odd Number ";
[Link](result);
</script>

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:

for (initialization; condition; update) {

// 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++;

} while (i <= 5);

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"

for (let fruit of fruits) {

[Link](fruit);

Array in JavaScript
An Array in JavaScript is a special type of object used to
store multiple values in a single variable.

It can hold numbers, strings, booleans, objects, or even other


arrays.

Arrays are ordered (values have indexes) and dynamic (size can
grow/shrink).

a)Creating Arrays

Using Square Brackets

let students = ["Samrat", "Musab", "Manali"];


[Link](students);

Using new Array()

let numbers = new Array(10, 20, 30);


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

b) Array Indexing
●​ Index starts from 0.​

●​ Last element index = [Link] - 1

let colors = ["Red", "Green", "Blue"]; Output:


[Link](colors[0]); “Red”
[Link](colors[2]); “Blue”
[Link](colors[[Link] - 1]); “Blue”

c) Array Methods

Method Description Example

push() Add element at end [Link]("Orange")

pop() Remove last element [Link]()

unshift() Add at beginning [Link]("Grapes")

shift() Remove first element [Link]()

length Get number of elements [Link]

Example:

let fruits = ["Apple", "Banana"]; OUTPUT:


[Link]("Orange"); ["Apple", "Banana", "Orange"]
[Link](fruits); ["Apple", "Banana"]
["Mango", "Apple", "Banana"]
[Link](); ["Apple", "Banana"]
[Link](fruits); 2
[Link]("Mango");
[Link](fruits);
[Link]();
[Link](fruits);
[Link]([Link]);

—----------------------------------------------

Functions in JavaScript

●​ A function is a reusable block of code that performs a


specific task.
●​ Functions help avoid repetition, make code modular,
readable, and reusable.
●​ Makes debugging easier.

a)​Syntax of a Function

function functionName(parameters) {
// code to execute
return value; // (optional)
}

b)​Why use Functions?


●​ Avoid repetition of code.​

●​ Divide big programs into smaller parts.​

●​ Reuse logic whenever needed.​

●​ Easier to debug and maintain.

c) Types of Functions

(i) Function Declaration (Named Function)


OUTPUT:
function greet() { Hello everyone

[Link]("Hello everyone");

greet(); // Calling the function

(ii) Function with Parameters and Return

OUTPUT:
function add(a, b) { 30

return a + b;

let result = add(10, 20);

[Link](result); // 30

(iii) Function Expression

●​ A function stored inside a variable.

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)

●​ Shorter syntax for functions.

OUTPUT:
let square = (n) => n * n; 36
[Link](square(6));

(v) Anonymous Function

●​ Function without a name, often used with events.

Example 1:

let greet = function() {


OUTPUT:
return "Hello World!"; Hello World!

};

[Link](greet());

OUTPUT:
Example 2: This message appears after 2
seconds
setTimeout(function() {
[Link]("This message
appears after 2 seconds");

}, 2000);

(vi) Default Parameters

OUTPUT:
function greet(name = "Guest") { Hello Amit
Hello Guest
[Link]("Hello " + name);

greet("Amit");

greet();

(vii) Rest Parameters

●​ Accepts multiple arguments as an array.

function sum(...numbers) {

return [Link]((total, num) =>


total + num, 0);

[Link](sum(1, 2, 3, 4));

(d). Function Scope

●​ Variables declared inside a function are local to it.​

●​ They cannot be accessed outside the function.​

function test() {

let x = 10; // local variable

[Link](x);

test();

// [Link](x); ❌ Error (x not defined outside function)

(e). Functions Returning Functions

Yes, functions can return another function.

function outer() {

return function inner() {

[Link]("Inner function executed!");

};

}
let func = outer();

func(); // Inner function executed!

—-------------------------------------------------------------

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:

Example: A Car has properties like color, brand, speed.

Creating an Object

(a) Using Object Literal (most common)

let car = { OUTPUT:


brand: "Toyota", {brand: "Toyota", color:
color: "Red", "Red", speed: 120}
speed: 120 Toyota
};

[Link](car);
[Link]([Link]);

(b) Using new Object()

let student = new Object(); OUTPUT:


[Link] = "Aman"; {name: "Aman", age: 18}
[Link] = 18;

[Link](student);

(c)Accessing Object Properties


let person = { name: "Ravi", age: 20 }; OUTPUT:
Ravi
[Link]([Link]); 20
[Link](person["age"]);

(d)Adding and Removing Properties

let book = { title: "Math", pages: 200 }; OUTPUT:


{
[Link] = "Ram"; "title": "Math",
[Link](book); "pages": 200,
"author": "Ram"
delete [Link]; }
[Link](book); // {title: "Math", {
author: "Ram"} "title": "Math",
"author": "Ram"
}

(e) Objects with Functions (Methods)

let calculator = { OUTPUT:


add: function(a, b) { 8
return a + b; 24
},
multiply(a, b) { Note:
return a * b; add: function(a,b)
} Is one way to
}; write function.
multiply(a,b) is
[Link]([Link](3, 5)); the modern method
[Link]([Link](4, 6)); of writing

JavaScript – map, filter, and reduce


These three are array methods. They help in transforming,
filtering, and reducing data easily.

1. map()
Use when you want to change/transform every item in an
[Link] returns a new array with the transformed values.

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


[2, 4, 6, 8]
let doubled = [Link](num => num * 2);

[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]

// 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 => "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];

let aboveAvg = [Link](num => num > avg);

[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;
}

let primes = [Link](isPrime);


[Link](primes);

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

// 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 : 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 }
];

let total = [Link]((acc, item) => acc + [Link], 0);

[Link](total);

Example5: OUTPUT:
let str = "hello"; “olleh”

let reversed = [Link]("").reduce((acc, char) => char + acc, "");

[Link](reversed);

DOM(Document Object Model)


The DOM is the bridge between your HTML and
JavaScript: it represents the HTML document as a tree
of nodes that JS can read and change. The document
object is the root entry point you use to access and
manipulate that tree.

●​ When a webpage loads, the browser turns HTML into


a tree of objects.​

●​ JavaScript can use this tree to read or change


the webpage.

●​ The browser parses HTML and builds a tree of


nodes (elements, text nodes, comments, etc.).
●​ Each element becomes a Node (an object) you can
inspect and change with JS.
●​ document is the global object that represents the
whole page (the document node).

i) Accessing elements:

a)​[Link](id)

●​ Selects a single element by its id (unique).


●​ Returns the element object, or null if not found.

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.​

●​ Returns an HTMLCollection (like an array, but not


exactly).

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.​

●​ Often used with form inputs.​

●​ 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>

ii) Changing Text:

a)​ What is innerText?


●​ innerText is a DOM property that allows you to get or
set the visible text of an element.​
●​ It ignores hidden text (like with display:none or
visibility:hidden).​

●​ It does not include HTML tags (unlike innerHTML).

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>

Note: When you click the button, "Hello World!"


changes to "Text has been changed!"

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>

iii) Changing HTML

What is .innerHTML?
●​ .innerHTML is a DOM property that allows you to get or set
the HTML content inside an element.​

●​ Unlike .innerText (which only deals with text), .innerHTML


works with HTML tags too

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.

Example3: Add new list items dynamically


<!DOCTYPE html>
<html>
<body>
<ul id="list"></ul>

<script>
[Link]("list").innerHTML =
"<li>Apple</li><li>Banana</li><li>Orange</li>";
</script>
</body>
</html>

Webpage OUTPUT:
●​ Apple
●​ Banana
●​ Orange
iv) Changing Style

<p id="demo">Change my color//with fontsize 20px</p>

<script>
let p = [Link]("demo");
[Link] = "blue";
[Link] = "20px";
</script>

Webpage Output:
Change my color // with fontsize 20px

v) Adding New Element

<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

vi) Handling Events(click)

<button id="btn">Click me</button>


<p id="msg"></p>

<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

Change my color! Change my color! Change my color!

You might also like