0% found this document useful (0 votes)
1 views55 pages

JavaScript NOTES

JavaScript is a high-level, interpreted scripting language primarily used for creating interactive web pages. It allows for dynamic content, form validation, and user event responses, and can be easily integrated with HTML and CSS. Key features include being lightweight, client-side executed, platform-independent, and supporting object-oriented programming.

Uploaded by

roopa170121
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)
1 views55 pages

JavaScript NOTES

JavaScript is a high-level, interpreted scripting language primarily used for creating interactive web pages. It allows for dynamic content, form validation, and user event responses, and can be easily integrated with HTML and CSS. Key features include being lightweight, client-side executed, platform-independent, and supporting object-oriented programming.

Uploaded by

roopa170121
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

✅ What is JavaScript?
• JavaScript (JS) is a high-level, interpreted scripting language used to make web pages
interactive.
• It runs in the browser (like Chrome, Firefox).

It is mainly used for:

• Adding dynamic content (e.g., updating text without reloading)


• Validating forms
• Responding to user events (clicks, inputs)
• Animations, interactive games, etc.

✅ Why Learn JavaScript?


• Makes web pages dynamic and interactive.
• Easy to learn and widely used.
• Works with HTML & CSS to build modern websites.

✅ General Syntax of JavaScript


1. JavaScript code is written inside the <script> tag in an HTML document.
2. It can also be placed in an external .js file and linked.

Basic Structure
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Syntax Example</title>

<script>
// This is a JavaScript statement
alert('Hello, Raksha!');
</script>

</head>
<body>

<h2>JavaScript Syntax Example</h2>

</body>
</html>
✅ Characteristics of JavaScript

Lightweight

• JavaScript is a lightweight scripting language.


• Designed mainly for small tasks in web pages (like animations or form validation).

Interpreted Language

• JavaScript code is interpreted by the browser, not compiled.


No need to compile — just write and run.
Client-Side Execution

• By default, JavaScript runs on the user’s browser (client-side).


• Fast response and less load on the server.

Platform Independent

• Works across all platforms and browsers (Windows, Mac, Linux, Android).
Write once, run everywhere.

Event-Driven

• JavaScript can respond to user actions like:


o Mouse clicks
o Keyboard input
o Scrolling
o Form submit
Example:
<button onclick="alert('Button Clicked!')">Click Me</button>

Object-Oriented

• Supports objects for organizing code and data.


Example:
let person = {
name: "Raksha",
age: 20
};
Dynamic Typing
• Variables don’t require explicit data types.
let x = 5;
x = "Hello"; // Allowed
✅ Summary Table

Characteristic Meaning

Lightweight Small, efficient language

Interpreted No compilation needed

Client-Side Execution Runs in browser

Platform Independent Works in all environments

Event-Driven Reacts to user actions

Object-Oriented Supports objects

Dynamic Typing No type declaration needed

✅ Advantages of JavaScript

Easy to Learn and Use


• JavaScript has simple syntax and is easy for beginners.
• Doesn’t require complex setup (just a browser).

Client-Side Execution
• Runs directly in the browser →
Faster response without waiting for the server.
Reduces server load.

Platform Independent
• Works on all operating systems and browsers (Windows, Mac, Linux, Chrome, Firefox, Edge).
Write once, run everywhere.

Interactivity
• Allows interaction with users:
o Form validation
o Animations
o Interactive games
o Real-time updates without refreshing the page.

Integration with HTML and CSS


• Works perfectly with HTML and CSS to:
o Change content dynamically
o Modify styles
o Respond to events (click, hover, input).
Supports Object-Oriented Programming
• Allows creating objects, methods, and reusable code.
let person = {
name: "Raksha",
age: 20
};

Wide Browser Support


• Supported by all modern browsers by default.
No need to install anything extra.

Rich Ecosystem
• Large community + plenty of libraries (e.g., jQuery, React, Angular).
Makes development faster and easier.

Summary Table

Advantage Description

Easy to Learn Simple syntax for beginners

Client-Side Execution Fast user interaction without server delay

Platform Independent Works on any OS/browser

Interactive Animations, form validation, games

Works with HTML & CSS Controls content & style easily

Object-Oriented Reusable code using objects

Wide Browser Support No installation required

Rich Ecosystem Lots of libraries and frameworks available


JavaScript Variables
1. What is a Variable?

• A variable is a container used to store data values.


• Example: let age = 20; → here age is a variable storing the value 20.
2. Declaring Variables

JavaScript provides three keywords to declare variables:

var
• Old way (before ES6).
• Function-scoped (accessible inside functions).
var name = "Raksha";

let
• Modern way (introduced in ES6).
• Block-scoped (accessible only inside { }).
let age = 22;

const
• Used for constants (values that don’t change).
const PI = 3.14159;
3. Rules for Naming Variables

✔ Must begin with a letter, _ (underscore), or $.


✔ Can’t begin with a number.
✔ Can contain letters, digits, underscores, and dollar signs.
✔ Case-sensitive → Name and name are different.
✔ No reserved keywords allowed (like let, var, if).

Examples
let myName = "Raksha";
let $price = 100;
let _count = 5;
Examples

let 2value = 10; // starts with number

let var = 5; // reserved keyword


4. Example Program
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Variables</title>
</head>
<body>
<h2>JavaScript Variables Example</h2>
<script>
var name = "Raksha"; // using var
let age = 22; // using let
const country = "India"; // using const

