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

JavaScript

JavaScript is a versatile programming language primarily used for creating interactive and dynamic websites, functioning on both the frontend and backend. It includes fundamental concepts such as variables, data types, operators, control flow, functions, and objects, which are essential for effective programming. The document provides a comprehensive overview of these concepts, including examples and best practices for using JavaScript.

Uploaded by

bjakash22
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views56 pages

JavaScript

JavaScript is a versatile programming language primarily used for creating interactive and dynamic websites, functioning on both the frontend and backend. It includes fundamental concepts such as variables, data types, operators, control flow, functions, and objects, which are essential for effective programming. The document provides a comprehensive overview of these concepts, including examples and best practices for using JavaScript.

Uploaded by

bjakash22
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JavaScript

🧠 1. Basics (Foundation)
📘 1.1 JavaScript Introduction (What, Why Use, Where Use)

Definition:
👉 JavaScript is a programming language used to make websites interactive and dynamic.
It works mainly in browsers (frontend) but can also run on servers (backend) using
[Link].
🧩 In simple words:
JavaScript is a programming language that helps make websites lively and interactive — for
example, when you click, animations appear or data updates dynamically.

💡 Why Use JavaScript?

Reason Explanation

🎨 Interactive Websites Buttons, sliders, pop-ups, forms — all can work dynamically

You can control how your webpage behaves (e.g., if the user
⚙️Logic Handling
clicks, show a message)

🌍 Everywhere Supported All browsers support JS

💻 Backend Too With [Link], JS can handle servers and databases

📱 App & Game


Used in React Native, [Link], etc.
Development

Where to Use JavaScript

Area Example

Frontend (Client-side) HTML + CSS + JS = Interactive website

Backend (Server-side) [Link] apps (API, database connection)

Mobile Apps React Native

Game Development [Link]

Machine Learning [Link]

⚡ Example: Basic JavaScript Program


<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<h2>Welcome to JavaScript</h2>
<button onclick="greet()">Click Me</button>

<script>
function greet() {
alert("Hello, welcome to JavaScript!");
}
</script>
</body>
</html>
🗣 Output:
When you click the button → a popup appears saying “Hello, welcome to JavaScript!”

🧾 1.2 Variables (var, let, const)

Definition:
Variables are containers used to store data values in JavaScript.
Syntax:
var name = "Suba";
let age = 21;
const country = "India";

📘 Types of Variables
Reassign
Keyword Scope Hoisting Description
Allowed?

var Function scoped ✅ Yes ✅ Yes Old method, avoid using now

Modern, best for reassignable


let Block scoped ✅ Yes ❌ No
values

const Block scoped ❌ No ❌ No Best for fixed values

💡 Example:

var name = "Suba";


let age = 21;
const city = "Madurai";

[Link](name); // Suba
[Link](age); // 21
[Link](city); // Madurai

age = 22; // ✅ allowed

// city = "Chennai"; ❌ Error: cannot reassign const

🗣 Explanation:

 var is the old keyword — scope control is limited.


 Using let and const makes the code safer.
 const = fixed value (cannot be changed).

1️⃣ Data Types in JavaScript

JavaScript has primitive and non-primitive data types.


A. Primitive Data Types
These store single values and are immutable.

Data Type Description Example

String Text enclosed in quotes ("", '', ````) "Hello"


Data Type Description Example

Number Integer or floating-point numbers 10, 3.14

Boolean Represents true or false true, false

Null Represents no value, explicitly assigned let x = null

let y; [Link](y) →
Undefined Variable declared but not assigned a value
undefined

Symbol Unique identifier (rarely used) Symbol("id")

Represents numbers larger than


BigInt 9007199254740991n
Number.MAX_SAFE_INTEGER

B. Non-Primitive Data Types


 Object: Collection of key-value pairs.
let person = {name: "Suba", age: 21};
 Array: Ordered list of items (can mix types).
let numbers = [1, 2, 3, 4];
let mixed = ["Suba", 21, true];

2️⃣ Operators in JavaScript

Operators are symbols that perform operations on values.


A. Arithmetic Operators

Operator Description Example

+ Addition / String concatenation 5 + 2 = 7, "Hi " + "Suba" = "Hi Suba"

- Subtraction 5-2=3

* Multiplication 3*2=6

/ Division 10 / 2 = 5

% Modulus (remainder) 10 % 3 = 1

** Exponentiation 2 ** 3 = 8

B. Comparison Operators
Return a Boolean (true/false).
Operator Description Example

== Equal (only value, type ignored) 5 == "5" → true

=== Strict equal (value + type) 5 === "5" → false

!= Not equal 5 != "5" → false

!== Strict not equal 5 !== "5" → true

> Greater than 5 > 3 → true

< Less than 3 < 5 → true

>= Greater than or equal 5 >= 5 → true

<= Less than or equal 3 <= 5 → true

C. Logical Operators
Used for true/false logic.

Operator Description Example

&& AND true && false → false

` `

! NOT !true → false

D. Assignment Operators
Assign or update values.

Operator Description Example

= Assign x=5

+= Add and assign x += 3 → x = x + 3

-= Subtract and assign x -= 2 → x = x - 2

*= Multiply and assign x *= 2 → x = x * 2

/= Divide and assign x /= 2 → x = x / 2

%= Modulus and assign x %= 3 → x = x % 3

3️⃣ Type Conversion in JavaScript


JavaScript sometimes automatically converts types (coercion) or you can convert
manually.
A. Implicit Conversion
JavaScript converts types automatically.
let result = "5" + 3; // "53" → number 3 becomes string
let num = "10" * 2; // 20 → string "10" becomes number
let boolCheck = "hello" - 1; // NaN → invalid operation
 + with string → converts other to string
 -, *, / → converts to number

