JavaScript NOTES
JavaScript NOTES
✅ 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).
Basic Structure
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Syntax Example</title>
<script>
// This is a JavaScript statement
alert('Hello, Raksha!');
</script>
</head>
<body>
</body>
</html>
✅ Characteristics of JavaScript
Lightweight
Interpreted Language
Platform Independent
• Works across all platforms and browsers (Windows, Mac, Linux, Android).
Write once, run everywhere.
Event-Driven
Object-Oriented
Characteristic Meaning
✅ Advantages of JavaScript
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.
Rich Ecosystem
• Large community + plenty of libraries (e.g., jQuery, React, Angular).
Makes development faster and easier.
Summary Table
Advantage Description
Works with HTML & CSS Controls content & style easily
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
Examples
let myName = "Raksha";
let $price = 100;
let _count = 5;
Examples
</body>
</html>
👉 Output:
Name: Raksha
Age: 22
Country: India
✅ 5. Summary Table
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;
</body>
</html>
👉 Output:
Name: Raksha
Age: 22
Quick Summary
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.
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
String "Hello"
Undefined let x;
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.
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!”
Output:
When user types a name and clicks Submit → it displays “Hello, [name]!”
Output:
Shows alert when any key is pressed inside the textbox.
✅ 3. Summary Table
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.
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 5 2
% Modulus (remainder) 10 % 3 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.
= 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
✅ Logical Operators
Used to combine multiple conditions.
` ` OR
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.
` ` OR `5
^ XOR 5^1 4
~ NOT ~5 -6
✅ String Operator
• The + operator can also join (concatenate) strings.
let firstName = "Ram";
let lastName = "Priya";
[Link](firstName + " " + lastName); // Ram Priya
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
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");
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
Number("5") + 2 Explicit 7
</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
Type Purpose
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");
}
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
// 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
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: 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
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();
</body>
</html>
Output:
Welcome to JavaScript!
Sum: 15
Square: 36
I am Global
I am Local
Summary Table
Concept Description
✅ 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]());
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
[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
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]("Fortuner");
[Link]([Link]()); // Toyota Fortuner
multiply(a, b) {
return a * b;
}
}
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.
Term Meaning
Access [Link]()
✅ 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
✅ 3. Types of Arrays
a) Single-Dimensional Array
• Stores values in one row.
let names = ["Raksha", "Anu", "Priya"];
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
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
// 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>");
</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
Access arr[0]
Length [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
✅ 6. valueOf()
• Returns the array itself.
let num = [1, 2, 3];
[Link]([Link]()); // [1, 2, 3]
// 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
Property Description
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"]
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
</body>
</html>
Output:
Name: Raksha
Length: 6
Uppercase: RAKSHA
Character at 2: k
Slice (0,3): Rak
Includes 'sha'? true
7️⃣ Summary Table
• 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.
Example:
</body>
<button onclick="[Link]='lightgreen'">
Change Background
</button>
Events:
<button onclick="[Link]('msg').[Link]='none'">Hide</button>
<button onclick="[Link]('msg').[Link]='block'">Show</button>
<button onclick="[Link]('text').[Link]='blue'">Blue</button>
7. Dynamic Content
Change Content
</button>
<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>
Example:
<script>
</script>
Example:
let pattern = /abc/;
This means we are searching for the pattern "abc" inside a string.
Using Special Symbols (Meta Characters)
"color", "colour"
? Optional character /colou?r/
[Link]([Link](text)); // true
/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-
Email Validate email format
z]{2,}$/
Mobile
/^[0-9]{10}$/ Only 10 digits
Number