[Link]("Name: " + name + "<br>");


[Link]("Age: " + age + "<br>");
[Link]("Country: " + country);
</script>

</body>
</html>

👉 Output:
Name: Raksha
Age: 22
Country: India
✅ 5. Summary Table

Keyword Scope Changeable? Hoisting

var Function scope Yes Yes

let Block scope Yes No

const Block scope No No

JavaScript Comments
What is a Comment?
• A comment is text in the code that the browser ignores.
• Used for:
o Explaining code
o Debugging
o Making code readable
Types of Comments in JavaScript

1. Single-Line Comment
• Starts with //
• Anything after // is ignored.
// This is a single-line comment
let name = "Raksha"; // Variable declaration

2. Multi-Line Comment
• Starts with /* and ends with */
• Can span multiple lines.
/* This is a multi-line comment
It can explain the code in detail */
let age = 22;
✅ Example Program (Comments in Action)
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Comments</title>
</head>
<body>
<h2>JavaScript Comments Example</h2>
<script>
// Single-line comment
let name = "Raksha";

/* Multi-line comment
Explaining variables */
let age = 22;

[Link]("Name: " + name + "<br>");


[Link]("Age: " + age);
</script>

</body>
</html>

👉 Output:
Name: Raksha
Age: 22

Quick Summary

Type Symbol Example

Single-line // // Hello World

Multi-line /* ... */ /* This is a comment */


JavaScript Data Types
Data types define the kind of values a variable can hold.
JavaScript has two main categories:
1. Primitive Data Types
2. Non-Primitive (Reference) Data Types
1. Primitive Data Types
These are the basic, simple values in JavaScript.

a) String
• Text values inside quotes.
let name = "Raksha";

b) Number
• Numeric values (integers, decimals).
let age = 22;
let price = 99.99;

c) Boolean
• Only two values: true or false.
let isStudent = true;

d) Undefined
• A variable declared but not assigned a value.
let x;
[Link](x); // undefined

e) Null
• Represents empty or no value.
let data = null;

f) Symbol (ES6)
• Used for unique values.
let id = Symbol("123");

g) BigInt (ES11)
• For very large numbers beyond normal limits.

let bigNum = 123456789012345678901234567890n;


2. Non-Primitive (Reference) Data Types
These can hold collections of values.

a) Object
• Stores data in key–value pairs.
let person = {
name: "Raksha",
age: 22
};

b) Array
• Stores a collection of values (list).
let fruits = ["Apple", "Banana", "Mango"];

c) Function
• Functions are also treated as objects in JavaScript.
function greet() {
return "Hello Raksha!";
}

✅ Example Program
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Data Types</title>
</head>
<body>
<h2>JavaScript Data Types Example</h2>
<script>
let name = "Raksha"; // String
let age = 22; // Number
let isStudent = true; // Boolean
let x; // Undefined
let data = null; // Null
let fruits = ["Apple", "Banana", "Mango"]; // Array
let person = { name: "Raksha", age: 22 }; // Object

[Link]("Name: " + name + "<br>");


[Link]("Age: " + age + "<br>");
[Link]("Is Student: " + isStudent + "<br>");
[Link]("Undefined: " + x + "<br>");
[Link]("Null: " + data + "<br>");
[Link]("Fruits: " + fruits + "<br>");
[Link]("Person: " + [Link] + ", " + [Link] + "<br>");
</script>
</body>
</html>

✅ Quick Summary Table

Data Type Example

String "Hello"

Number 25, 3.14

Boolean true, false

Undefined let x;

Null let y = null;

Object {name:"Raksha", age:22}

Array ["Apple", "Banana"]


Screen Output and Keyboard Input in JavaScript
1. Screen Output in JavaScript
JavaScript provides several ways to display (output) information on the screen.

a) Using [Link]()
• Displays output directly on the webpage.
• Mostly used for demonstrations and simple programs.
<script>
[Link]("Hello, Raksha! Welcome to JavaScript!");
</script>

Output:
Displays the text directly on the browser page.

b) Using alert()
• Displays a popup message box.
• Used for notifications, warnings, or validations.
<script>
alert("Welcome to my website!");
</script>

Output:
A popup box appears with the message “Welcome to my website!”
c) Using [Link]()
• Prints messages in the browser’s console (used by developers for debugging).
<script>
[Link]("This is a console message.");
</script>

Output:
The message appears inside the Console tab of the browser’s Developer Tools.

d) Using innerHTML
• Displays content inside an HTML element (like <p> or <div>).
<p id="output"></p>
<script>
[Link]("output").innerHTML = "Hello from JavaScript!";
</script>
Output:
Displays “Hello from JavaScript!” inside the paragraph.

2. Keyboard Input in JavaScript


JavaScript doesn’t have a direct input() function like C or Python.
Instead, we can take user input using these methods:

a) Using prompt()
• Displays a popup input box to take user input.
<script>
let name = prompt("Enter your name:");
[Link]("Hello, " + name + "!");
</script>

Output:
Shows an input box asking for the name → then displays:
“Hello, Raksha!”

b) Using <input> and Event Handling


• We can get user input from form fields using the value property.
Name: <input type="text" id="userName">
<button onclick="displayName()">Submit</button>
<p id="msg"></p>
<script>
function displayName() {
let name = [Link]("userName").value;
[Link]("msg").innerHTML = "Hello, " + name + "!";
}
</script>