B. Explicit Conversion
You manually convert types using functions.
// String → Number
let num = Number("123"); // 123
let num2 = parseInt("123.45"); // 123
let num3 = parseFloat("123.45"); // 123.45

// Number → String
let str = String(123); // "123"
let str2 = (123).toString(); // "123"

// Boolean Conversion
Boolean(0); // false
Boolean(1); // true
Boolean(""); // false
Boolean("Hi");// true
Tip: Always check for NaN when converting strings to numbers.

✅ Summary Table for Quick Reference


Concept Example Result

String "Suba" "Suba"

Number 10 10

Boolean true true

Null null null

Undefined let a; undefined

Object {name:"Suba"} Object

Array [1,2,3] Array

Addition 5+2 7

Concatenation "Hi"+" Suba" "Hi Suba"

Equality 5=="5" true

Strict Equality 5==="5" false

Implicit Conversion "5"+3 "53"

Explicit Conversion Number("5") 5

Conditional Statements
Conditional statements allow JavaScript to make decisions based on conditions.
A. if Statement
Executes a block of code if the condition is true.
let age = 18;

if (age >= 18) {


[Link]("You are an adult");
}
 Output: "You are an adult"
 Here, the code inside {} runs only if age >= 18.

B. if...else Statement
Executes one block if the condition is true, another block if false.
let age = 15;

if (age >= 18) {


[Link]("You are an adult");
} else {
[Link]("You are a minor");
}
 Output: "You are a minor"

C. if...else if...else
For multiple conditions.
let marks = 75;

if (marks >= 90) {


[Link]("Grade A");
} else if (marks >= 75) {
[Link]("Grade B");
} else if (marks >= 50) {
[Link]("Grade C");
} else {
[Link]("Fail");
}
 Output: "Grade B"

D. switch Statement
Useful when comparing one value with many options.
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"
 break stops execution after a match.
 default runs if no case matches.

2️⃣ Loops in JavaScript

Loops are used to repeat code multiple times.

A. for Loop
Runs a fixed number of times.
for (let i = 1; i <= 5; i++) {
[Link]("Hello", i);
}
 Output:
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
 i++ means i = i + 1.

B. while Loop
Runs as long as the condition is true.
let i = 1;
while (i <= 5) {
[Link]("Hi", i);
i++;
}
 Output is same as for loop.
 Be careful: If condition never becomes false → infinite loop.

C. do...while Loop
Runs at least once, then checks the condition.
let i = 1;
do {
[Link]("Hey", i);
i++;
} while (i <= 5);
 Output:
Hey 1
Hey 2
Hey 3
Hey 4
Hey 5

3️⃣ for...in and for...of Loops


These are special loops for objects and arrays.
A. for...in
Loops through object keys or array indices.
let person = {name: "Suba", age: 21};

for (let key in person) {


[Link](key, person[key]);
}
 Output:
name Suba
age 21
let arr = [10, 20, 30];
for (let index in arr) {
[Link](index, arr[index]);
}
 Output:
0 10
1 20
2 30
Note: for...in gives keys or indices, not values directly.

B. for...of
Loops through values of an array or iterable.
let arr = [10, 20, 30];
for (let value of arr) {
[Link](value);
}
 Output:
10
20
30
 Can also use with strings:
let name = "Suba";
for (let char of name) {
[Link](char);
}
 Output:
S
u
b
a
Key difference:
 for...in → keys/indexes
 for...of → values

✅ Summary Table

Control Flow Example Description

Runs if
if if(x>5){} condition
true

if...else if(x>5){} else {} Two choices

if(){} else if(){} Multiple


if...else if
else{} choices

Compare one
switch(x){case1:
switch value against
...}
many

Repeat fixed
for for(i=0;i<5;i++)
times

Repeat while
while while(x<5)
true
Control Flow Example Description

Runs at least
do...while do{} while(x<5)
once

Loop
for...in for(key in obj)
keys/index

for...of for(value of arr) Loop values

What is a Function?
A function is a block of reusable code that performs a
specific task.
Instead of writing the same code again and again, you can
call a function whenever needed.
function greet() {
[Link]("Hello Suba!");
}

greet(); // Function call


 Definition: function greet(){...}
 Call: greet();
 Output: Hello Suba!

2️⃣ Parameters & Return

A. Parameters
Functions can take inputs called parameters (or arguments).
function greet(name) {
[Link]("Hello " + name + "!");
}

greet("Suba"); // Hello Suba!


greet("Vidya"); // Hello Vidya!
Control Flow Example Description

 name is a parameter, "Suba" is the argument.

B. Return Statement
Functions can return a value using return.
function add(a, b) {
return a + b;
}

let result = add(5, 3);


[Link](result); // 8
 return allows storing or using the result outside the
function.

3️⃣ Function Expressions

You can assign a function to a variable. This is called a


function expression.
const greet = function(name) {
[Link]("Hello " + name);
};

greet("Suba"); // Hello Suba


 Key difference from normal function:
o Normal functions can be called before
definition (hoisting).
o Function expressions cannot be called before
they are defined.

4️⃣ Arrow Functions (ES6)

Arrow functions are a shorter syntax for writing functions.


Control Flow Example Description

const add = (a, b) => {


return a + b;
};

[Link](add(5, 3)); // 8
 If the function has only one statement, you can
skip {} and return:
const multiply = (a, b) => a * b;
[Link](multiply(4, 2)); // 8
 No this binding in arrow functions → behaves
differently in objects (advanced topic).

5️⃣ Callback Functions

A callback function is a function passed as an argument to


another function.
It’s called later inside that function.
function greet(name) {
[Link]("Hello " + name);
}

function processUser(name, callback) {


[Link]("Processing user...");
callback(name); // Call the passed function
}

processUser("Suba", greet);
 Output:
Processing user...
Hello Suba
Control Flow Example Description

 Callback functions are commonly used for


asynchronous operations like API requests, timers,
or events.

6️⃣ Summary Table

