0% found this document useful (0 votes)
3 views38 pages

Javascript

JavaScript is a high-level, interpreted scripting language essential for web development, enabling interactivity and dynamic content. It features various data types, operators, and control structures, including functions and loops, which facilitate efficient coding practices. Key aspects include variable declaration methods (var, let, const), primitive and non-primitive data types, and built-in functions for common tasks.

Uploaded by

rpaher
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)
3 views38 pages

Javascript

JavaScript is a high-level, interpreted scripting language essential for web development, enabling interactivity and dynamic content. It features various data types, operators, and control structures, including functions and loops, which facilitate efficient coding practices. Key aspects include variable declaration methods (var, let, const), primitive and non-primitive data types, and built-in functions for common tasks.

Uploaded by

rpaher
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

1.

3 Core JavaScript
JavaScript (JS) is a high-level, interpreted, object-oriented scripting language used to
make web pages interactive and dynamic. It is one of the three core technologies of web
development:

 HTML – Creates the structure of a web page.


 CSS – Styles and designs the web page.
 JavaScript – Adds interactivity and functionality.

JavaScript allows developers to create dynamic content such as image sliders, animations,
form validation, games, calculators, chat applications, and interactive web applications.

Definition

JavaScript is a client-side scripting language used to create dynamic and interactive


web pages. It can also run on the server using environments like [Link].

History of JavaScript

 Developed by Brendan Eich in 1995.


 Created in just 10 days while working at Netscape Communications.
 Initially named Mocha, then LiveScript, and finally JavaScript.
 Standardized by ECMAScript (ES), which defines the official language specification.

Features of JavaScript

1. Lightweight
o Requires less memory and executes quickly.
2. Interpreted Language
o Code is executed line by line without requiring compilation.
3. Object-Oriented
o Supports objects, classes, inheritance, and encapsulation.
4. Dynamic Typing
o Variable types are determined automatically.
5. Event-Driven
o Responds to user actions such as clicks, key presses, and mouse movements.
6. Cross-Platform
o Runs on Windows, Linux, macOS, Android, and iOS.
7. Platform Independent
o Works in almost all modern web browsers.
8. Case Sensitive
o Variable names such as age and Age are treated as different.
1. Variables in JavaScript
Definition

A variable is a container used to store data values. JavaScript provides three ways to declare
variables:

 var
 let
 const

A) var

 Introduced in older JavaScript versions.


 Can be redeclared and updated.
 Function scoped.

Example
var name = "Rahul";
[Link](name);

var name = "Amit";


[Link](name);

Output

Rahul
Amit

B) let

 Introduced in ES6.
 Cannot be redeclared in the same scope.
 Can be updated.
 Block scoped.

Example
let age = 20;
age = 21;

[Link](age);

Output

21
C) const

 Used for constant values.


 Cannot be updated.
 Block scoped.

Example
const PI = 3.14159;

[Link](PI);

Output

3.14159

Difference between var, let and const

Feature var let const

Redeclare Yes No No

Update Yes Yes No

Scope Function Block Block

2. Data Types in JavaScript


Data types specify the type of value stored in variables.

Primitive Data Types


Primitive data types are the basic built-in data types in JavaScript. They store a single
value (not a collection of values) and are immutable, meaning their values cannot be
changed directly. When you modify a primitive value, JavaScript creates a new value instead
of changing the original one.
1. Number - The Number data type is used to store integers and decimal (floating-point)
numbers.

let age = 20;


let price = 199.99;

[Link](age);
[Link](price);
Output

20
199.99

2. String - A string is used to store a text value. It is a sequence of characters. There are
different ways to declare a string: • Double quotes • Single quotes

let name = "Rahul";


let city = 'Pune';

[Link](name);
[Link](city);

Output

Rahul
Pune

3. Boolean - A Boolean stores only two values:

 true
 false

It is commonly used in decision-making and conditional statements.

let isStudent = true;


let isPassed = false;