Output:
When user types a name and clicks Submit → it displays “Hello, [name]!”

c) Keyboard Events (onkeypress, onkeydown, onkeyup)


Used to detect when the user presses a key.
<input type="text" onkeypress="alert('Key pressed!')">

Output:
Shows alert when any key is pressed inside the textbox.
✅ 3. Summary Table

Output Method Description Example

[Link]() Writes directly to webpage [Link]("Hello")

alert() Popup box alert("Hi!")

[Link]() Message in console [Link]("Debug info")

innerHTML Writes inside HTML element [Link]="Text"

Input Method Description Example

prompt() Popup input box prompt("Enter name:")

<input> + JS Form-based input [Link]

Keyboard Events Detect key press onkeypress, onkeydown, onkeyup


Operators in JavaScript
1️⃣ Definition
• Operators are symbols that perform operations on values and variables.
• They are used to compute, compare, and assign values in expressions.
Example:
let x = 10, y = 5;
let sum = x + y; // + is an operator

Types of Operators
JavaScript supports several categories of operators:
1. Arithmetic Operators
2. Assignment Operators
3. Comparison (Relational) Operators
4. Logical Operators
5. Bitwise Operators
6. String Operators
7. Conditional (Ternary) Operator

✅ Arithmetic Operators
Used to perform mathematical calculations.

Operator Description Example Result

+ Addition 10 + 5 15

- Subtraction 10 - 5 5

* Multiplication 10 * 5 50

/ Division 10 / 5 2

% Modulus (remainder) 10 % 3 1

++ Increment x++ Increases by 1

-- Decrement x-- Decreases by 1

Example:
let a = 10, b = 3;
[Link](a + b); // 13
[Link](a % b); // 1
a++;
[Link](a); // 11

Assignment Operators
Used to assign values to variables.

Operator Example Meaning

= x = 10 Assign 10 to x

+= x += 5 x=x+5

-= x -= 5 x=x-5

*= x *= 2 x=x*2

/= x /= 2 x=x/2

%= x %= 2 x=x%2

Example:
let x = 10;
x += 5; // x = 15

✅ Comparison (Relational) Operators


Used to compare two values and return a Boolean (true/false).

Operator Description Example Result

== Equal to (value only) 5 == "5" true

=== Equal to (value + type) 5 === "5" false

!= Not equal 5 != 8 true

!== Not equal (value + type) 5 !== "5" true

> Greater than 10 > 5 true

< Less than 5 < 10 true

>= Greater or equal 5 >= 5 true


Operator Description Example Result

<= Less or equal 3 <= 5 true

✅ Logical Operators
Used to combine multiple conditions.

Operator Description Example Result


&& AND (x > 5 && y < 10) true if both true

` ` OR

! NOT !(x > 5) reverses result

Example:
let a = 10, b = 5;
[Link](a > 5 && b < 10); // true
[Link](a < 5 || b < 10); // true
[Link](!(a == 10)); // false

✅ Bitwise Operators
Operate on binary (bit) values.

Operator Description Example Result

& AND 5&1 1