Function Type Syntax Example Notes

Can be called
Normal Function function greet(){}
before definition

Function with Input values are


function greet(name){}
Parameters parameters

Function with function add(a,b)


Returns a value
Return {return a+b;}

Function const greet = function()


Cannot be hoisted
Expression {}

const add = Short syntax, no


Arrow Function
(a,b)=>a+b; this

Passed as
Callback processUser(name,
argument, called
Function callback)
later

💡 Quick Tip:

 Use normal functions for simple reusable blocks.


 Use arrow functions for short, inline operations.
 Use callback functions for asynchronous tasks or
when you want to execute a function after another
function.
Objects in JavaScript
An object is a collection of key-value pairs.
Keys are called properties, and values can be data or
functions (methods).
A. Creating an Object
Control Flow Example Description

let person = {
name: "Suba",
age: 21,
greet: function() {
[Link]("Hello, " + [Link]);
}
};
 Properties: name, age
 Method: greet()
[Link]([Link]); // Suba
[Link](); // Hello, Suba
this refers to the current object.

B. Modifying Objects
[Link] = 22; // Update property
[Link] = "Madurai"; // Add new property
delete [Link]; // Delete property

C. Nested Objects
Objects can have objects inside them.
let student = {
name: "Vidya",
marks: { math: 90, science: 85 }
};

[Link]([Link]); // 90

2️⃣ Arrays in JavaScript


Control Flow Example Description

An array is an ordered collection of items. Items can be of


any type.
let numbers = [1, 2, 3, 4];
let mixed = ["Suba", 21, true];

A. Common Array Methods


1. push() → Add element to end
[Link](5);
[Link](numbers); // [1,2,3,4,5]
2. pop() → Remove last element
[Link]();
[Link](numbers); // [1,2,3,4]
3. map() → Returns a new array by transforming each
element
let doubled = [Link](num => num * 2);
[Link](doubled); // [2,4,6,8]
4. filter() → Returns a new array with elements that meet
condition
let even = [Link](num => num % 2 === 0);
[Link](even); // [2,4]
5. reduce() → Reduces array to a single value
let sum = [Link]((acc, curr) => acc + curr, 0);
[Link](sum); // 10
 acc → accumulator, curr → current element
 0 → initial value of accumulator
6. forEach() → Executes a function for each element (does
not return a new array)
[Link](num => [Link](num * 2));
// 2 4 6 8
Control Flow Example Description

B. Nested Arrays
Arrays can contain arrays or objects.
let nestedArr = [[1,2],[3,4]];
[Link](nestedArr[0][1]); // 2

let users = [
{name: "Suba", age: 21},
{name: "Vidya", age: 22}
];
[Link](users[1].name); // Vidya

3️⃣ Spread & Rest Operators

Both use ... but serve different purposes.


A. Spread Operator
Used to expand arrays or objects.
let arr1 = [1,2];
let arr2 = [3,4];

let combined = [...arr1, ...arr2];


[Link](combined); // [1,2,3,4]

let person1 = {name: "Suba", age: 21};


let person2 = {...person1, city: "Madurai"};
[Link](person2); // {name:"Suba", age:21,
city:"Madurai"}

B. Rest Operator
Control Flow Example Description

Used to collect remaining elements into an array or object.


function sum(...numbers) {
return [Link]((acc, curr) => acc + curr, 0);
}
[Link](sum(1,2,3,4)); // 10
 Can also be used in destructuring:
let [first, ...rest] = [1,2,3,4];
[Link](first); // 1
[Link](rest); // [2,3,4]

4️⃣ Summary Table

Concept Example Description

Key-value
Object {name:"Suba", age:21}
collection

Object Function
greet:function(){}
Method inside object

Object inside
Nested Object {marks:{math:90}}
object

Array [1,2,3] Ordered list

push() [Link](4) Add at end

pop() [Link]() Remove last

Transform
map() [Link](x=>x*2) array, returns
new

Filter
filter() [Link](x=>x>2) elements,
returns new

Reduce to
reduce() [Link]((a,c)=>a+c,0)
single value

forEach() [Link](x=>[Link](x)) Loop, no


Control Flow Example Description

Concept Example Description

return

Nested Multi-level
arr=[{name:"Suba"}]
Array/Object data

Expand
Spread ... [...arr1, ...arr2]
array/object

Collect
Rest ... function sum(...nums) remaining
values

💡 Quick Tip:

 Use spread for copying or combining arrays/objects.


 Use rest for variable function arguments or
destructuring remaining elements.

String Methods in JavaScript


A string is a sequence of characters, and JavaScript provides many built-in methods to work
with strings.

A. Common String Methods

Method Definition Example Output

Returns the number of


length "Suba".length 4
characters in a string

Converts string to
toUpperCase() "hello".toUpperCase() "HELLO"
uppercase

Converts string to
toLowerCase() "HELLO".toLowerCase() "hello"
lowercase

Returns character at
charAt(index) "Suba".charAt(1) "u"
specified index

Returns the first index


indexOf(search) "Suba".indexOf("b") 2
of the search value
Method Definition Example Output

Returns the last index


lastIndexOf(search) "banana".lastIndexOf("a") 5
of the search value

Extracts part of string


slice(start, end) "Subalakshmi".slice(0,4) "Suba"
from start to end-1

substring(start, end) Similar to slice "Subalakshmi".substring(0,4) "Suba"

Replaces first "Hello "Hello


replace(old, new)
occurrence of substring Suba".replace("Suba","Vidya") Vidya"

Checks if string
includes(value) "Hello".includes("lo") true
contains value

Removes whitespace
trim() " Hello ".trim() "Hello"
from both ends

Splits string into array


split(separator) "a,b,c".split(",") ["a","b","c"]
using separator

repeat(n) Repeats string n times "Hi".repeat(3) "HiHiHi"