[Link](isStudent);
[Link](isPassed);

Output

true
false

4. Undefined - A variable that is declared but not assigned a value has the value
undefined.

let city;
[Link](city);

Output

undefined
5. Null - null represents an intentional empty or unknown value. Unlike undefined, it is
assigned explicitly by the programmer.

let address = null;


[Link](address);

Output

null

Difference between null and undefined:

Undefined Null
Value not assigned Intentionally assigned empty value
Assigned automatically Assigned manually by the programmer

6. BigInt - BigInt is used to store very large integers that are larger than the maximum safe
integer for the Number type.

A BigInt value ends with the letter n.

let bigNumber = 123456789123456789123456789n;


[Link](bigNumber);

Output

123456789123456789123456789n

Uses:

 Banking applications
 Scientific calculations
 Large numerical computations

7. Symbol - A Symbol creates a unique identifier. Even if two Symbols have the same
description, they are always different.
Example
let id1 = Symbol("id");
let id2 = Symbol("id");

[Link](id1 === id2);

Output

false

Uses:

 Creating unique object property keys


 Avoiding property name conflicts

Non-Primitive Data Types


Non-primitive data types (also called reference data types) are data types that can store
multiple values or complex data. They are mutable, meaning their contents can be changed
after creation. Non-primitive values are stored by reference, not by value.

[Link]

An object is a collection of key-value pairs used to store related information.

Example
let student = {
name: "Rahul",
age: 20,
course: "BCA"
};

[Link]([Link]);

Output

Rahul

Uses:

 Store student records


 Employee information
 Product details
[Link]

An array stores multiple values in a single variable. Each value is accessed using an index,
starting from 0.

Example
let fruits = ["Apple", "Mango", "Banana"];

[Link](fruits[1]);

Output

Mango

Uses:

 Store list of students


 Product names
 Marks
 Cities

[Link]

A function is a reusable block of code that performs a specific task. It can accept inputs
(parameters) and return a value.

Example
function add(a, b) {
return a + b;
}

[Link](add(10, 20));

Output

30

Uses:

 Perform calculations
 Validate forms
 Reuse code
3. Operators in JavaScript
Operators are special symbols used to perform operations on variables and values. They
help in calculations, comparisons, assignments, logical operations, and much more.

A) Arithmetic Operators
Arithmetic operators perform mathematical calculations.

Operator Meaning Example

+ Addition 5+2

- Subtraction 5-2

* Multiplication 5*2

/ Division 5/2

% Modulus 5%2

** Exponent 2**3

Example
let a = 10;
let b = 5;

[Link](a+b);
[Link](a-b);
[Link](a*b);
[Link](a/b);
[Link](a%b);

Output

15
5
50
2
0

B) Assignment Operators
Assignment operators assign values to variables.
Operator Meaning Example
= Assign x = 10
+= Add and assign x += 5
-= Subtract and assign x -= 5
*= Multiply and assign x *= 2
Operator Meaning Example
/= Divide and assign x /= 2
%= Modulus and assign x %= 3
**= Power and assign x **= 2

let a = 10;
let b = 10;
let c = 10;
let d = 10;
let e = 10;
let f = 10;

a += 5;
b -= 5;
c *= 5;
d /= 5;
e %= 5;
f **= 5;
[Link](a);
[Link](b);
[Link](c);
[Link](d);
[Link](e);
[Link](f);

Output

15
5
50
2
0
100000

C) Comparison Operators
Comparison operators compare two values and return true or false.

Operator Meaning

== Equal

=== Strict Equal

!= Not Equal
Operator Meaning

> Greater

< Less

>= Greater or Equal

<= Less or Equal

Example
[Link](5 == "5");
[Link](5 === "5");

Output

true
false

D) Logical Operators
Logical operators combine multiple conditions.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Example 1
let age = 20;
[Link](age > 18 && age < 30);

Output

true

Example 2
let marks = 35;
[Link](marks >= 40 || marks >= 30);