` ` OR `5

^ XOR 5^1 4

~ NOT ~5 -6

<< Left Shift 5 << 1 10

>> Right Shift 5 >> 1 2

(Note: Used rarely in basic web tasks — more in low-level programming.)

✅ String Operator
• The + operator can also join (concatenate) strings.
let firstName = "Ram";
let lastName = "Priya";
[Link](firstName + " " + lastName); // Ram Priya

✅ Conditional (Ternary) Operator


• Acts like a short if–else statement.
let age = 18;
let result = (age >= 18) ? "Eligible" : "Not Eligible";
[Link](result);

Output: Eligible
Type Conversion in JavaScript

1️⃣ Definition
• Type Conversion means changing a value from one data type to another (e.g., number →
string).
• JavaScript supports two types of type conversion:

Type Description

Implicit Conversion Automatic conversion done by JavaScript (Type Coercion)

Explicit Conversion Manual conversion done by the programmer

2️⃣ Implicit Type Conversion (Type Coercion)


• JavaScript automatically converts one data type to another when needed.
Example 1: String + Number
let result = "5" + 2;
[Link](result); // "52" → number is converted to string

Example 2: Number + String + Number


let value = 5 + "10" + 20;
[Link](value); // "51020" → everything becomes string

Example 3: Arithmetic with Strings


let result = "10" - 2;
[Link](result); // 8 → string converted to number

Rule:
• If you use + with a string → concatenation happens.
• Other operators (-, *, /) → convert strings to numbers.
3️⃣ Explicit Type Conversion (Manual Conversion)
You can manually convert values using built-in functions.

a) String Conversion
• Convert any value into a string.
let num = 123;
let str1 = String(num);
let str2 = [Link]();

[Link](str1); // "123"
[Link](typeof str1); // string

b) Number Conversion
• Convert a value into a number.
let str = "25";
let num1 = Number(str);
let num2 = parseInt("100.50");
let num3 = parseFloat("50.55");

[Link](num1, num2, num3); // 25 100 50.55

Number() → converts entire string


parseInt() → converts only integer part
parseFloat() → converts decimal values

c) Boolean Conversion
• Convert a value into true or false.
[Link](Boolean(10)); // true
[Link](Boolean(0)); // false
[Link](Boolean("")); // false
[Link](Boolean("Hi")); // true

Rule:

Value Result

0, null, undefined, "" false

All others true


d) Automatic toString() in Output
let x = 10 + "5";
[Link](x); // "105" (number converted to string)

Examples Comparing Implicit and Explicit

Expression Type Conversion Output

"5" + 2 Implicit (to string) "52"

"5" - 2 Implicit (to number) 3

Number("5") + 2 Explicit 7

String(5 + 2) Explicit "7"

Full Example Program


<!DOCTYPE html>
<html>
<head>
<title>Type Conversion in JavaScript</title>
</head>
<body>
<h2>Type Conversion Example</h2>
<script>
// Implicit Conversion
[Link]("Result of '5' + 2: " + ("5" + 2) + "<br>");
[Link]("Result of '5' - 2: " + ("5" - 2) + "<br>");
// Explicit Conversion
let num = "25";
[Link]("Number('25') + 5 = " + (Number(num) + 5) + "<br>");
[Link]("String(100) = " + String(100) + "<br>");
[Link]("Boolean(0) = " + Boolean(0) + "<br>");
</script>

</body>
</html>
Output:
Result of '5' + 2: 52
Result of '5' - 2: 3
Number('25') + 5 = 30
String(100) = 100
Boolean(0) = false

✅ Summary Table

Function / Operator Converts To Example Output

String(value) String String(123) "123"

[Link]() String (10).toString() "10"

Number(value) Number Number("5") 5

parseInt(value) Integer parseInt("10.5") 10

parseFloat(value) Float parseFloat("10.5") 10.5

Boolean(value) Boolean Boolean("") false


Flow Control in JavaScript
✅ Definition
• Flow control statements determine how the program executes — they control the order of
execution of statements based on certain conditions.
• There are three main types:

Type Purpose

Conditional Statements Make decisions based on conditions

Looping Statements Repeat actions multiple times

Jumping Statements Transfer control to another part of the program

1. Conditional Statements
Conditional statements are used to perform different actions based on conditions.

a) if Statement
Executes a block of code only if a 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
Executes one block if the condition is true, otherwise another block.
let marks = 40;
if (marks >= 50) {
[Link]("Pass");
} else {
[Link]("Fail");
}

Output: Fail
c) if...else if...else Statement
Used when there are multiple conditions to check.
let score = 75;
if (score >= 90) {
[Link]("Grade A");
} else if (score >= 75) {
[Link]("Grade B");
} else if (score >= 50) {
[Link]("Grade C");
} else {
[Link]("Fail");
}

Output: Grade B

d) switch Statement
Used to select one option among many.
let day = 3;
switch (day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
default: [Link]("Invalid Day");
}

Output: Wednesday
2. Looping Statements
Loops are used to repeat a block of code multiple times until a condition is false.

a) for Loop
Used when the number of iterations is known.
for (let i = 1; i <= 5; i++) {
[Link]("Count: " + i);
}

Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

b) while Loop
Executes as long as the condition is true.
let i = 1;
while (i <= 3) {
[Link]("Number: " + i);
i++;
}

Output:
Number: 1
Number: 2
Number: 3

c) do...while Loop
Executes at least once, even if condition is false.
let i = 1;
do {
[Link]("Hello " + i);
i++;
} while (i <= 3);
Output:
Hello 1
Hello 2
Hello 3

3. Jumping Statements
These statements change the normal flow of control in a program.

a) break
Used to exit a loop or switch statement immediately.
for (let i = 1; i <= 5; i++) {
if (i == 3) break;
[Link](i);
}

Output:
1
2

b) continue
Used to skip the current iteration and move to the next one.
for (let i = 1; i <= 5; i++) {
if (i == 3) continue;
[Link](i);
}

Output:
1
2
4
5
c) return
Used inside a function to return a value and exit the function.
function add(a, b) {
return a + b;
}
[Link](add(5, 10)); // 15

✅ Full Example Program


<!DOCTYPE html>
<html>
<head>
<title>Flow Control in JavaScript</title>
</head>
<body>
<h2>Flow Control Example</h2>
<script>

// Conditional
let age = 18;
if (age >= 18) {
[Link]("Eligible to vote<br>");
} else {
[Link]("Not eligible<br>");
}

// Loop
for (let i = 1; i <= 3; i++) {
[Link]("Loop count: " + i + "<br>");
}

// Jumping
for (let j = 1; j <= 5; j++) {
if (j == 3) continue;
[Link]("Value: " + j + "<br>");
}
</script>

</body>
</html>
Output:
Eligible to vote
Loop count: 1
Loop count: 2
Loop count: 3
Value: 1
Value: 2
Value: 4
Value: 5

✅ Summary Table

Type Statement Purpose

Conditional if, if-else, switch Make decisions

Looping for, while, do-while Repeat code

Jumping break, continue, return Control flow

Real-Life Uses:
• Conditional: Form validation (if field is empty → show error).
• Looping: Display list of products, iterate through array.
• Jumping: Stop loop when a condition is met (like login success).
JavaScript Functions

✅ 1. Basics of Functions
• A function is a block of code designed to perform a task.
• It runs only when it is called (invoked).

Syntax:
function functionName() {
// code to be executed
}

Example:
function greet() {
[Link]("Hello, Raksha!<br>");
}

✅ 2. Function Parameters
• Functions can take inputs called parameters.
• Values passed are called arguments.
function greetUser(name) {
[Link]("Hello, " + name + "!<br>");
}
greetUser("Raksha"); // Argument "Raksha"

Output: Hello, Raksha!

✅ 3. Function Invocation (Calling a Function)


• To run a function, just call it using its name followed by ().
function add(a, b) {
[Link](a + b);
}
add(5, 10); // Function invocation

Output: 15
4. Return Statement
• A function can return a value using the return keyword.
function multiply(x, y) {
return x * y;
}
let result = multiply(4, 5);
[Link]("Result: " + result);

Output: Result: 20

✅ 5. Global and Local Variables

Global Variable
• Declared outside any function.
• Accessible everywhere.
let globalVar = "I am Global"; // Global
function showGlobal() {
[Link](globalVar + "<br>");
}
showGlobal();
[Link](globalVar);

Output:
I am Global
I am Global

Local Variable
• Declared inside a function.
• Accessible only within that function.
function showLocal() {
let localVar = "I am Local"; // Local
[Link](localVar);
}
showLocal();

// [Link](localVar); // Error: not defined


Full Example Program (All Concepts)
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Functions</title>
</head>
<body>
<h2>JavaScript Functions Example</h2>
<script>
// Function without parameters
function greet() {
[Link]("Welcome to JavaScript!<br>");
}
// Function with parameters
function add(a, b) {
[Link]("Sum: " + (a + b) + "<br>");
}
// Function with return
function square(num) {
return num * num;
}
// Global variable
let globalVar = "I am Global";
function testScope() {
// Local variable
let localVar = "I am Local";
[Link](globalVar + "<br>");
[Link](localVar + "<br>");
}
// Invocation
greet();
add(5, 10);
[Link]("Square: " + square(6) + "<br>");
testScope();
</script>

</body>
</html>
Output:
Welcome to JavaScript!
Sum: 15
Square: 36
I am Global
I am Local
Summary Table

Concept Description

Function Block of reusable code

Parameters Variables passed to a function

Invocation Calling a function to execute it

Return Statement Sends a value back to the caller

Global Variable Declared outside → used anywhere

Local Variable Declared inside function → limited scope

🌟 JavaScript Objects and Classes


✅ 1. Class (Definition)
• A class is a blueprint for creating objects.
• It defines properties (variables) and methods (functions) that objects will have.
• Introduced in ES6 (2015).

✅ 2. Class Syntax
class ClassName {
constructor(parameters) {
// Properties
}

method1() {
// Method code
}

method2() {
// Method code
}

}
✅ 3. Class Example
class Student {
// Constructor
constructor(name, age) {
[Link] = name; // property
[Link] = age;
}
// Method
displayInfo() {
return `Name: ${[Link]}, Age: ${[Link]}`;
}
}
// Creating objects from class
let s1 = new Student("Raksha", 22);
let s2 = new Student("Anu", 21);

[Link]([Link]());
[Link]([Link]());
👉 Output:
Name: Raksha, Age: 22
Name: Anu, Age: 21

4. Object (Definition)
• An object is a real instance created from a class (or directly).
• It represents a real-world entity with properties and methods.

5. Object Creation

a) Object Literal
let person = {
name: "Raksha",
age: 22,
greet: function() {
return "Hello, " + [Link];
}
};
[Link]([Link]());

Output: Hello, Raksha


b) Using new Object()
let car = new Object();
[Link] = "Toyota";
[Link] = "Innova";
[Link] = function() {
return "Car started";
};
[Link]([Link], [Link], [Link]());

Output: Toyota Innova Car started

c) From a Class
(Already shown in Student example).

6. Object Properties
• Properties are values inside an object.
let book = {
title: "JavaScript Basics",
pages: 200
};
[Link]([Link]); // Dot notation
[Link](book["pages"]); // Bracket notation

7. Built-in Objects in JavaScript


JavaScript provides many predefined (built-in) objects:
• Math → [Link](25) → 5
• Date → new Date() → Current date & time
• String → "Hello".toUpperCase() → HELLO
• Array → [1,2,3].length → 3
• JSON → [Link]({x:10}) → {"x":10}
✅ Full Example Program
<!DOCTYPE html>
<html>
<head>
<title>Objects and Classes</title>
</head>
<body>
<h2>JavaScript Objects and Classes Example</h2>
<script>
// Class with constructor and method
class Student {
constructor(name, course) {
[Link] = name;
[Link] = course;
}
display() {
return [Link] + " is studying " + [Link];
}
}
let s1 = new Student("Raksha", "Web Technologies");
let s2 = new Student("Anu", "JavaScript");
[Link]([Link]() + "<br>");
[Link]([Link]() + "<br>");
// Object literal
let teacher = {
name: "Shaili",
subject: "HTML",
teach: function() {
return [Link] + " teaches " + [Link];
}
};

[Link]([Link]() + "<br>");
// Built-in object
let today = new Date();
[Link]("Today's Date: " + [Link]());
</script>

</body>
</html>
Output:
Raksha is studying Web Technologies
Anu is studying JavaScript
Shaili teaches HTML
Today's Date: (current system date)
Quick Summary Table

Concept Example

Class Definition class Student { ... }

Constructor constructor(name) { [Link] = name; }

Class Method display() { return [Link]; }

Object Literal let obj = {name:"Ram"};

Object Property [Link] or obj["name"]

Built-in Objects Math, Date, Array, String, JSON

JavaScript Class Methods

✅ What are Class Methods?


• Methods are functions defined inside a class.
• They define the behavior (actions) of the objects created from that class.
• They are written without the function keyword inside a class.

Syntax
class ClassName {
constructor(param1, param2) {
this.param1 = param1;
this.param2 = param2;
}
// Method 1
method1() {
return this.param1;
}
// Method 2
method2() {
return this.param2;
}
}
Example 1: Simple Class with Methods
class Student {
constructor(name, age) {
[Link] = name;
[Link] = age;
}

// Method 1
getName() {
return [Link];
}

// Method 2
getDetails() {
return `Name: ${[Link]}, Age: ${[Link]}`;
}
}

// Creating object
let s1 = new Student("Raksha", 22);

[Link]([Link]()); // Output: Raksha


[Link]([Link]()); // Output: Name: Raksha, Age: 22

Example 2: Method to Update Property


class Car {
constructor(brand, model) {
[Link] = brand;
[Link] = model;
}

// Method to display car info


display() {
return `${[Link]} ${[Link]}`;
}

// Method to update model


updateModel(newModel) {
[Link] = newModel;
}
}

let myCar = new Car("Toyota", "Innova");


[Link]([Link]()); // Toyota Innova

[Link]("Fortuner");
[Link]([Link]()); // Toyota Fortuner

Example 3: Method with Calculation


class Calculator {
add(a, b) {
return a + b;
}

multiply(a, b) {
return a * b;
}
}

let calc = new Calculator();


[Link]([Link](10, 5)); // 15
[Link]([Link](4, 6)); // 24

Key Points
• A method is a function inside a class.
• Methods use this keyword to access properties.
• Objects created from the class can call these methods.

Quick Summary Table

Term Meaning

Method Function inside a class

Syntax methodName() { ... }

Access [Link]()

Uses this Refers to object properties


JavaScript Arrays

✅ 1. Definition of Array
• An array is a special variable that can store multiple values in a single variable.
• Each value is stored at a numeric index (starting from 0).

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

✅ 2. Creation of Array

a) Using Array Literal (Most common)


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

b) Using new Array() Constructor


let colors = new Array("Red", "Green", "Blue");

✅ 3. Types of Arrays

a) Single-Dimensional Array
• Stores values in one row.
let names = ["Raksha", "Anu", "Priya"];

b) Multi-Dimensional Array (Array of Arrays)


• Stores values in rows and columns (like a matrix).
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

Accessing: matrix[1][2] → 6
✅ 4. Accessing Array Elements
• Use index numbers (starting from 0).
let fruits = ["Apple", "Banana", "Mango"];

[Link](fruits[0]); // Apple
[Link](fruits[1]); // Banana
[Link](fruits[2]); // Mango

Changing values:
fruits[1] = "Orange";
[Link](fruits); // ["Apple", "Orange", "Mango"]

✅ 5. Array Properties
• length → returns the number of elements.
let fruits = ["Apple", "Banana", "Mango"];
[Link]([Link]); // 3

✅ 6. Common Array Methods

Adding / Removing
• push() → Add element at end
• pop() → Remove last element
• unshift() → Add element at beginning
• shift() → Remove first element
let fruits = ["Apple", "Banana"];
[Link]("Mango"); // ["Apple", "Banana", "Mango"]
[Link](); // ["Apple", "Banana"]

Searching
• indexOf("item") → returns index of element
• includes("item") → checks if element exists
[Link]([Link]("Banana")); // 1
[Link]([Link]("Apple")); // true
Combining / Slicing
• concat() → joins arrays
• slice(start, end) → extracts part of array
• splice(start, deleteCount, item1...) → removes/adds items
let arr = [1, 2, 3, 4, 5];
[Link]([Link](1, 3)); // [2, 3]
[Link](2, 1); // removes element at index 2
[Link](arr); // [1, 2, 4, 5]

Iteration
• forEach() → loop through elements
• map() → creates a new array after applying function
let nums = [1, 2, 3];
[Link](n => [Link](n * 2)); // 2, 4, 6

let squares = [Link](n => n * n);


[Link](squares); // [1, 4, 9]

✅ Full Example Program


<!DOCTYPE html>
<html>
<head>
<title>JavaScript Arrays</title>
</head>
<body>
<h2>JavaScript Arrays Example</h2>
<script>
let fruits = ["Apple", "Banana", "Mango"];

// Accessing
[Link]("First fruit: " + fruits[0] + "<br>");

// Changing
fruits[1] = "Orange";
[Link]("Changed Array: " + fruits + "<br>");
// Properties
[Link]("Length: " + [Link] + "<br>");

// Methods
[Link]("Grapes");
[Link]("After push: " + fruits + "<br>");

[Link]();
[Link]("After pop: " + fruits + "<br>");

[Link]("Includes Apple? " + [Link]("Apple") + "<br>");


</script>

</body>
</html>
👉 Output:
First fruit: Apple
Changed Array: Apple,Orange,Mango
Length: 3
After push: Apple,Orange,Mango,Grapes
After pop: Apple,Orange,Mango
Includes Apple? true
✅ Quick Summary Table

Feature Example

Create Array let arr = [1,2,3];

Access arr[0]

Length [Link]

Add End [Link](10)

Remove End [Link]()

Add Start [Link](0)

Remove Start [Link]()

Slice [Link](1,3)

Splice [Link](2,1)
JavaScript Array Properties
Array properties give information about arrays. Unlike methods, they do not perform
actions.

✅ 1. length
• Returns the number of elements in the array.
let fruits = ["Apple", "Banana", "Mango"];
[Link]([Link]); // 3

✅ 2. constructor
• Returns the function that created the array’s prototype.
let arr = [1, 2, 3];
[Link]([Link]);
// function Array() { [native code] }

✅ 3. prototype
• Allows you to add new properties or methods to all arrays.
[Link] = function() {
return this[0];
};
let numbers = [10, 20, 30];
[Link]([Link]()); // 10

✅ 4. [Link]() (Static Property/Method)


• Checks if a value is an array.
[Link]([Link]([1,2,3])); // true
[Link]([Link]("Hello")); // false
✅ 5. toString()
• Converts the array to a string (comma separated).
let colors = ["Red", "Green", "Blue"];
[Link]([Link]()); // "Red,Green,Blue"

✅ 6. valueOf()
• Returns the array itself.
let num = [1, 2, 3];
[Link]([Link]()); // [1, 2, 3]

✅ Example Program (All Properties)


<!DOCTYPE html>
<html>
<head>
<title>Array Properties</title>
</head>
<body>
<h2>JavaScript Array Properties</h2>
<script>
let fruits = ["Apple", "Banana", "Mango"];

// length
[Link]("Length: " + [Link] + "<br>");

// constructor
[Link]("Constructor: " + [Link] + "<br>");

// toString
[Link]("toString: " + [Link]() + "<br>");

// valueOf
[Link]("valueOf: " + [Link]() + "<br>");

// [Link]
[Link]("Is Array? " + [Link](fruits) + "<br>");
</script>
</body>
</html>
👉 Output:
Length: 3
Constructor: function Array() { [native code] }
toString: Apple,Banana,Mango
valueOf: Apple,Banana,Mango
Is Array? true

✅ Quick Summary Table

Property Description

length Number of elements in array

constructor Function that created the array

prototype Add new properties/methods to arrays

[Link] Checks if a value is array

toString() Converts array to string

valueOf() Returns the array itself


JavaScript Strings
1️⃣ Definition of String
• A string is a sequence of characters (letters, numbers, symbols) enclosed in
quotes.
• Strings are used to store and manipulate text in JavaScript.
Example:
let name = "Raksha";
let message = 'Welcome to JavaScript!';

2️⃣ Creation of Strings

a) Using String Literals


• The most common way to create strings.
let str1 = "Hello";
let str2 = 'World';

b) Using new String() Constructor


• Creates a String object, not a primitive string (not recommended for general
use).
let str3 = new String("Hello JavaScript");

3️⃣ Accessing String Elements


Strings behave like arrays of characters, where each character has an index (starting
from 0).
Example:
let word = "Hello";
[Link](word[0]); // H
[Link](word[1]); // e
[Link]([Link](2)); // l

You can use either index notation ([ ]) or the charAt() method.


4️⃣ Common String Properties

Property Description Example

length Returns number of characters "Raksha".length → 6

5️⃣ Common String Methods


Here are the most useful string methods with examples:

a) toUpperCase() and toLowerCase()


Convert letters to uppercase or lowercase.
let text = "Hello Raksha";
[Link]([Link]()); // HELLO RAKSHA
[Link]([Link]()); // hello raksha

b) concat()
Joins two or more strings.
let str1 = "Hello";
let str2 = "World";
[Link]([Link](" ", str2)); // Hello World

c) trim()
Removes extra spaces from start and end.
let str = " JavaScript ";
[Link]([Link]()); // "JavaScript"

d) slice(start, end)
Extracts a part of a string.
let text = "JavaScript";
[Link]([Link](0, 4)); // Java
e) substring(start, end)
Similar to slice() but doesn’t accept negative indexes.
let text = "Programming";
[Link]([Link](0, 7)); // Program

f) replace(search, replace)
Replaces part of a string.
let msg = "I love HTML";
[Link]([Link]("HTML", "JavaScript")); // I love JavaScript

g) split(separator)
Splits string into an array.
let fruits = "Apple,Banana,Mango";
[Link]([Link](",")); // ["Apple", "Banana", "Mango"]

h) indexOf() and lastIndexOf()


Finds position of a substring.
let text = "Learn JavaScript from JavaScript tutorial";
[Link]([Link]("JavaScript")); // 6
[Link]([Link]("JavaScript")); // 24

i) includes()
Checks if a string contains another string → returns true or false.
let str = "Welcome to JavaScript";
[Link]([Link]("Java")); // true
j) charCodeAt()
Returns the Unicode value of a character.
let text = "A";
[Link]([Link](0)); // 65

6️⃣ Example Program


<!DOCTYPE html>
<html>
<head>
<title>JavaScript Strings</title>
</head>
<body>
<h2>JavaScript String Example</h2>
<script>
let name = "Raksha";
[Link]("Name: " + name + "<br>");
[Link]("Length: " + [Link] + "<br>");
[Link]("Uppercase: " + [Link]() + "<br>");
[Link]("Character at 2: " + [Link](2) + "<br>");
[Link]("Slice (0,3): " + [Link](0,3) + "<br>");
[Link]("Includes 'sha'? " + [Link]("sha"));
</script>

</body>
</html>
Output:
Name: Raksha
Length: 6
Uppercase: RAKSHA
Character at 2: k
Slice (0,3): Rak
Includes 'sha'? true
7️⃣ Summary Table

Concept Example Description

String Literal "Hello" Basic string

Constructor new String("Hi") Object form

Access Element str[0] or [Link](0) Access characters

Length [Link] Number of characters

toUpperCase() "hi".toUpperCase() → "HI" Convert case

slice() "Hello".slice(0,2) → "He" Extract text

replace() "Hi".replace("Hi","Bye") Replace part

split() "a,b,c".split(",") Split string

includes() "Hello".includes("He") Check substring


JavaScript Events and Event Handling
1. What is an Event?

• An event is an action that happens in the browser.

• Events can be triggered by the user (click, key press, mouse move) or by the browser (page load, error,
resize).

• Example: clicking a button, typing in a textbox, moving the mouse, loading a page.

Event Handling means writing JavaScript code that reacts to these actions.

2. Handling Events from <body> Elements

• Events attached to the whole page.

Common <body> Events:

• onload → Runs when the page is fully loaded.

• onunload → Runs when user leaves the page.

• onresize → Runs when browser window is resized.

Example:

<body onload="alert('Welcome! Page loaded successfully.')">

<h2>Body Event Example</h2>

</body>

When the page loads, an alert message pops up.

3. Handling Events from Button Elements

• Buttons often use onclick to perform actions.

<button onclick="[Link]='lightgreen'">

Change Background

</button>

Use case: Submitting a form, opening a popup, changing content.

4. Handling Events from TextBox and Password Elements

Events:

• onfocus → when the input field gets focus (cursor inside).


• onblur → when focus is lost.
• onchange → when value changes and cursor leaves.
Example:

Name: <input type="text" onfocus="[Link]='yellow'"


onblur="[Link]='white'"><br>

Password: <input type="password" onchange="alert('Password changed!')">

Use case: Highlight active input, validate password/email.


5. Element Visibility

• We can show or hide elements using [Link].

<p id="msg">Hello Raksha!</p>

<button onclick="[Link]('msg').[Link]='none'">Hide</button>

<button onclick="[Link]('msg').[Link]='block'">Show</button>

6. Changing Colors and Fonts

• Using CSS properties via JavaScript ([Link], [Link]).

<p id="text">Change my style!</p>

<button onclick="[Link]('text').[Link]='blue'">Blue</button>

<button onclick="[Link]('text').[Link]='28px'">Big Font</button>

Use case: Highlight text, dark mode switch, styling on click.

7. Dynamic Content

• Change HTML content dynamically using .innerHTML.

<p id="demo">Old Content</p>

<button onclick="[Link]('demo').innerHTML='New Content Loaded!'">

Change Content

</button>

Use case: Updating product price, comments section, live scoreboard.

8. Slow Movement of Elements (Animation)

• Use setInterval() to move elements step by step.

<div id="box" style="width:50px; height:50px; background:red; position:absolute;"></div>

<script>
let pos = 0;
function moveBox() {
let box = [Link]("box");
let id = setInterval(frame, 20); // 20ms delay
function frame() {
if (pos == 300) {
clearInterval(id); // stop at 300px
} else {
pos++;
[Link] = pos + "px"; // move right
}
}
}
</script>

<button onclick="moveBox()">Move Box</button>

Use case: Animations, sliding menus, image sliders.


9. Navigator Object

• The navigator object gives information about the browser.

Example:

<script>

[Link]("Browser Name: " + [Link] + "<br>");

[Link]("Browser Version: " + [Link] + "<br>");

[Link]("Platform: " + [Link] + "<br>");

[Link]("Language: " + [Link] + "<br>");

</script>

Use case: Detect browser type (for compatibility), detect OS.


Basics of Pattern Matching using Regular Expressions (RegExp)

What is a Regular Expression (RegExp)?


• A Regular Expression (RegExp) is a pattern used to search, match, or validate
strings (text).
• It helps to check whether a string follows a specific format, like:
o Email address
o Mobile number
o Password
o Postal code, etc.

Example:
let pattern = /abc/;
This means we are searching for the pattern "abc" inside a string.
Using Special Symbols (Meta Characters)

Symbol Meaning Example Matches

^ Starts with /^J/ "Java"

$ Ends with /t$/ "JavaScript"

. Any single character /h.t/ "hat", "hot"

* 0 or more characters /lo*/ "lo", "loo"

+ 1 or more characters /go+/ "go", "goo"

"color", "colour"
? Optional character /colou?r/

[] Character set /[aeiou]/ Any vowel

{} Quantity /[0-9]{3}/ 3 digits

\d Digit (0–9) /\d\d/ Two digits

\w Word character (a-z, A-Z, 0-9, _) /\w+/ Words


Testing a Pattern with .test()
The .test() method checks if the pattern exists in a string.
It returns:
• true → if pattern is found
• false → if pattern is not found
Example:
let pattern = /java/;
let text = "I love JavaScript";

[Link]([Link](text)); // true

Common RegExp Use Cases in JavaScript

Use Case Example Pattern Description

/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-
Email Validate email format
z]{2,}$/

Mobile
/^[0-9]{10}$/ Only 10 digits
Number

At least 8 chars, one uppercase, one


Password /^(?=.*[A-Z])(?=.*[0-9]).{8,}$/
digit

Postal Code /^[0-9]{6}$/ 6 digits only

Only Letters /^[A-Za-z]+$/ No numbers or symbols

You might also like