B. Example Usage
let text = " Hello Suba ";

[Link]([Link]); // 13
[Link]([Link]()); // " HELLO SUBA "
[Link]([Link]()); // "Hello Suba"
[Link]([Link]("Suba"));// true
[Link]([Link]("Suba","Vidya")); // " Hello Vidya "
[Link]([Link](" ")); // ["", "", "Hello", "Suba", "", ""]

2️⃣ Math Methods in JavaScript

The Math object provides mathematical constants and functions. You do not create a
Math object, just call its methods.

A. Common Math Methods


Method Definition Example Output

Rounds x to nearest
[Link](x) [Link](4.6) 5
integer

Rounds x up to
[Link](x) [Link](4.1) 5
nearest integer

Rounds x down to
[Link](x) [Link](4.9) 4
nearest integer

Removes decimal
[Link](x) [Link](4.9) 4
part

Returns x to the
[Link](x,y) [Link](2,3) 8
power of y

[Link](x) Returns square root [Link](16) 4

Returns absolute
[Link](x) [Link](-5) 5
value

Returns smallest
[Link](a,b,...) [Link](1,5,3) 1
number

Returns largest
[Link](a,b,...) [Link](1,5,3) 5
number

Returns random
[Link]() number between 0 [Link]() 0.123…
and 1

Random integer
[Link]([Link]()*10) [Link]([Link]()*10) e.g., 7
between 0-9

B. Example Usage
let num = 4.7;

[Link]([Link](num)); // 5
[Link]([Link](num)); // 5
[Link]([Link](num)); // 4
[Link]([Link](num)); // 4
[Link]([Link](16)); // 4
[Link]([Link](2,3)); // 8
[Link]([Link](-10)); // 10

// Random number between 1 and 100


let randomNum = [Link]([Link]() * 100) + 1;
[Link](randomNum);

✅ Summary

 String methods: manipulate text (uppercase, slice, split, replace, etc.)


 Math methods: perform calculations (round, ceil, floor, random, sqrt, etc.)

💡 Quick Tip:

 Use string methods for text formatting, searching, splitting, etc.


 Use Math methods for calculations, rounding, generating random numbers.
What is DOM?
 DOM (Document Object Model) is a tree-like structure that represents your
HTML page.
 Using JavaScript, you can access and manipulate HTML elements and their styles.
Think of the DOM as a bridge between HTML and JS.

2️⃣ Selecting Elements

A. getElementById
 Selects one element by its id.
 Returns a single element object.
let heading = [Link]("title");
[Link]([Link]); // Access text
 Example in HTML:
<h1 id="title">Hello</h1>
B. getElementsByClassName
 Selects all elements with the given class.
 Returns an HTMLCollection (like an array but not exactly).
let items = [Link]("item");
[Link](items[0].innerText); // Access first element
 Example in HTML:
<p class="item">Item 1</p>
<p class="item">Item 2</p>

C. querySelector & querySelectorAll


 querySelector → selects first element that matches a CSS selector
 querySelectorAll → selects all matching elements (returns NodeList)
let firstItem = [Link](".item"); // First .item
let allItems = [Link](".item"); // All .item elements

3️⃣ Changing HTML & CSS with JS

A. Change HTML content


let heading = [Link]("title");
[Link] = "Hello World"; // Changes text
[Link] = "<em>Hello</em>"; // Can add HTML tags
B. Change CSS styles
[Link] = "red";
[Link] = "30px";

4️⃣ Event Handling

JavaScript can respond to user actions like clicks, typing, hover, etc.
A. Using HTML attribute (onclick)
<button onclick="sayHello()">Click Me</button>
<script>
function sayHello() {
alert("Hello Suba!");
}
</script>
B. Using addEventListener (Recommended)
let btn = [Link]("button");

[Link]("click", function() {
alert("Button clicked!");
});
 Advantages:
o Can attach multiple events

o Keeps HTML clean

5️⃣ Creating & Removing Elements

A. Creating an element
let newPara = [Link]("p"); // Create <p> element
[Link] = "I am new!";
[Link](newPara); // Add to page
B. Removing an element
let oldPara = [Link]("old");
[Link](); // Removes element from DOM
C. Modifying element dynamically
let list = [Link]("ul");
let newItem = [Link]("li");
[Link] = "New Item";
[Link](newItem); // Add new <li> to <ul>
6️⃣ Summary Table

Conce
Method/Property Example Notes
pt

Select Returns single


getElementById("id") [Link]("title")
by id element

