JS FUNDAMENTALS

What is JavaScript?

JavaScript is a programming language used to make websites interactive.


Without JS:

  • HTML → structure
  • CSS → design
  • ❌ No interactivity


With JS:

  • Button click → works
  • Form validation → works
  • Animations → dynamic
  • Data from server → load


JavaScript is Case Sensitive

JavaScript identifiers are case sensitive.

The variables lastName and lastname, are different variables

JavaScript Engine

A JavaScript Engine is a program that:


Reads your JS code

Converts it into machine code

Executes it


Popular JS Engines

  • V8 (Chrome, Node.js)
  • SpiderMonkey (Firefox)
  • JavaScriptCore (Safari)


How Engine Works


How to Execute JavaScript Code ? - GeeksforGeeks


Steps:

  1. You write JS code
  2. Engine parses code
  3. Converts to machine code
  4. Executes instantly 


Runtime

 Runtime (Browser Environment)


JavaScript alone = language

But it needs a runtime to run


Browser = Runtime

Browser gives:

  • DOM (Document Object Model)
  • APIs (fetch, setTimeout, etc.)
  • Event system


Example

console.log("Hello");

console.log() is NOT pure JS

It is provided by the browser runtime


Runtime Components

Includes:

  • Call Stack
  • Web APIs
  • Event Loop
  • Callback Queue


👉 You’ll learn these deeply later (advanced level)

How Browser Executes JavaScript

Flow:

  1. Browser reads HTML
  2. Builds DOM
  3. Finds <script>
  4. Stops HTML parsing ⛔
  5. Executes JS
  6. Continues loading


 JS is blocking by default

That means:

  • If JS takes time → page load slows

Use:

<script defer src="script.js"></script>

👉 defer = run JS after HTML loads

JavaScript Where To

The <script> Tag

In HTML, JavaScript code is inserted between <script> and </script> tags.


JavaScript in <head> or <body>

You can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

JavaScript in <head>

In this example, a JavaScript function is placed in the <head> section of an HTML page.