Output

true
Example 3
let isStudent = true;
[Link](!isStudent);

Output

false

E) Increment and Decrement Operators

These operators increase or decrease a variable by 1.

Operator Description

++ Increment

-- Decrement

Pre-Increment
let x = 5;
[Link](++x);

Output

Post-Increment
let x = 5;
[Link](x++);
[Link](x);

Output

5
6

Pre-Decrement
let x = 10;
[Link](--x);

Output

9
Post-Decrement
let x = 10;
[Link](x--);
[Link](x);

Output

10
9

F) String Operator

The + operator joins (concatenates) strings.

let first = "Java";


let second = "Script";

[Link](first + second);

Output

JavaScript

With a space:

[Link](first + " " + second);

Output

JavaScript

G)Ternary (Conditional) Operator

A shorthand way to write an if...else statement.

Syntax

condition ? expression1 : expression2;


Example
let age = 18;
let result = age >= 18 ? "Eligible to Vote" : "Not Eligible";
[Link](result);

Output

Eligible to Vote
4. Conditional Statements
Conditional statements are used to execute different blocks of code depending on whether a
condition is true or false.

A) if Statement - The if statement executes a block of code only if the condition is true.

let age = 20;

if (age >= 18) {


[Link]("You are eligible to vote.");
}
Output
You are eligible to vote.

B) if-else Statement - The if...else statement executes one block if the condition is true and
another block if the condition is false.

let marks = 40;

if (marks >= 35) {


[Link]("Pass");
}
else {
[Link]("Fail");
}
Output
Pass

C) else-if Ladder - Used when multiple conditions need to be checked.


let marks = 85;

let marks = 82;

if (marks >= 90) {


[Link]("Grade A");
}
else if (marks >= 75) {
[Link]("Grade B");
}
else if (marks >= 60) {
[Link]("Grade C");
}
else if (marks >= 35) {
[Link]("Grade D");
}
else {
[Link]("Fail");
}
Output
Grade B

D) switch Statement - The switch statement is used to choose one block of code from
multiple options.
let day = 3;

switch(day) {

case 1:
[Link]("Monday");
break;

case 2:
[Link]("Tuesday");
break;

case 3:
[Link]("Wednesday");
break;

case 4:
[Link]("Thursday");
break;

default:
[Link]("Invalid Day");

}
Output
Wednesday

5. Loops

Loops are used to execute the same block of code repeatedly until a condition becomes false.
A) for Loop - Used when the number of iterations is known.
Syntax
for(initialization; condition; increment) {

}
Flow
Initialization

Condition

True

Code

Increment

Condition Again

Example 1
for(let i=1; i<=5; i++) {
[Link](i);
}
Output
1
2
3
4
5

B) while Loop - The while loop repeats as long as the condition is true.

Syntax
while(condition) {

}
Example
let i = 1;

while(i <= 5){

[Link](i);

i++;
}
Output
1
2
3
4
5

C) do-while Loop - The do...while loop executes the code at least once, even if the
condition is false.
Syntax
do{

}
while(condition);
Example
let i = 1;

do{

[Link](i);

i++;

}
while(i<=5);
Output
1
2
3
4
5

D) for...of Loop - Used to iterate over iterable objects like arrays and strings.
Syntax
for(let value of iterable){

}
Example (Array)
let fruits = ["Apple", "Banana", "Mango"];

for(let fruit of fruits){


[Link](fruit);
}
Output
Apple
Banana
Mango

E) for...in Loop - Used to iterate over the properties (keys) of an object.

Syntax
for(let key in object){

}
Example
let student = {
name: "Rahul",
age: 20,
city: "Pune"
};

for(let key in student){


[Link](key, student[key]);
}
Output
name Rahul
age 20
city Pune

Loop Control Statements

break Statement

Stops the loop immediately.

Example
for(let i=1; i<=10; i++){

if(i==6){
break;
}

[Link](i);
}
Output
1
2
3
4
5