Returns
Select getElementsByClassName("cl [Link](
HTMLCollecti
by class ass") "item")
on

CSS
Selecto querySelector(".class") [Link](".item") First match
r

CSS
NodeList of all
Selecto querySelectorAll(".class") [Link](".item")
matches
r All

Change
innerText [Link] = "Hi" Only text
text

Change [Link] = Can add


innerHTML
HTML "<em>Hi</em>" HTML

Change
[Link] [Link] = "red" Inline CSS
style

Event Simple, but not


onclick <button onclick="func()">
inline clean

Event addEventListener("click", Can attach


Recommended
JS func) multiple events

Create [Link]("tag Create


<p>
element ") dynamically

Add
appendChild [Link](child) Add to DOM
element

Remov
Delete from
e remove() [Link]()
DOM
element

💡 Quick Tips:

1. querySelector is more flexible than getElementById or getElementsByClassName.


2. Always use addEventListener for better maintainability.
3. Creating/removing elements dynamically is essential for interactive web pages.
Scope in JavaScript
Scope determines where a variable is accessible.
A. Global Scope
 Variables declared outside any function or block.
 Accessible anywhere in your code.
let globalVar = "I am global";

function test() {
[Link](globalVar); // Accessible
}
test();
[Link](globalVar); // Accessible

B. Function Scope
 Variables declared inside a function are local to that function.
 Cannot be accessed outside the function.
function myFunc() {
let localVar = "I am local";
[Link](localVar); // Accessible
}
myFunc();
[Link](localVar); // Error: localVar is not defined

C. Block Scope
 Variables declared with let or const inside { } are block-scoped.
 var is not block scoped (function-scoped).
if(true){
let blockVar = "I am block scoped";
var funcVar = "I am function scoped";
}

[Link](blockVar); // Error
[Link](funcVar); // Accessible

2️⃣ Hoisting

Hoisting moves variable and function declarations to the top of their scope before
execution.
A. Functions are hoisted
greet(); // Works

function greet(){
[Link]("Hello");
}
B. Variables
 var is hoisted but undefined initially
 let and const are hoisted but cannot be accessed before declaration (TDZ -
Temporal Dead Zone)
[Link](x); // undefined
var x = 5;

[Link](y); // Error
let y = 10;

3️⃣ Closures

A closure is a function that remembers variables from its outer scope, even after the outer
function has finished.
function outer() {
let count = 0;
return function inner() {
count++;
[Link](count);
}
}

let counter = outer();


counter(); // 1
counter(); // 2
counter(); // 3
 Use cases: data privacy, maintaining state, callbacks.

4️⃣ this Keyword

this refers to the context object in which a function is called.

Context this refers to

Global (non-strict) window (browser)

Function (normal) window (browser)

Method in object The object

Constructor The newly created object

Arrow function Lexical this (from outer scope)

Examples
// Object method
let obj = {
name: "Suba",
greet: function() {
[Link]([Link]);
}
};
[Link](); // Suba

// Arrow function
let arrow = () => [Link](this);
arrow(); // Window (or outer scope)

5️⃣ Prototype & Inheritance

A. Prototype
 Every JavaScript object has a prototype.
 You can add methods/properties to it for reuse.
function Person(name){
[Link] = name;
}

[Link] = function(){
[Link]("Hello " + [Link]);
}

let p1 = new Person("Suba");


[Link](); // Hello Suba
 Prototype allows all instances to share methods, saving memory.

B. Inheritance (Prototype-based)
 Objects can inherit properties/methods from other objects.
function Animal(name){
[Link] = name;
}

[Link] = function(){
[Link]([Link] + " makes a sound");
}

function Dog(name){
[Link](this, name); // Inherit properties
}

[Link] = [Link]([Link]); // Inherit methods


[Link] = Dog;

let d = new Dog("Tommy");


[Link](); // Tommy makes a sound
 Key steps:
1. Use call() to inherit properties
2. Use [Link]() to inherit methods
3. Reset constructor

6️⃣ Summary Table

Concept Definition Example

Determines where variables are


Scope Global, Function, Block
accessible

Hoisting Moves declarations to top of scope var x; function greet(){}

Closure Function remembers outer variables function outer(){ return function inner(){}}

this Refers to calling context [Link]() → obj

Prototype Shared methods/properties of objects [Link]

Object derives properties/methods [Link] =


Inheritance
from another [Link]([Link])

💡 Quick Tips:
1. Use closures for private variables.
2. Always understand what this refers to, especially with arrow functions.
3. Use prototype to save memory when creating multiple objects.
4. Inheritance in JS is prototype-based, not class-based (though ES6 classes make it
look like classes).
What is Asynchronous JavaScript?
 Normally, JavaScript executes line by line (synchronously).
 Asynchronous JS allows code to run without blocking the rest of the program.
 Useful for timers, API calls, or heavy tasks.

2️⃣ Callback Functions

 A callback function is a function passed as an argument and executed later.


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

function processUser(name, callback) {


[Link]("Processing user...");
callback(name);
}

processUser("Suba", greet);
Output:
Processing user...
Hello Suba
 Real-time analogy: You order food, and the chef calls you (callback) when it’s ready.

3️⃣ setTimeout & setInterval


A. setTimeout
 Executes a function after a specified delay (ms).
setTimeout(() => {
[Link]("Hello after 2 seconds");
}, 2000);
 Output: "Hello after 2 seconds" (after 2 seconds)
B. setInterval
 Repeats a function at a specified interval (ms).
let count = 0;
let interval = setInterval(() => {
count++;
[Link]("Count: " + count);
if(count === 5) clearInterval(interval); // Stop after 5 times
}, 1000);
 Output every 1 second:
Count: 1
Count: 2
...
Count: 5

4️⃣ Callback Hell

 Occurs when multiple nested callbacks are used.


 Makes code hard to read and maintain.
loginUser(user, function(err, user) {
if(user){
getUserDetails([Link], function(err, details){
getPosts([Link], function(err, posts){
[Link](posts);
});
});
}
});
 Solution: Use Promises or Async/Await.

5️⃣ Promises

 A Promise represents a future value:


o Pending → Not resolved yet

o Fulfilled → Success

o Rejected → Error

Example:
let promise = new Promise((resolve, reject) => {
let success = true;
setTimeout(() => {
if(success) resolve("Task completed");
else reject("Task failed");
}, 2000);
});

promise
.then(result => [Link](result)) // Success
.catch(error => [Link](error)); // Error
Output (after 2 sec):
Task completed
 Real-time analogy: Promise is like ordering a package online. It will either arrive
(resolve) or fail (reject).

6️⃣ Async / Await

 Syntactic sugar over Promises.


 Makes asynchronous code look synchronous.
Example:
function wait(ms){
return new Promise(resolve => setTimeout(resolve, ms));
}

async function greet() {


[Link]("Start");
await wait(2000);
[Link]("Hello after 2 seconds");
}

greet();
 Output:
Start
Hello after 2 seconds
 Use: Simplifies chaining multiple async tasks without callback hell.

7️⃣ Fetch API (API Call)

 Fetch is used to call APIs and get data asynchronously.


 Returns a Promise.
Example (Real-time)
// Fetch data from public API
fetch("[Link]
.then(response => [Link]()) // Parse JSON
.then(data => [Link](data)) // Handle data
.catch(error => [Link](error));
 Using Async/Await:
async function getPost() {
try {
let response = await fetch("[Link]
let data = await [Link]();
[Link](data);
} catch(error) {
[Link](error);
}
}

getPost();
 Real-time analogy: You ask a server for info → server responds → you handle data
when it arrives.

8️⃣ Summary Table

Concept Definition Example / Notes

Callback Function passed as argument, executed later processUser("Suba", greet)

setTimeout Run function after delay setTimeout(fn, 2000)

setInterval Run function repeatedly setInterval(fn, 1000)

Callback Hell Nested callbacks making code unreadable Multiple nested API calls

Represents future value (pending, fulfilled,


Promise new Promise((res,rej)=>{})
rejected)

then / catch Handle resolved/rejected promises .then(res).catch(err)

Async/Await Syntactic sugar over promises await fetch(url)

Fetch API Make API calls asynchronously fetch("url").then(res=>[Link]())

💡 Tips for Real-Time JS

1. Use Promises or Async/Await for cleaner code.


2. Avoid callback hell by not nesting multiple callbacks.
3. Use fetch + async/await for API calls for modern JS apps.
4. Combine setTimeout or setInterval with Promises for timed async tasks.
What is Error Handling?
 Error Handling is a mechanism to catch and manage errors in your code so your
program doesn’t crash unexpectedly.
 Helps improve user experience and debugging.
Why we use it:
1. Prevents program crashes.
2. Helps provide informative error messages.
3. Makes code more robust and maintainable.

2️⃣ try, catch, finally

 try: Block of code that may throw an error.


 catch: Block to handle the error.
 finally: Block that always runs, whether an error occurs or not.
Syntax:
try {
// Code that may throw error
} catch(error) {
// Handle the error
} finally {
// Code that runs always
}
Example:
try {
let result = riskyOperation(); // Suppose this throws error
[Link](result);
} catch(error) {
[Link]("An error occurred:", [Link]);
} finally {
[Link]("Execution finished");
}
 Output (if error occurs):
An error occurred: riskyOperation is not defined
Execution finished
 Output (if no error occurs):
[Result from riskyOperation]
Execution finished

3️⃣ Throwing Custom Errors

 You can throw your own errors using throw.


 Useful for validation or specific conditions.
Example:
function divide(a, b){
if(b === 0){
throw new Error("Cannot divide by zero!");
}
return a / b;
}

try {
[Link](divide(10,0));
} catch(error) {
[Link]("Error:", [Link]);
}
 Output:
Error: Cannot divide by zero!
 Real-time analogy:
o Imagine a vending machine → you try to buy candy with no money →
machine throws an error instead of giving wrong candy.

4️⃣ Why We Use Error Handling

Reason Explanation

Prevent Crashes Program continues running even if an error occurs

Debugging Shows meaningful messages to fix issues

User Experience Gives friendly error messages instead of blank pages

Validation Check for invalid inputs or conditions

Maintenance Easier to manage large codebases

5️⃣ Summary Table

Concept Definition Example

try Code that might throw error try { ... }

catch Handle error catch(error){ ... }

finally Always executes finally { [Link]("Done") }

throw Create custom error throw new Error("Message")

Error object Provides details about error [Link], [Link]

💡 Quick Tips:

1. Always validate inputs and throw custom errors for clarity.


2. Use try/catch around risky code like API calls, file operations, or dynamic
computations.
3. Use finally for cleanup tasks like closing files or stopping timers.
Template Literals
 Template literals allow easier string creation and interpolation.
 Uses backticks (`) instead of quotes.
 Can include variables and expressions with ${}.
Example:
let name = "Suba";
let age = 21;

// Old way
[Link]("Hello " + name + ", your age is " + age);

// Template literal
[Link](`Hello ${name}, your age is ${age}`);
 Output: Hello Suba, your age is 21
 Also supports multi-line strings:
let text = `Hello
Suba
Welcome!`;
[Link](text);
Why use it: Cleaner syntax, easier to read, supports expressions.

2️⃣ Destructuring

 Allows extracting values from arrays or objects into variables.


 Makes code shorter and cleaner.
A. Array Destructuring
let arr = [1,2,3];
let [a,b,c] = arr;
[Link](a,b,c); // 1 2 3
 Can skip elements:
let [x, , z] = arr;
[Link](x,z); // 1 3
B. Object Destructuring
let person = {name:"Suba", age:21};
let {name, age} = person;
[Link](name, age); // Suba 21
 Can assign new variable names:
let {name: fullName, age: years} = person;
[Link](fullName, years); // Suba 21
Why use it: Cleaner, reduces repetitive code like [Link].

3️⃣ Modules (import, export)

 Modules allow splitting code into multiple files for better maintainability.
 export → expose variables/functions
 import → use them in another file
Example:
[Link]
export function add(a,b){ return a+b; }
export const PI = 3.14;
[Link]
import { add, PI } from "./[Link]";
[Link](add(2,3)); // 5
[Link](PI); // 3.14
Why use it: Better organization, reusable code, avoids global scope pollution.

4️⃣ Classes

 Classes are blueprints for objects.


 ES6 introduced class syntax for easier object-oriented programming.
Example:
class Person {
constructor(name, age){
[Link] = name;
[Link] = age;
}
greet(){
[Link](`Hello, I am ${[Link]}`);
}
}

let suba = new Person("Suba",21);


[Link](); // Hello, I am Suba
Why use it: Cleaner syntax for object creation, supports methods, inheritance, and
constructors.

5️⃣ Default Parameters

 Allows functions to have default values for parameters.


function greet(name="Guest"){
[Link](`Hello ${name}`);
}

greet("Suba"); // Hello Suba


greet(); // Hello Guest
Why use it: Avoid undefined values, simplifies code.

6️⃣ Optional Chaining (?.)

 Allows safe access to nested object properties without throwing errors if a property
is undefined or null.
let person = {name:"Suba", address:{city:"Madurai"}};

[Link]([Link]); // Madurai
[Link]([Link]?.phone); // undefined (does not throw error)
 Works with arrays and functions too:
let arr = [1,2,3];
[Link](arr?.[5]); // undefined
Why use it: Prevents runtime errors when accessing deep or optional properties.

7️⃣ Summary Table

Feature Definition Example Why Use

Template Multi-line & variable Cleaner strings, supports


`Hello ${name}`
literals interpolation expressions

Extract values from let {name, age} =


Destructuring Less repetitive code
arrays/objects person

Split code using import {add} from


Modules Organized, reusable code
export/import './[Link]'

Object-oriented
Classes Blueprint for objects class Person {...}
programming, clean syntax

Default Set default values in Avoid undefined, simplify


function fn(a=5)
parameters functions code

Optional Safe access to nested


obj?.prop?.subprop Prevent runtime errors
chaining properties

💡 Quick Tips:

1. Use template literals instead of string concatenation.


2. Use destructuring for cleaner access to objects/arrays.
3. Use optional chaining to avoid errors in deep objects.
4. Use modules for maintainable and reusable code.
LocalStorage / SessionStorage
Both are part of the Web Storage API, allowing us to store data in the browser.
A. LocalStorage
 Stores data permanently, even after the browser is closed.
 Data is key-value pairs (both as strings).
// Set data
[Link]("name", "Suba");

// Get data
let name = [Link]("name");
[Link](name); // Suba

// Remove data
[Link]("name");

// Clear all
[Link]();
Why use it:
 Persist data across sessions (like user preferences, theme).
 Faster than server-side storage for small data.

B. SessionStorage
 Stores data only for the current session.
 Data is deleted when the browser/tab is closed.
[Link]("sessionName", "Suba");
[Link]([Link]("sessionName")); // Suba
Why use it:
 Useful for temporary data, e.g., form input while user navigates pages.

2️⃣ JSON (JavaScript Object Notation)

 JSON is a data format used to send and receive data between server and client.
 It is lightweight and easy to read.
A. Converting JS objects to JSON
let person = {name:"Suba", age:21};
let jsonData = [Link](person);
[Link](jsonData); // '{"name":"Suba","age":21}'
B. Converting JSON to JS object
let obj = [Link]('{"name":"Suba","age":21}');
[Link]([Link]); // Suba
Why use it:
 Communicate with APIs (fetch/send data).
 Store complex data in LocalStorage/SessionStorage.

3️⃣ Event Loop & Call Stack

JavaScript is single-threaded, meaning it can execute one task at a time, but it can handle
asynchronous tasks via Event Loop.

A. Call Stack
 A stack data structure that keeps track of function calls.
 LIFO (Last In First Out) → last function called is executed first.
function first() {
second();
[Link]("First");
}
function second() {
[Link]("Second");
}
first();
 Execution flow:
1. first() pushed to stack
2. second() pushed → executed → popped
3. [Link]("First") executes → popped
Output:
Second
First

B. Event Loop
 Handles asynchronous code like setTimeout, Promises, fetch.
 How it works:
1. JS executes synchronous code in the call stack.
2. Async tasks go to Web APIs / browser APIs (like timers, fetch).
3. When ready, async callbacks go to task queue.
4. Event loop checks if call stack is empty → pushes task from queue.
Example:
[Link]("Start");

setTimeout(() => {
[Link]("Timeout");
}, 0);

[Link]("End");
Output:
Start
End
Timeout
Explanation:
 setTimeout callback goes to task queue, executed after call stack is empty.
Why use it:
 Makes JS non-blocking.
 Handles async tasks like API calls, timers, DOM events efficiently.

4️⃣ Summary Table

Topic Definition Example Why Use

Store data Save


LocalStorage permanently [Link]("name","Suba") preferences,
in browser user data

SessionStorage Store data [Link]("sessionName","Suba") Temporary data,


Topic Definition Example Why Use

for current
forms
session

Data format API


JSON for JS [Link](obj), [Link](json) communication,
objects storage

Tracks
Understand
function
Call Stack first(); second(); sync code
execution
execution
(LIFO)

Make JS non-
Handles blocking,
Event Loop setTimeout(()=>{},0)
async tasks handle async
code

💡 Quick Tips:

1. Use LocalStorage for persistent user settings.


2. Use SessionStorage for temporary data.
3. Always convert JS objects to JSON before storing or sending to APIs.
4. Understand call stack + event loop to debug async code effectively.
What is OOP?
Object-Oriented Programming (OOP) is a programming paradigm that organizes code
into objects.
 Objects contain properties (data) and methods (functions).
 Helps structure code in a modular, reusable, and maintainable way.
Why we use OOP:
1. Organizes code logically into objects.
2. Makes code reusable with classes and inheritance.
3. Helps manage complex programs easily.
4. Provides concepts like Encapsulation, Inheritance, Polymorphism, Abstraction.

2️⃣ Core OOP Concepts in JavaScript


A. Class
 A blueprint for creating objects.
 Introduced in ES6, but earlier JS used functions/prototypes.
class Person {
constructor(name, age) {
[Link] = name; // property
[Link] = age;
}
greet() { // method
[Link](`Hello, I am ${[Link]}`);
}
}

let suba = new Person("Suba", 21);


[Link](); // Hello, I am Suba

B. Object
 Instance of a class.
 Contains specific values for properties.
let vidya = new Person("Vidya", 22); // Object
[Link]([Link]); // Vidya

C. Encapsulation
 Hiding internal details of an object.
 Use private properties with _ or # (ES2020).
class BankAccount {
#balance = 0; // private property

deposit(amount) {
this.#balance += amount;
}

getBalance() {
return this.#balance;
}
}

let account = new BankAccount();


[Link](100);
[Link]([Link]()); // 100
[Link](account.#balance); // Error: private property
Why: Protect data from outside access.

D. Inheritance
 One class inherits properties and methods from another class.
 Use extends and super().
class Animal {
constructor(name) {
[Link] = name;
}
speak() {
[Link](`${[Link]} makes a sound`);
}
}

class Dog extends Animal {


speak() {
[Link](`${[Link]} barks`);
}
}

let dog = new Dog("Tommy");


[Link](); // Tommy barks
Why: Reuse code from parent classes, avoid duplication.

E. Polymorphism
 Same method behaves differently for different objects.
 Achieved by method overriding.
let cat = new Animal("Kitty");
[Link](); // Kitty makes a sound
[Link](); // Tommy barks
 Both speak() exist, but behave differently.

F. Abstraction
 Hide unnecessary details, show only essential features.
 Achieved using classes and methods.
class Car {
startEngine() {
this.#checkFuel();
[Link]("Engine started");
}
#checkFuel() {
[Link]("Fuel level OK"); // private method
}
}

let car = new Car();


[Link](); // Fuel level OK, Engine started
// car.#checkFuel(); // Error: private method

3️⃣ Prototype & Methods

 JS objects also use prototype-based inheritance.


 Methods added to prototype are shared across objects.
function PersonProto(name) {
[Link] = name;
}

[Link] = function() {
[Link](`Hello, ${[Link]}`);
};

let p = new PersonProto("Suba");


[Link](); // Hello, Suba

4️⃣ Summary Table of OOP Concepts in JS

Concept Definition Example

Class Blueprint for objects class Person {...}

Object Instance of a class let p = new Person()

Encapsulation Hide internal details Private property: #balance

Inheritance Child class inherits parent class Dog extends Animal

Polymorphism Same method, different behavior Override speak()

Abstraction Show only essential details Private method: #checkFuel()

Prototype Shared methods for objects [Link]

💡 Quick Tips:

1. Use classes for structured code instead of many global functions.


2. Encapsulation protects sensitive data.
3. Inheritance and polymorphism reduce code duplication.
4. Abstraction simplifies interface for users of your class.

Task
Calculator
Purpose: Create a simple arithmetic calculator that performs basic operations like addition,
subtraction, multiplication, and division.
Key Concepts:
 Handling user input via buttons.
 Performing arithmetic operations.
 Displaying results dynamically.
 Managing state (current input, previous input).
Learning Outcome: You'll grasp event handling, DOM manipulation, and basic logic
implementation.

2. To-Do List
Purpose: Develop an application that allows users to add, edit, and delete tasks.
Key Concepts:
 Creating and managing lists.
 Handling user interactions (add, edit, delete).
 Storing data temporarily (e.g., using arrays).
Learning Outcome: You'll learn about CRUD operations (Create, Read, Update, Delete) and
dynamic content rendering.

3. Digital Clock
Purpose: Build a real-time digital clock that displays the current time and updates every
second.
Key Concepts:
 Using JavaScript's setInterval function.
 Manipulating Date and Time objects.
 Updating the DOM at regular intervals.
Learning Outcome: You'll understand asynchronous operations and time-based functions.

4. Weather App (Fetch API)


Purpose: Create an application that fetches and displays weather information based on user
input (e.g., city name).
Key Concepts:
 Making HTTP requests using the Fetch API.
 Handling JSON data.
 Error handling and displaying loading states.
Learning Outcome: You'll gain experience with asynchronous programming and working
with external APIs.

5. Rock-Paper-Scissors Game
Purpose: Develop a simple game where the user plays against the computer.
Key Concepts:
 Generating random choices for the computer.
 Comparing user and computer choices.
 Displaying results and keeping score.
Learning Outcome: You'll practice conditional statements and random number generation.

6. Form Validation
Purpose: Implement a form that validates user input before submission (e.g., checking for
empty fields, valid email format).
Key Concepts:
 Accessing and validating form elements.
 Providing real-time feedback to users.
 Preventing form submission on invalid input.
Learning Outcome: You'll enhance your understanding of user input handling and validation
techniques.

7. Small Portfolio Website with JS Interaction


Purpose: Create a personal portfolio website that showcases your projects and skills,
incorporating interactive elements.
Key Concepts:
 Designing responsive layouts with HTML and CSS.
 Adding interactivity with JavaScript (e.g., modals, sliders).
 Organizing content effectively.
Learning Outcome: You'll develop skills in web design, user experience, and integrating
JavaScript for interactivity.

8. Countdown Timer
Purpose: Build a timer that counts down from a specified time and alerts the user when time
is up.
Key Concepts:
 Using setInterval and clearInterval.
 Calculating time differences.
 Updating the DOM dynamically.
Learning Outcome: You'll understand time-based events and user notifications.

9. Quotes Generator
Purpose: Develop an application that displays a random quote each time the user interacts
with it.
Key Concepts:
 Storing and retrieving data (quotes).
 Manipulating the DOM to display content.
 Handling user interactions (e.g., button clicks).
Learning Outcome: You'll practice working with arrays and event listeners.
10. BMI Calculator
Purpose: Create a tool that calculates the Body Mass Index (BMI) based on user input
(weight and height).
Key Concepts:
 Performing mathematical calculations.
 Converting units (e.g., cm to meters).
 Displaying results and categorizing BMI.
Learning Outcome: You'll enhance your skills in mathematical operations and data
presentation.

11. Hex Colour Background Change


Purpose: Develop a feature that changes the background color of a webpage to a random hex
color upon user interaction.
Key Concepts:
 Generating random hex values.
 Manipulating CSS properties with JavaScript.
 Handling user events (e.g., button clicks).
Learning Outcome: You'll learn about color manipulation and dynamic styling.

You might also like