Example function myFunction() { document.getElementByIHTML Sandbox — click to edit


JavaScript in <body>

In this example, a JavaScript function is placed in the <body> section of an HTML page.


Demo JavaScript in Body A Paragraph Try it function myFuHTML Sandbox — click to edit


External JavaScript

Scripts can also be placed in external files:

External file: myScript.js

function myFunction() {

 document.getElementById("demo").innerHTML = "Paragraph changed.";

}

External scripts are practical when the same code is used in many different web pages.

JavaScript files have the file extension .js.

To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:


Example

<script src="myScript.js"></script>


Advantages

Placing scripts in external files has some advantages:

  • It separates HTML and code
  • It makes HTML and JavaScript easier to read and maintain
  • Cached JavaScript files can speed up page loads


JavaScript Output

JavaScript Display Possibilities

JavaScript can "display" data in different ways:

  • Writing into an HTML element, using innerHTML or innerText.
  • Writing into the HTML output using document.write().
  • Writing into an alert box, using window.alert().
  • Writing into the browser console, using console.log().


Using innerHTML

To access an HTML element, you can use the document.getElementById(id) method.

Use the id attribute to identify the HTML element.

Then use the innerHTML property to change the HTML content of the HTML element:


My First Web Page My First Paragraph document.getElementHTML Sandbox — click to edit

Using innerText

To access an HTML element, use the document.getElementById(id) method.

Then use the innerText property to change the inner text of the HTML element:


My First Web Page My First Paragraph document.getElementHTML Sandbox — click to edit


Use innerHTML when you want to change an HTML element.

Use innerText when you only want to change the plain text.


Using document.write()

For testing purposes, it is convenient to use document.write():


My First Web Page My first paragraph. document.write(5 + 6HTML Sandbox — click to edit


Using window.alert()

You can use an alert box to display data:

My First Web Page My first paragraph. window.alert(5 + 6);HTML Sandbox — click to edit

Using console.log()

For debugging purposes, you can call the console.log() method in the browser to display data.

console.log(5 + 6);HTML Sandbox — click to edit


VARIABLES & DATA TYPES

 Variables (in programming)


A variable is a named container used to store data.


👉 Example (JavaScript):

let name = "Jeeshma";

Here, name is a variable storing a value.


In short:

➡️ Variable = a box that holds data


Data Types


A data type defines what kind of data a variable stores.


👉 Common types:

  • String"Hello"
  • Number25
  • Booleantrue / false
  • Array[1, 2, 3]
  • Object{name: "Jeeshma"}


In short:

➡️ Data Type = type of data inside the box

Variable

 What is a Variable?


A variable is a container that stores data.


 Example

let age = 20;

  • let → keyword
  • age → variable name
  • 20 → value


 var, let, const


1. var (OLD WAY – avoid in modern JS)

var name = "John";

❌ Problems:

  • Function scoped (not block scoped)
  • Can be re-declared
  • Causes bugs
var x = 10;
var x = 20; // ✅ allowed (but dangerous)


2. let (MODERN – use this )

let age = 25;

✅ Features:

  • Block scoped
  • Can be updated
  • Cannot be re-declared
let x = 10;
x = 20; // ✅ allowed

let x = 30; // ❌ error


3. const (CONSTANT – most used )

const pi = 3.14;

✅ Features:

  • Block scoped
  • Cannot be updated
  • Cannot be re-declared
const x = 10;
x = 20; // ❌ error


When to use what?

  • const → default choice ✅
  • let → if value changes
  • var → ❌ avoid


Data Types

 1. Primitive Types


Stored by value


Types:

  • String → "hello"
  • Number → 10
  • Boolean → true / false
  • Undefined → variable declared but no value
  • Null → intentionally empty


Example:

let name = "blackbox";   // String
let age = 20;           // Number
let isStudent = true;   // Boolean
let x;                  // Undefined
let y = null;           // Null


2. Reference Types

👉 Stored by reference (memory address)

Types:

  • Object
  • Array
  • Function

Example:

let user = {
  name: "blackbox",
  age: 20
};

let arr = [1, 2, 3];


Key Difference (VERY IMPORTANT)

Primitive:

let a = 10;
let b = a;

b = 20;

console.log(a); // 10

👉 Copy created → separate memory

Reference:

let obj1 = { name: "John" };
let obj2 = obj1;

obj2.name = "Alex";

console.log(obj1.name); // Alex 😱

👉 Same memory → both change

Type Coercion

 JavaScript automatically converts types when needed


 1. Implicit Coercion (Automatic)

Example:

console.log("5" + 2); 
// "52"

👉 Number → converted to string

console.log("5" - 2);
// 3

👉 String → converted to number

console.log(true + 1);
// 2

👉 true → 1


2. Explicit Coercion (Manual)

You convert types yourself:

Number("10");   // 10
String(100);    // "100"
Boolean(0);     // false




Mini Practice

let a = "10";
let b = 5;

console.log(a + b); 
console.log(a - b);
console.log(a * b);

👉 Try to predict output before running


Quick Rule (VERY IMPORTANT)

  • + → string concatenation if one is string
  • -, *, / → always convert to number


Type Conversion

Type Conversion


Converting one type into another.

String Conversion

let num = 100;

console.log(String(num));

Output:

"100"

Number Conversion

let str = "123";

console.log(Number(str));

Output:

123

Boolean Conversion

Boolean(1);
Boolean(0);

Output:

true
false


String Formatting

String formatting means combining variables, text, and values inside a string to create dynamic output.


1. Traditional String Concatenation

Using + operator.

let name = "Jeeshma";
let age = 25;

console.log("My name is " + name + " and I am " + age + " years old.");

Output:

My name is Jeeshma and I am 25 years old.

Problems

As the string becomes longer, readability decreases.


2. Template Literals

Uses backticks ` `

Variables are inserted using ${}

let name = "Jeeshma";
let age = 25;

console.log(`My name is ${name} and I am ${age} years old.`);

Output:

My name is Jeeshma and I am 25 years old.


3. Expressions Inside Template Literals

You can perform calculations.

let a = 10;
let b = 20;

console.log(`Total: ${a + b}`);

Output:

Total: 30


4. Function Calls Inside Template Literals

function greet() {
  return "Hello";
}

console.log(`${greet()} Jeeshma`);

Output:

Hello Jeeshma


OPERATORS

Operators (JS): symbols that perform actions on values

👉 Types:

  • Arithmetic → + - * / %
  • Comparison → == === > <
  • Logical → && || !
  • Assignment → = += -=


Arithmetic Operators

 Used for mathematical calculations


➕ Basic Operators

let a = 10;
let b = 3;

console.log(a + b); // 13
console.log(a - b); // 7
console.log(a * b); // 30
console.log(a / b); // 3.33...
console.log(a % b); // 1 (remainder)


🔥 Increment / Decrement

let x = 5;

x++; // post-increment
console.log(x); // 6

++x; // pre-increment
console.log(x); // 7


👉 Why?

  • x++ → increases after → becomes 6
  • ++x → increases before → becomes 7


⚠️ Important Difference

let x = 5;

console.log(x++); // 5 (use first, then increase)
console.log(++x); // 7 (increase first, then use)

Step 1: console.log(x++)

  • Current x = 5
  • x++use first → print 5
  • Then increase → x = 6

👉 Output: 5


Step 2: console.log(++x)

  • Now x = 6
  • ++xincrease first → becomes 7
  • Then print → 7

👉 Output: 7


Easy Trick to Remember

  • Post (x++) → "Use → Then Increase"
  • Pre (++x) → "Increase → Then Use"


JavaScript Operators


 Quick Practice

What will this print?

let x = 10;

console.log(++x); 
console.log(x++); 
console.log(x);

Answer:

  • ++x → 11
  • x++ → prints 11, then becomes 12
  • final x → 12


Comparison Operators

 Used to compare values → returns true or false


Basic Comparison

console.log(5 > 3);   // true
console.log(5 < 3);   // false
console.log(5 >= 5);  // true
console.log(5 <= 4);  // false


Logical Operators

Used to combine conditions


AND (&&)

Both must be true

console.log(true && true);   // true
console.log(true && false);  // false


OR (||)

At least one true

console.log(true || false); // true
console.log(false || false); // false


NOT (!)

Reverses value

console.log(!true);  // false
console.log(!false); // true


String Operators

5. String Operators

Used with strings.

let first = "Hello";
let second = "World";

console.log(first + " " + second);
// Hello World


JavaScript Conditionals

Conditional Statements

Conditional Statements allow us to perform different actions for different conditions.

Conditional statements run different code depending on true or false conditions.

Conditional statements include:

  • if
  • if...else
  • if...else if...else
  • switch
  • ternary (? :)


When to use Conditionals

  • Use if to specify a code block to be executed, if a specified condition is true
  • Use else to specify a code block to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative code blocks to be executed
  • Use (? :) (ternary) as a shorthand for if...else



if, else, else if

if Statement

Use if to specify a code block to be executed, if a specified condition is true.


Syntax

if (condition) {

  // code to execute if the condition is true

}


<!DOCTYPE html>
<html>
<body>

<h2>If Statement</h2>

<script>
let age = 20;

if (age >= 18) {
  document.write("You can vote");
}
</script>

</body>
</html>


else Statement

Use else to specify a code block to be executed, if the same condition is false.


Syntax

if (condition) {

  // code to execute if the condition is true

} else {

  // code to execute if the condition is false

}


<!DOCTYPE html>
<html>
<body>

<h2>If Else Statement</h2>

<script>
let age = 16;

if (age >= 18) {
  document.write("You can vote");
} else {
  document.write("You cannot vote");
}
</script>

</body>
</html>


else if Statement

Use else if to specify a new condition to test, if the first condition is false.


Syntax

if (condition1) {

  // code to execute if condition1 is true

} else if (condition2) {

  // code to execute if the condition1 is false and condition2 is true

} else {

  // code to execute if the condition1 is false and condition2 is false

}

<!DOCTYPE html>
<html>
<body>

<h2>Else If Statement</h2>

<script>
let marks = 75;

if (marks >= 90) {
  document.write("Grade A");
} else if (marks >= 70) {
  document.write("Grade B");
} else {
  document.write("Grade C");
}
</script>

</body>
</html>

switch Statement

switch Statement

Use switch to specify many alternative code blocks to be executed.


Syntax

switch(expression) {

  case x:

    // code block

    break;

  case y:

    // code block

    break;

  default:

   // code block

}

Switch StatementHTML Sandbox — click to edit

                                

Ternary Operator (? :)

Ternary Operator (? :)

Use (? :) (ternary) as a shorthand for if...else.


Syntax

condition ? valueIfTrue : valueIfFalse;



Using if...else

let age = 20;

if (age >= 18) {
  console.log("Adult");
} else {
  console.log("Minor");
}

Using Ternary

let age = 20;

let result = age >= 18 ? "Adult" : "Minor";

console.log(result);

Output:

Adult



Example

condition ? expression1 : expression2

Loops

Loops

Repeat code multiple times.

for Loop


1. for Loop

for(let i = 1; i <= 5; i++){
    console.log(i);
}

How it works

A for loop has 3 parts:

for(initialization; condition; increment)

In your example:

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


Iteration-by-Iteration

First iteration

i = 1
1 <= 5  // true

Print:

console.log(1);

Output:

1

Then:

i++;


while Loop

while Loop

let i = 1;

while(i <= 5){
   console.log(i);
   i++;
}

Structure

while(condition){
   // code
}

The condition is checked before executing the loop body.

The for loop simply puts initialization, condition, and increment in one line.


for → Use when you know how many times to loop.

while → Use when looping depends on a condition.

do...while Loop

let i = 10;

do{
   console.log(i);
   i++;
}
while(i <= 5);

Structure

do{
   // code
}
while(condition);

The important difference:

The code runs first, then the condition is checked.




Examples

1. for Loop (Known Number of Iterations)

Example 1: Display products on an e-commerce website

const products = ["Laptop", "Phone", "Watch"];

for(let i = 0; i < products.length; i++){
    console.log(products[i]);
}

Use case: Showing all products from a list.


Step 1: Create an Array

const products = ["Laptop", "Phone", "Watch"];

This creates an array containing 3 items:

Think of it like:

products[0] = "Laptop"
products[1] = "Phone"
products[2] = "Watch"

Step 2: Start the Loop

for(let i = 0; i < products.length; i++)

Initialization

let i = 0

Start from the first item.

Current value:

i = 0

Condition

i < products.length

What is products.length?

products.length

Output:

3

Because there are 3 items in the array.

So the condition becomes:

i < 3

First Iteration

Current value:

i = 0

Check:

0 < 3

✅ True

Run:

console.log(products[i]);

Which means:

console.log(products[0]);

Output:

Laptop

Then:

i++

we use:

for(let i = 0; i < products.length; i++)

because if you later add more products:

const products = ["Laptop", "Phone", "Watch", "Tablet", "Camera"];

products.length automatically becomes 5, and the loop still works without changing the code.


2. while Loop (Unknown Number of Iterations)

Example 1: Login System

let password = "";

while(password !== "admin"){
    password = prompt("Enter Password");
}

Use case: Keep asking until the correct password is entered.


Comparing the Logic

while

let password = "";

while(password !== "admin"){
    password = prompt("Enter Password");
}

Flow:

Initialize password
      ↓
Check condition
      ↓
Ask password
      ↓
Check again

do...while

let password;

do{
    password = prompt("Enter Password");
}while(password !== "admin");

Flow:

Ask password
      ↓
Check condition
      ↓
Ask again if wrong


Simple Rule

  • while → "Check first, then run."
  • do...while → "Run first, then check."


Functions

Functions

A function is a reusable block of code that performs a specific task.

Instead of writing the same code again and again, you write it once inside a function and call it whenever needed.


Basic Function

function greet(){
   console.log("Hello");
}

greet();
  • function → keyword to create a function
  • greet → function name
  • {} → function body

At this point, nothing is printed.

The function is only stored in memory.

Call the function

greet();

Output:

Hello

The code inside the function executes.


Function with Parameters

Parameters allow a function to receive data.

function greet(name){
   console.log("Hello " + name);
}

greet("John");

Output:

Hello John

Multiple Parameters

function introduce(name, age){
   console.log(name + " is " + age + " years old");
}

introduce("John", 25);

Output:

John is 25 years old


Return Value

Sometimes a function should send a value back.

For that we use:

return

Example:

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

console.log(add(5,3));

Output:

8

Why Return is Important

Without return:

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

Output:

console.log(add(5,3));

Result:

undefined

Because nothing was returned.

Function Expressions

 Function Expressions

Functions can be stored in variables.

const greet = function(){
   console.log("Hello");
};

greet();

Call Function

greet();

Output:

Hello

Difference from Normal Function

Function Declaration

function greet(){
   console.log("Hello");
}

Function Expression

const greet = function(){
   console.log("Hello");
};

Both work similarly.

Arrow Functions

Arrow Functions

Arrow functions are a shorter way to write functions.

Traditional:

function greet(){
   console.log("Hello");
}

Arrow:

const greet = () => {
   console.log("Hello");
};

Output:

Hello

Syntax

const functionName = () => {
   // code
};

Single-Line Arrow Function

Traditional:

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

Arrow:

const add = (a,b) => a+b;

What Happens?

(a,b) => a+b

Automatically means:

(a,b) => {
   return a+b;
}


Objects & Arrays

how JavaScript stores, manages, and manipulates data.

Almost every JavaScript project uses:

  • Objects → Store related data
  • Arrays → Store collections of data
  • Array Methods → Process and transform data


Objects

Objects

An object is a collection of key-value pairs.

let person = {
    name: "John",
    age: 25,
    city: "London"
};

console.log(person);

Output:

{
   name: "John",
   age: 25,
   city: "London"
}

Why Objects?

Without objects:

let name = "John";
let age = 25;
let city = "London";

With objects:

let person = {
   name: "John",
   age: 25,
   city: "London"
};

Everything related stays together.


Accessing Properties

Dot Notation

console.log(person.name);
console.log(person.age);

Output:

John
25

Bracket Notation

console.log(person["name"]);

Output:

John

Useful when property name is dynamic.

let key = "age";

console.log(person[key]);

Output:

25

Updating Properties

person.age = 30;

console.log(person);

Output:

{
   name: "John",
   age: 30,
   city: "London"
}

Adding Properties

person.country = "UK";

Output:

{
   name: "John",
   age: 30,
   city: "London",
   country: "UK"
}

Deleting Properties

delete person.city;

Output:

{
   name: "John",
   age: 30,
   country: "UK"
}

Nested Objects

Objects can contain objects.

let user = {
   name: "John",
   address: {
      city: "London",
      zip: 12345
   }
};

console.log(user.address.city);

Output:

London

Object Methods

Methods are functions inside objects.

let person = {
   name: "John",

   greet: function() {
      console.log("Hello");
   }
};

person.greet();

Output:

Hello

Real Example

let calculator = {
   add(a,b){
      return a+b;
   },

   sub(a,b){
      return a-b;
   }
};

console.log(calculator.add(5,3));

Output:

8

this Keyword

this refers to the object that is calling the method.

let person = {
    name: "Jithu",

    greet() {
        console.log(this.name);
    }
};

person.greet();

Output

Jithu

Without this

let person = {
    name: "Jithu",

    greet() {
        console.log(name);
    }
};

person.greet();

❌ Error because name is not defined globally.

Array

 Arrays

An Array stores multiple values in a single variable.

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

Access Elements

console.log(fruits[0]);
console.log(fruits[1]);

Output

Apple
Orange

Change Value

fruits[1] = "Banana";

console.log(fruits);

Array Length

console.log(fruits.length);

Output

3


Basic Array Methods

push()

Add item at end.

let arr = [1, 2, 3];

arr.push(4);

console.log(arr);

Output

[1,2,3,4]


pop()

Remove last item.

arr.pop();

console.log(arr);

Output

[1,2,3]


unshift()

Add at beginning.

arr.unshift(0);

console.log(arr);

Output

[0,1,2,3]


shift()

Remove first element.

arr.shift();

console.log(arr);

Output

[1,2,3]


1. forEach()

What is it?

forEach() is used to execute a function for every element in an array.

Think of it as:

"Go through each item and do something."


Syntax

array.forEach((element, index, array) => {
    // code
});


Example

numbers.forEach(num => {
    console.log(num);
});

Output

1
2
3
4
5


Example with Index

numbers.forEach((num, index) => {
    console.log(index, num);
});

Output

0 1
1 2
2 3
3 4
4 5


Important

const result = numbers.forEach(num => num * 2);

console.log(result);

Output:

undefined

❌ forEach() does NOT return anything.


2. map()

What is it?

map() creates a NEW array by transforming each element.

Think:

"Take every item and convert it into something else."

Syntax

array.map((element) => {
    return something;
});

Example

const doubled = numbers.map(num => num * 2);

console.log(doubled);

Output:

[2, 4, 6, 8, 10]

Original array:

[1,2,3,4,5]

New array:

[2,4,6,8,10]


3. filter()

What is it?

filter() returns a NEW array containing only elements that pass a condition.

Think:

"Keep only the items that match."

Syntax

array.filter(element => condition);

Example

const even = numbers.filter(
    num => num % 2 === 0
);

console.log(even);

Output:

[2,4]


Real World Example

const users = [
    {name:"Jithu", age:22},
    {name:"Rahul", age:17},
    {name:"Arun", age:25}
];

const adults = users.filter(
    user => user.age >= 18
);

console.log(adults);

Output:

[
 {name:"Jithu", age:22},
 {name:"Arun", age:25}
]


4. find()

What is it?

find() returns ONLY the first element that matches a condition.

Think:

"Find the first matching item and stop."

Example

const result = numbers.find(
    num => num > 3
);

console.log(result);

Output:

4


5. some()

What is it?

Checks whether AT LEAST ONE element satisfies a condition.

Think:

"Does any item match?"

Example

const result = numbers.some(
    num => num > 4
);

console.log(result);

Output:

true

Because 5 is greater than 4.


Example

const result = numbers.some(
    num => num > 10
);

console.log(result);

Output:

false


6. every()

What is it?

Checks if ALL elements satisfy a condition.

Think:

"Do all items match?"

Example

const result = numbers.every(
    num => num > 0
);

console.log(result);

Output:

true

Example

const result = numbers.every(
    num => num > 2
);

console.log(result);

Output:

false


7. reduce()

What is it?

reduce() converts an entire array into a single value.

Think:

"Reduce many values into one."

Syntax

array.reduce(
    (accumulator, currentValue) => {},
    initialValue
);

Example: Sum

const total = numbers.reduce(
    (acc, curr) => acc + curr,
    0
);

console.log(total);

Output:

15

Step-by-Step

[1,2,3,4,5]

Initial:

acc = 0

Iteration 1:

0 + 1 = 1

Iteration 2:

1 + 2 = 3

Iteration 3:

3 + 3 = 6

Iteration 4:

6 + 4 = 10

Iteration 5:

10 + 5 = 15

Final:

15

Real World Example

Calculate total cart price.

const cart = [
    {name:"Phone", price:30000},
    {name:"Mouse", price:500},
    {name:"Keyboard", price:2000}
];

const total = cart.reduce(
    (sum, item) => sum + item.price,
    0
);

console.log(total);

Output:

32500


8. sort()

What is it?

Used to arrange array elements.

Think:

"Put items in order."

Sorting Strings

const fruits = [
    "Orange",
    "Apple",
    "Banana"
];

fruits.sort();

console.log(fruits);

Output:

["Apple","Banana","Orange"]

Sorting Numbers

Wrong Way

const nums = [100, 5, 20, 1];

nums.sort();

console.log(nums);

Output:

[1,100,20,5]

Because JavaScript treats them as strings.

Correct Way

nums.sort((a,b) => a - b);

Output:

[1,5,20,100]

How It Works

(a,b) => a - b

If result is:

Negative → a comes first
Positive → b comes first
0 → no change

Descending Order

nums.sort((a,b) => b - a);

Output:

[100,20,5,1]


Sort by Age

const users = [
    { name: "Jithu", age: 22 },
    { name: "Rahul", age: 18 },
    { name: "Arun", age: 25 }
];

users.sort((a, b) => a.age - b.age);

console.log(users);

Output:

[
 {name:"Rahul", age:18},
 {name:"Jithu", age:22},
 {name:"Arun", age:25}
]


Modern ES6+ JavaScript

Write cleaner, shorter, and more modern JavaScript code.

ES6 (ECMAScript 2015) introduced many features that are heavily used in React, Node.js, and modern web development.



Template Literals

Template Literals

What is it?

Template literals allow you to embed variables directly inside strings.

Before ES6:

const name = "Jithu";
const age = 22;

console.log(
    "My name is " + name + " and I am " + age + " years old."
);

Output:

My name is Jithu and I am 22 years old.

ES6 Way

Use backticks (`)

const name = "Jithu";
const age = 22;

console.log(
    `My name is ${name} and I am ${age} years old.`
);

Output:

My name is Jithu and I am 22 years old.

Multiple Lines

Before ES6:

const text =
"Hello\n" +
"World";

After ES6:

const text = `
Hello
World
`;

console.log(text);

Output:

Hello
World

Expression Inside Template Literal

const a = 10;
const b = 20;

console.log(`Sum = ${a + b}`);

Output:

Sum = 30


Destructuring

Destructuring


What is it?

Extract values from arrays or objects into variables.


Array Destructuring

Without Destructuring

const colors = ["red", "green", "blue"];

const first = colors[0];
const second = colors[1];

With Destructuring

const colors = ["red", "green", "blue"];

const [first, second] = colors;

console.log(first);
console.log(second);

Output:

red
green

Skip Values

const colors = ["red", "green", "blue"];

const [first, , third] = colors;

console.log(third);

Output:

blue


Object Destructuring

const user = {
    name: "Jithu",
    age: 22,
    city: "Trivandrum"
};

const { name, age } = user;

console.log(name);
console.log(age);

Output:

Jithu
22


Rename Variables

const user = {
    name: "Jithu"
};

const { name: userName } = user;

console.log(userName);

Output:

Jithu


Spread Operator (...)

Spread Operator (...)

What is it?

Spread breaks an array or object into individual values.

Think:

...

means

"Spread everything out."

Array Example

const nums = [1, 2, 3];

console.log(...nums);

Output:

1 2 3

Copy Array

const nums = [1, 2, 3];

const copy = [...nums];

console.log(copy);

Output:

[1,2,3]


Merge Arrays

const arr1 = [1, 2];
const arr2 = [3, 4];

const merged = [...arr1, ...arr2];

console.log(merged);

Output:

[1,2,3,4]


DOM Mastery

What is DOM?

DOM = Document Object Model

When the browser loads an HTML page, it converts the HTML into a tree-like structure called the DOM.

HTML

<body>
    <h1>Hello</h1>
    <p>Welcome</p>
</body>

DOM Tree

Document
│
└── html
    │
    ├── head
    │
    └── body
         │
         ├── h1
         │    └── "Hello"
         │
         └── p
              └── "Welcome"

JavaScript can access and modify any node in this tree.


Without DOM, JavaScript cannot:

  • Change text
  • Change images
  • Open menus
  • Create cards
  • Build sliders
  • Build modals
  • Build shopping carts

Almost every frontend website uses DOM.

Selecting Elements

querySelector()

Used to select ONE element.

It always returns the first matching element.

Real World Usage

Suppose you have:

<button class="menu-btn">
    Menu
</button>

When user clicks menu button:

const menuBtn =
document.querySelector(".menu-btn");

Now JavaScript can control it.


querySelectorAll()

Used when multiple elements need to be selected.

Example

<div class="card"></div>
<div class="card"></div>
<div class="card"></div>


const cards =
document.querySelectorAll(".card");

Now all cards are selected.


getElementById()

Used to select an element by ID.

IDs should be unique.

Example:

<h1 id="hero-title">
    Welcome
</h1>


const title =
document.getElementById("hero-title");


const heading = document.getElementById("title");

const headings = [
"Welcome",
"Learn JavaScript",
"Become a Frontend Developer"
];

let index = 0;

setInterval(() => {
heading.textContent = headings[index];
index = (index + 1) % headings.length;
}, 3000);


2. querySelector()

Selects the first matching element.

HTML

<p class="text">Paragraph 1</p>
<p class="text">Paragraph 2</p>

JavaScript

const para = document.querySelector(".text");

console.log(para);

Output

<p class="text">Paragraph 1</p>

Only the first match is selected.


Using Tag Name

const heading = document.querySelector("h1");

Using ID

const heading = document.querySelector("#title");

Using Class

const heading = document.querySelector(".box");


3. querySelectorAll()

Selects all matching elements.

HTML

<li>Apple</li>
<li>Orange</li>
<li>Banana</li>

JavaScript

const items = document.querySelectorAll("li");

console.log(items);

Output:

Apple
Orange
Banana


4. textContent

Used to read or change text.

Example

<h1 id="title">
    Hello
</h1>

Read:

title.textContent

Output:

Hello

Change Text

title.textContent =
"Welcome";


5. innerHTML

Used to read or insert HTML.

Example

<div id="box">
</div>


box.innerHTML =
"<h2>Hello</h2>";

Result:

<div id="box">
    <h2>Hello</h2>
</div>


1. classList.add()

Adds a class to an element.

Syntax

element.classList.add("classname");

Example

HTML

<h1 id="title">
    Hello
</h1>

CSS

.active{
    color:red;
}

JavaScript

const title =
document.getElementById("title");

title.classList.add("active");

Result

<h1 id="title" class="active">
    Hello
</h1>

Text becomes red.


Real World Usage

Open Mobile Menu

Before

<div class="menu">

After

<div class="menu active">


menu.classList.add("active");

Menu becomes visible.