continue Statement

Skips the current iteration and continues with the next one.

Example
for(let i=1; i<=5; i++){

if(i==3){
continue;
}

[Link](i);
}
Output
1
2
4
5

6. Functions and Scope


Function

A function is a reusable block of code that performs a specific task. Instead of writing the
same code multiple times, you can write it once inside a function and call (invoke) it
whenever needed.

Functions are one of the most important concepts in JavaScript because they make programs:

 Reusable – Write once, use many times.


 Organized – Keep code clean and structured.
 Easy to Maintain – Changes are made in one place.
 Modular – Break large programs into smaller parts.
 Readable – Easier for others to understand.

Built-in Functions
JavaScript provides many predefined (built-in) functions.

Function Purpose
[Link]() Displays output in the console
Function Purpose
alert() Shows a popup message
prompt() Accepts input from the user
confirm() Displays a confirmation dialog
parseInt() Converts a string to an integer
parseFloat() Converts a string to a decimal number
Number() Converts a value to a number
String() Converts a value to a string

User-Defined Functions
Functions created by the programmer are called user-defined functions.

Example
function square() {
[Link](5 * 5);
}

square();

Output

25

Function Naming Rules

A function name:

 Must begin with a letter, _, or $


 Cannot begin with a number
 Cannot contain spaces
 Cannot use JavaScript reserved keywords
 Should describe the task clearly

Good Names
calculateSalary()

findLargest()

displayStudent()

printTable()
Bad Names
function 123test()

function var()

function my function()

These are invalid.

Function Declaration

A function declaration defines a function using the function keyword.

