JavaScript Variables
Variables are used to store data in JavaScript so you can use and manipulate it later. Think of
a variable like a
labeled box that holds information such as numbers, text, or other types of data.
Types of Variable Declarations
- var: Old way of declaring variables (function-scoped, can be re-declared).
- let: Modern way to declare variables (block-scoped, can be updated).
- const: Block-scoped but cannot be reassigned once defined.
Declaring Variables
// Using var
var name = "Alice";
// Using let
let age = 25;
// Using const
const country = "Nepal";
Reassigning Values
let score = 10;
score = 20; // OK
const year = 2024;
year = 2025; // ❌ Error: Cannot reassign a const
Variable Naming Rules
- Must start with a letter,
_ or $.
- Cannot start with a number.
- No spaces allowed.
- Use camelCase for multiple words:
userName
Example
let userName = "John";
let userAge = 30;
console.log("Name:", userName);
console.log("Age:", userAge);
Output
Name: John
Age: 30
Live HTML + JS Example
<script>
let product = "Laptop";
let price = 1200;
alert("Product: " + product + "\\nPrice: $" + price);
</script>
JavaScript Data Types
Data types define the kind of value a variable can hold. JavaScript is a dynamically typed
language, meaning you don’t have to specify the type — it figures it out for you.
Primitive Data Types
- String: Text data →
"hello" or 'world'
- Number: Numeric values →
42, 3.14
- Boolean: True or false →
true, false
- Undefined: A variable declared but not assigned →
let a;
- Null: Explicitly empty →
null
- BigInt: Large integers →
123456789012345678901234567890n
- Symbol: Unique identifier (advanced) →
Symbol("id")
Non-Primitive (Reference) Types
- Object: Key-value pairs →
{ name: "Alex", age: 30 }
- Array: Ordered list of values →
[1, 2, 3]
- Function: Reusable block of code →
function greet() { ... }
Examples
let name = "Sita"; // String
let age = 22; // Number
let isStudent = true; // Boolean
let nothing = null; // Null
let notDefined; // Undefined
let big = 1234567890123n; // BigInt
let person = { name: "Ram", age: 25 }; // Object
let colors = ["red", "green", "blue"]; // Array
let greet = function() {
console.log("Hello!");
}; // Function
Checking Type
You can check a variable’s type using the typeof operator.
console.log(typeof "Hello"); // string
console.log(typeof 123); // number
console.log(typeof true); // boolean
console.log(typeof {}); // object
console.log(typeof []); // object (yes, arrays are objects!)
console.log(typeof null); // object (this is a historical bug)
JavaScript Conditionals
Conditional statements allow you to run different blocks of code based on different conditions.
They're how your code makes decisions.
Types of Conditional Statements
- if: Runs a block of code if a condition is true
- else: Runs if the condition is false
- else if: Checks another condition if the previous one is false
- switch: Selects one of many blocks of code to run
- ternary operator: A shortcut for if...else
Examples
// Basic if
let score = 85;
if (score > 80) {
console.log("Great job!");
}
// if...else
let age = 16;
if (age >= 18) {
console.log("You can vote.");
} else {
console.log("You are too young to vote.");
}
// if...else if...else
let time = 14;
if (time < 12) {
console.log("Good morning!");
} else if (time < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
// switch statement
let color = "blue";
switch (color) {
case "red":
console.log("Color is red");
break;
case "blue":
console.log("Color is blue");
break;
default:
console.log("Color not recognized");
}
// ternary operator
let isLoggedIn = true;
let message = isLoggedIn ? "Welcome back!" : "Please log in.";
console.log(message);
Real Example
<script>
let temperature = 30;
if (temperature > 35) {
alert("It’s really hot outside!");
} else if (temperature > 20) {
alert("Nice weather.");
} else {
alert("It’s a bit cold.");
}
</script>
JavaScript Loops
Loops are used to repeat a block of code multiple times. They help reduce repetition and make
code more efficient.
1. for Loop
Used when you know how many times to loop.
// For loop
for (let i = 1; i <= 5; i++) {
console.log("Count:", i);
}
2. while Loop
Runs as long as the condition is true. Good when the number of iterations is not known
beforehand.
// While loop
let x = 1;
while (x <= 3) {
console.log("While Loop:", x);
x++;
}
3. do...while Loop
Runs the code block once before checking the condition. It always runs at least once.
// Do...while loop
let y = 1;
do {
console.log("Do While Loop:", y);
y++;
} while (y <= 2);
4. for...of Loop
Used to loop through the values in an iterable (like arrays, strings, etc.).
// For...of loop
let fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
console.log("Fruit:", fruit);
}
5. for...in Loop
Used to loop through the properties (keys) of an object.
// For...in loop
let user = { name: "Alex", age: 20 };
for (let key in user) {
console.log(key + ":", user[key]);
}
Real Example
<script>
let colors = ["red", "green", "blue"];
let list = "";
for (let i = 0; i < colors.length; i++) {
list += colors[i] + " ";
}
alert("Colors: " + list);
</script>
JavaScript Functions
A function is a block of reusable code that performs a specific task. Functions
help break code into smaller, manageable pieces.
Why Use Functions?
- Write code once and reuse it.
- Keep your code organized and clean.
- Make large programs easier to manage.
Function Structure
function functionName(parameters) {
// code to run
}
1. Declaring and Calling a Function
Create a function using function, and then call it by its name followed by
().
// Declare the function
function greet() {
console.log("Hello there!");
}
// Call the function
greet();
2. Function with Parameters
You can pass values into a function using parameters (placeholders).
function greetUser(name) {
console.log("Hello, " + name + "!");
}
greetUser("Alex"); // Hello, Alex!
3. Function with Return Value
Use return to send a value back from a function.
function add(a, b) {
return a + b;
}
let sum = add(5, 3); // sum is 8
console.log(sum);
4. Function Expression
You can also assign a function to a variable.
const multiply = function(x, y) {
return x * y;
};
console.log(multiply(4, 3));
5. Arrow Functions (Shorter Syntax)
Arrow functions are shorter versions of function expressions.
const square = (n) => {
return n * n;
};
console.log(square(5));
6. Real Example
Calculate area of a rectangle:
<script>
function getArea(width, height) {
return width * height;
}
let area = getArea(10, 5);
alert("Area is " + area);
</script>
Tips for Beginners
- Always start with
function keyword (unless using arrow functions).
- You can create multiple functions and call them as needed.
- Parameters are like input; return gives output.
- Try to write small, focused functions for one task only.
JavaScript Arrays & Array Methods
An array is a list of items stored in a single variable. It's useful when you
want to group similar data.
1. Creating Arrays
let fruits = ["apple", "banana", "orange"];
let numbers = [1, 2, 3, 4, 5];
2. Accessing Items
Array items start at index 0.
console.log(fruits[0]); // "apple"
3. Changing Items
fruits[1] = "mango";
console.log(fruits); // ["apple", "mango", "orange"]
4. Adding & Removing Items
fruits.push("grape"); // Add at end
fruits.pop(); // Remove last
fruits.unshift("kiwi"); // Add at beginning
fruits.shift(); // Remove first
5. Looping Through Arrays
fruits.forEach(function(fruit) {
console.log(fruit);
});
Array Methods (React Favorites)
1. map()
map() creates a new array by transforming each item.
let nums = [1, 2, 3];
let doubled = nums.map(n => n * 2);
console.log(doubled); // [2, 4, 6]
2. filter()
filter() creates a new array with only items that match a condition.
let nums = [1, 2, 3, 4, 5];
let even = nums.filter(n => n % 2 === 0);
console.log(even); // [2, 4]
3. find()
find() returns the first item that matches a condition.
let users = [
{ name: "Alice", age: 20 },
{ name: "Bob", age: 25 }
];
let found = users.find(user => user.age === 25);
console.log(found); // { name: "Bob", age: 25 }
4. includes()
includes() checks if an item exists in an array.
let colors = ["red", "blue", "green"];
console.log(colors.includes("blue")); // true
5. reduce()
reduce() turns an array into a single value (like sum).
let prices = [10, 20, 30];
let total = prices.reduce((sum, price) => sum + price, 0);
console.log(total); // 60
Bonus: Chaining Methods
let result = [1, 2, 3, 4, 5]
.filter(n => n % 2 === 0)
.map(n => n * 10);
console.log(result); // [20, 40]
Why this matters for React
map() is used to render lists of components.
filter() and find() help handle dynamic data.
includes() is used for checking selections.
reduce() is helpful for totals, scores, etc.
JavaScript Objects
An object is a collection of key-value pairs (properties). It's used to store
related data and functions in a structured way.
1. Creating an Object
const person = {
name: "Alice",
age: 25,
isStudent: true
};
2. Accessing Properties
You can access values using dot . or bracket [] notation:
console.log(person.name); // "Alice"
console.log(person["age"]); // 25
3. Changing & Adding Properties
person.age = 26; // Change
person.city = "New York"; // Add
console.log(person);
4. Deleting a Property
delete person.isStudent;
5. Nested Objects
Objects can hold other objects as values.
const user = {
name: "Bob",
address: {
city: "Kathmandu",
zip: 44600
}
};
console.log(user.address.city); // "Kathmandu"
6. Object Destructuring
Destructuring lets you extract values from an object easily.
const person = {
name: "Alice",
age: 25,
city: "Pokhara"
};
// Destructure properties
const { name, age } = person;
console.log(name); // "Alice"
console.log(age); // 25
7. Nested Destructuring
const user = {
name: "Bob",
address: {
city: "Birgunj",
zip: 44300
}
};
const { address: { city } } = user;
console.log(city); // "Birgunj"
Bonus: Object in Arrays (Common in React)
const people = [
{ name: "Ram", age: 22 },
{ name: "Sita", age: 28 }
];
people.forEach(person => {
console.log(person.name + " is " + person.age + " years old.");
});
Why this matters in React: You'll often deal with objects (like user data, form
state, API responses), and destructuring makes your code clean and readable!
DOM Manipulation
DOM (Document Object Model) manipulation is how JavaScript interacts with and updates HTML
elements on a page.
You can select elements, change their content or style, add/remove elements, and handle events.
Selecting Elements
document.getElementById("id") – Select by ID
document.querySelector("selector") – Select first match
document.querySelectorAll("selector") – Select all matches
document.getElementsByClassName("class") – Old method (HTMLCollection)
document.getElementsByTagName("tag") – Old method (HTMLCollection)
Example HTML
<h1 id="title">Original Title</h1>
<p id="info">Some info</p>
<div class="box">Box content</div>
<ul><li>Item 1</li></ul>
<button id="myBtn">Click Me</button>
Changing Content
// Change text
document.getElementById("title").textContent = "Hello!";
// Change HTML
document.getElementById("info").innerHTML = "<strong>Updated!</strong>";
Changing Styles
const box = document.querySelector(".box");
box.style.backgroundColor = "skyblue";
box.style.padding = "20px";
Creating & Appending Elements
const newItem = document.createElement("li");
newItem.textContent = "New list item";
document.querySelector("ul").appendChild(newItem);
Removing Elements
const item = document.querySelector("li");
item.remove();
Event Listeners
const btn = document.getElementById("myBtn");
btn.addEventListener("click", function () {
alert("Button clicked!");
});
DOM: Styling & Element Manipulation
JavaScript can change the appearance and structure of your web page by modifying styles,
classes, IDs, and HTML elements.
1. Changing Inline Styles
const box = document.getElementById("myBox");
// Add or update styles
box.style.backgroundColor = "lightblue";
box.style.padding = "1rem";
// Remove a style
box.style.backgroundColor = "";
<div id="myBox">Styled Box</div>
2. Working with Classes
const btn = document.querySelector("button");
// Add a class
btn.classList.add("active");
// Remove a class
btn.classList.remove("active");
// Toggle a class (add if not present, remove if present)
btn.classList.toggle("highlight");
// Check if a class exists
console.log(btn.classList.contains("active"));
<button>Click Me</button>
3. Changing or Removing ID
const el = document.querySelector(".card");
// Change ID
el.id = "newId";
// Remove ID
el.removeAttribute("id");
4. Creating and Appending Elements
// Create a new element
const newPara = document.createElement("p");
newPara.textContent = "This is a new paragraph";
// Append it to a container
const container = document.getElementById("content");
container.appendChild(newPara);
<div id="content"></div>
5. Removing Elements
const unwanted = document.getElementById("removeMe");
unwanted.remove();
<div id="removeMe">Goodbye</div>
Quick Summary
- style.property: Change inline styles.
- classList: Add/remove/toggle classes.
- id: Set or remove element IDs.
- createElement(): Create a new HTML element.
- appendChild(): Add an element into the DOM.
- remove(): Delete an element from the page.
JavaScript Events
Events let you respond to user interactions like clicks, typing, form submissions, and more. In
JavaScript, you can attach "event listeners" to elements and define what should happen when an
event occurs.
Example HTML
<button id="clickBtn">Click Me</button>
<input id="nameInput" type="text" placeholder="Type something..." />
<select id="colorSelect">
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
<form id="myForm">
<input type="text" placeholder="Your name" />
<button type="submit">Submit</button>
</form>
Adding Event Listeners
element.addEventListener("event", functionToCall);
Click Event
document.getElementById("clickBtn").addEventListener("click", function () {
alert("Button was clicked!");
});
Input Event (Typing in Input Field)
document.getElementById("nameInput").addEventListener("input", function (e) {
console.log("You typed:", e.target.value);
});
Change Event (For dropdowns or when input loses focus)
document.getElementById("colorSelect").addEventListener("change", function (e) {
console.log("Selected color:", e.target.value);
});
Submit Event (On Forms)
document.getElementById("myForm").addEventListener("submit", function (e) {
e.preventDefault(); // Prevents page reload
console.log("Form submitted!");
});
Mouse Events
click, dblclick, mouseover, mouseout,
mousemove
Keyboard Events
keydown: Fires when any key is pressed down
keyup: Fires when the key is released
ES6 Features (Modern JavaScript)
ES6 (ECMAScript 2015) introduced powerful features that make JavaScript easier, cleaner, and
more efficient. These are heavily used in React and modern development.
1. let and const
let: Block-scoped variable (re-assignable)
const: Block-scoped constant (cannot be reassigned)
let count = 0;
const name = "John";
2. Arrow Functions
Simpler function syntax. It also handles this differently.
// Normal function
function greet() {
return "Hello";
}
// Arrow function
const greet = () => "Hello";
3. Template Literals
Use backticks (`) to embed variables directly into strings.
const name = "Alice";
console.log(`Hello, ${name}!`);
4. Destructuring
Extract values from objects or arrays easily.
// Object destructuring
const user = { name: "John", age: 25 };
const { name, age } = user;
// Array destructuring
const colors = ["red", "green", "blue"];
const [first, second] = colors;
5. Spread Operator ...
Copies all elements or properties into a new array/object.
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]
const user1 = { name: "Sam" };
const user2 = { ...user1, age: 20 };
6. Rest Parameters
Use ... to group extra arguments into an array.
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6
7. Default Parameters
function greet(name = "Guest") {
console.log("Hello " + name);
}
greet(); // Hello Guest
8. Ternary Operator
Short form for if/else.
const age = 18;
const message = age >= 18 ? "Adult" : "Minor";
Async JavaScript: Promises & async/await
JavaScript is single-threaded, but it supports asynchronous behavior (like loading data from a
server) without freezing the whole page. This is done using Promises and
async/await.
1. What is a Promise?
A Promise is a special object that represents a task that will finish in the future (either
success or failure).
- Pending: Not finished yet
- Resolved: Finished successfully
- Rejected: Finished with an error
// Creating a Promise
const myPromise = new Promise((resolve, reject) => {
const success = true;
setTimeout(() => {
if (success) {
resolve("It worked!");
} else {
reject("Something went wrong!");
}
}, 1000);
});
// Consuming the Promise
myPromise
.then(result => console.log("Success:", result))
.catch(error => console.error("Error:", error));
2. Async & Await
async makes a function return a Promise.
await waits for a Promise to finish — and makes the code look synchronous and
clean.
// Simulated async function
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data loaded!");
}, 1500);
});
}
// Using async/await
async function getData() {
console.log("Loading...");
const result = await fetchData();
console.log(result);
}
getData();
3. Error Handling with try...catch
Use try...catch with await to catch errors (just like
.catch with Promises).
async function getUser() {
try {
const user = await fetchUser(); // suppose this returns a Promise
console.log("User:", user);
} catch (err) {
console.error("Failed to get user:", err);
}
}
4. Real Example: Simulate API Fetch
function fakeApiCall() {
return new Promise((resolve) => {
setTimeout(() => resolve("✅ Fetched data from server!"), 2000);
});
}
async function showData() {
console.log("Fetching...");
const result = await fakeApiCall();
console.log(result);
}
showData();
Why Use Async/Await?
- Cleaner and easier than
.then().catch() chains
- Helps avoid "callback hell"
- Looks more like regular top-to-bottom code
Fetch API: Getting Data from the Internet
The fetch() API lets you get data from servers (like REST APIs). It returns a
Promise, so you can use then() or async/await to
handle the response.
1. Basic Fetch with .then()
// Example: Fetch a post from JSONPlaceholder
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(res => res.json()) // convert response to JSON
.then(data => {
console.log('Post title:', data.title);
})
.catch(err => console.error('Error:', err));
2. Same Example Using async/await
async function getPost() {
try {
const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await res.json();
console.log('Post body:', data.body);
} catch (err) {
console.error('Failed to fetch:', err);
}
}
getPost();
3. Making a POST Request (Sending Data)
async function createPost() {
try {
const res = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'Hello!',
body: 'This is a new post.',
userId: 1
})
});
const result = await res.json();
console.log('New post created:', result);
} catch (err) {
console.error('Error creating post:', err);
}
}
createPost();
4. Notes:
fetch() doesn’t reject on HTTP errors (like 404), only on network errors.
- You always need to use
res.json() to read the response data.
- For POST/PUT/PATCH, always set the method and headers, and convert your object using
JSON.stringify().
5. Real Use Case
// Get multiple posts and display titles
async function getPosts() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await res.json();
posts.slice(0, 5).forEach(post => {
console.log(post.title);
});
}
getPosts();
JavaScript Modules: import, export & Code Splitting
JavaScript modules let you split your code into smaller, reusable files. Each file can export
values (like functions or variables), and others can import them. This keeps your code organized
and efficient.
1. Exporting from a Module
You can export things from a file using export.
// utils.js
export const PI = 3.14;
export function add(a, b) {
return a + b;
}
2. Importing from a Module
Use import to bring in values from another file.
// main.js
import { PI, add } from './utils.js';
console.log(PI); // 3.14
console.log(add(5, 3)); // 8
3. Default Export
You can export a single default value from a file.
// math.js
export default function subtract(a, b) {
return a - b;
}
// main.js
import subtract from './math.js';
console.log(subtract(10, 3)); // 7
4. Rename Imports
You can rename an import using as:
import { add as sum } from './utils.js';
console.log(sum(2, 2));
5. What is Code Splitting?
Code splitting means breaking up your code into smaller files that are loaded only when needed —
improving performance. Modern bundlers (like Webpack or Vite) and tools like React.lazy use
modules to make this possible.
Example (React-style Lazy Loading)
import React, { Suspense } from "react";
const About = React.lazy(() => import('./About.js'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<About />
</Suspense>
);
}
Important Notes
- Each module is scoped: variables/functions stay inside unless exported.
- Modules only work with a server (or use
type="module" in a browser).
- Code splitting is a performance optimization done by bundlers like Webpack, Vite, etc.
<script type="module" src="main.js"></script>
JavaScript Event Loop
The event loop is a mechanism that allows JavaScript (which runs on a single thread) to handle
asynchronous tasks like setTimeout, fetch, and user events without
blocking the main program. It constantly checks whether the call stack is empty and pulls tasks
from the queue to execute.
How It Works
- Call Stack: Keeps track of the currently running functions. Only one
function can run at a time.
- Web APIs: Provided by the browser (e.g.,
setTimeout,
fetch, DOM Events).
- Callback Queue (Task Queue): Stores async callbacks ready to be executed
once the stack is clear.
- Microtask Queue: Holds promise callbacks and runs before the callback
queue.
- Event Loop: Keeps checking the call stack and pushes queued tasks to it
when it's empty.
Simple Example
console.log("Start");
setTimeout(() => {
console.log("Inside setTimeout");
}, 0);
console.log("End");
Output:
Start
End
Inside setTimeout
Microtask Queue (Promise Example)
console.log("Start");
Promise.resolve().then(() => {
console.log("Promise resolved");
});
console.log("End");
Output:
Start
End
Promise resolved
Why It Matters
- Helps understand why async code doesn’t block the UI.
- Crucial when using
Promises, async/await, fetch(),
and event handlers.
- Gives you better control over execution order.