Syntax
function functionName() {

Example

function sayHello() {
[Link]("Hello");
}

Function Execution Flow

Program Starts

Function Created

Function Called

Statements Execute

Program Continues

Advantages of Functions
1. Code Reusability - Write once and use many times.
2. Less Code - Avoid writing duplicate code.
3. Easy Debugging - Errors are easier to locate.
4. Better Organization - Large programs become manageable.
5. Easy Maintenance - Changes are made in one place.
6. Improved Readability - Functions divide code into meaningful sections.

Arrow Function - Arrow functions are a special way of writing functions


const square=(n)=>
{
return n*n;
};

[Link](square(5));

Output

25

Scope
Scope determines the visibility and accessibility of variables, functions, and objects in
different parts of a JavaScript program.

Global Scope
A variable declared outside every function and block belongs to the Global Scope.
let college = "ABC College";

function display() {
[Link](college);
}

display();

[Link](college);

Output

ABC College
ABC College

Local Scope
Variables declared inside a function are called Local Variables.
function demo() {
let city = "Mumbai";
[Link](city);
}

demo();

Output

Mumbai

Block Scope
A block is any code enclosed within { }.

Variables declared with:

 let
 const

are block scoped.

They exist only inside that block.

Example using let


{
let age = 20;
[Link](age);
}

[Link](age);

Output

20
ReferenceError

Example using const


{
const PI = 3.14;
[Link](PI);
}

[Link](PI);

Output

3.14
ReferenceError
7. Arrays and Objects Manipulation
JavaScript Arrays

An array is a special JavaScript object used to store multiple values in a single variable.

Syntax
let arrayName = [value1, value2, value3];
Example
let fruits = ["Apple", "Banana", "Mango"];

[Link](fruits);

Output

["Apple", "Banana", "Mango"]

Instead of writing

let student1 = "Rahul";


let student2 = "Priya";
let student3 = "Amit";

We can write

let students = ["Rahul", "Priya", "Amit"];

This makes code shorter and easier to manage.

Array Index

Array elements are stored using indexes.

Index starts from 0.

Index Value

0 Apple

1 Banana

2 Mango

Example

let fruits = ["Apple", "Banana", "Mango"];


[Link](fruits[0]);
[Link](fruits[1]);
[Link](fruits[2]);

Output

Apple
Banana
Mango

Creating Arrays

Method 1: Array Literal (Most Common)


let numbers = [10, 20, 30, 40];

Method 2: Using Array Constructor


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

[Link](numbers);

Output

[10,20,30]

Array Can Store Different Data Types

let data = [
"Rahul",
21,
true,
95.5
];

[Link](data);

Output

["Rahul",21,true,95.5]

Finding Array Length

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

[Link]([Link]);
Output

Modifying Array Elements

let fruits = ["Apple","Banana","Mango"];

fruits[1] = "Orange";

[Link](fruits);

Output

["Apple","Orange","Mango"]

Adding Elements

push()

Adds element at the end.

let numbers = [10,20,30];

[Link](40);

[Link](numbers);

Output

[10,20,30,40]

unshift()

Adds element at the beginning.

let numbers = [20,30];

[Link](10);

[Link](numbers);

Output

[10,20,30]
Removing Elements

pop()

Removes last element.

let fruits = ["Apple","Banana","Mango"];

[Link]();

[Link](fruits);

Output

["Apple","Banana"]

shift()

Removes first element.

let fruits = ["Apple","Banana","Mango"];

[Link]();

[Link](fruits);

Output

["Banana","Mango"]

Inserting and Removing Elements

splice()

Syntax

[Link](start, deleteCount, item1, item2);

Example

let fruits = ["Apple","Banana","Mango"];

[Link](1,1,"Orange");

[Link](fruits);

Output
["Apple","Orange","Mango"]

Extracting Part of an Array

slice()
let numbers = [10,20,30,40,50];

let result = [Link](1,4);

[Link](result);

Output

[20,30,40]

Searching Arrays

indexOf()
let fruits = ["Apple","Banana","Mango"];

[Link]([Link]("Banana"));

Output

includes()
let fruits = ["Apple","Banana","Mango"];

[Link]([Link]("Apple"));

Output

true

Joining Arrays

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

[Link]([Link]("-"));

Output

Red-Green-Blue
Reversing Arrays

let numbers = [1,2,3];

[Link]();

[Link](numbers);

Output

[3,2,1]

Sorting Arrays

let numbers = [50,10,30,20];

[Link]();

[Link](numbers);

Output

[10,20,30,50]

For numbers in ascending order:

let numbers = [50, 10, 30, 20];

[Link]((a, b) => a - b);

[Link](numbers);

Output:

[10,20,30,50]

Looping Through Arrays

Using for Loop


let fruits = ["Apple","Banana","Mango"];

for(let i=0;i<[Link];i++)
{
[Link](fruits[i]);
}
Using for...of
let fruits = ["Apple","Banana","Mango"];

for(let fruit of fruits)


{
[Link](fruit);
}

Using forEach()
let fruits = ["Apple","Banana","Mango"];

[Link](function(item)
{
[Link](item);
});

Common Array Methods

Method Purpose

push() Add at end

pop() Remove from end

shift() Remove first

unshift() Add first

slice() Extract portion

splice() Add/Remove elements

sort() Sort array

reverse() Reverse array

join() Convert to string

includes() Check value

indexOf() Find index

forEach() Loop through array

map() Create new array by transforming elements

filter() Return elements matching a condition


Method Purpose

reduce() Reduce array to a single value

Objects

An object is a collection of properties, where each property consists of a key (property


name) and a value.

Objects are used to represent real-world entities.

Example:

Student

 Name
 Age
 Course
 Marks

Syntax

let objectName = {
key1: value1,
key2: value2
};

Example

let student = {
name: "Rahul",
age: 20,
course: "BCA"
};

[Link](student);

Output

{
name:"Rahul",
age:20,
course:"BCA"
}
Accessing Object Properties

Dot Notation
[Link]([Link]);

Output

Rahul

Bracket Notation
[Link](student["age"]);

Output

20

Bracket notation is useful when the property name is stored in a variable.

let key = "course";


[Link](student[key]);

Output

BCA

Modifying Object Properties

[Link] = 21;

[Link](student);

Output

{
name:"Rahul",
age:21,
course:"BCA"
}

Adding New Properties

[Link] = "Nashik";

[Link](student);
Output

{
name:"Rahul",
age:21,
course:"BCA",
city:"Nashik"
}

Deleting Properties

delete [Link];

[Link](student);

Output

{
name:"Rahul",
age:21,
city:"Nashik"
}

Object Methods

Objects can also contain functions called methods.

let person = {
name: "Amit",

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

[Link]();

Output

Hello

Using this Keyword

this refers to the current object.


let person = {
name: "Amit",

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

[Link]();

Output

Hello Amit

Nested Objects

let student = {
name: "Rahul",

address: {
city: "Nashik",
state: "Maharashtra"
}
};

[Link]([Link]);

Output

Nashik

Array of Objects

let students = [
{
name: "Rahul",
age: 20
},
{
name: "Priya",
age: 21
},
{
name: "Amit",
age: 22
}
];

[Link](students[1].name);

Output

Priya

Looping Through Objects

Using for...in
let student = {
name: "Rahul",
age: 20,
city: "Nashik"
};

for(let key in student)


{
[Link](key, student[key]);
}

Output

name Rahul
age 20
city Nashik

Object Built-in Methods

[Link]()
let student = {
name: "Rahul",
age: 20
};

[Link]([Link](student));

Output

["name","age"]

[Link]()
[Link]([Link](student));
Output

["Rahul",20]

[Link]()
[Link]([Link](student));

Output

[
["name","Rahul"],
["age",20]
]

Array vs Object

Feature Array Object

Stores Ordered collection of values Key-value pairs

Access by Index (0, 1, 2, …) Property name (key)

Syntax [] {}

Use Case Lists of similar items Represent real-world entities with named properties

Example ["Apple","Banana"] {name:"Rahul", age:20}

8. DOM (Document Object Model)


The DOM represents the HTML document as a tree of objects. JavaScript uses the DOM to
access and modify webpage elements.

DOM Selection
By ID

HTML

<p id="demo">Hello</p>

JavaScript

let element=[Link]("demo");

[Link](element);
By Class
[Link]("box");

By Tag
[Link]("p");

Query Selector
[Link](".box");

Query Selector All


[Link]("p");

DOM Traversal

Moving between DOM elements.

<div id="parent">
<p>Paragraph</p>
</div>

let parent=[Link]("parent");

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

DOM Modification

Change Text
[Link]("demo").textContent="Welcome";

Change HTML
[Link]("demo").innerHTML="<b>Hello</b>";

Change Style
[Link]("demo").[Link]="red";

Change Attribute
[Link]("image").src="[Link]";
Create New Element
let p=[Link]("p");

[Link]="New Paragraph";

[Link](p);

9. Event Handling
An event is an action performed by the user or browser, such as clicking a button, submitting
a form, pressing a key, or loading a page. JavaScript responds to these actions using event
handlers.

A) Click Event

HTML

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


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

JavaScript

[Link]("btn").addEventListener("click", function() {
[Link]("msg").textContent = "Button clicked!";
});

B) Submit Event

HTML

<form id="myForm">
<input type="text" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>

JavaScript

[Link]("myForm").addEventListener("submit", function(event) {
[Link](); // Prevent page reload
alert("Form submitted successfully!");
});

C) Keyboard Event

HTML-+++++++++++++++++++++++++++++
<input type="text" id="name">

JavaScript

[Link]("name").addEventListener("keydown", function(event) {
[Link]("Key pressed:", [Link]);
});

Common keyboard events:

 keydown – Fires when a key is pressed.


 keyup – Fires when a key is released.
 keypress – Deprecated; avoid using in new code.

D) Load Event

The load event occurs when the page and its resources have finished loading.

[Link]("load", function() {
[Link]("Page loaded successfully!");
});

You might also like