Home
Education
D/L Mode
HTML CSS JavaScript Python SQL Node.js PHP Java C++

Welcome to JavaScript

Start your journey into web development

Lessons

Start learning step by step

Question & Answer

Check your understanding

Interview Asked Questions

Prepare for real interviews

Quiz

Test your skills

πŸ’» JS Lesson 1: Introduction to JavaScript

JavaScript (JS) is a programming language that makes your website interactive and dynamic.

/* Example: Show alert */
<script>
  alert("Hello, JavaScript!");
</script>
    
βœ”

πŸ’» JS Lesson 2: Variables

Variables store data values. Use let, const, or var.

/* Example */
let name = "Zohil";
const age = 20;
var country = "Afghanistan";

console.log(name, age, country);
    
βœ”

πŸ’» JS Lesson 3: Data Types

JS has different data types like Number, String, Boolean, Object, and Array.

/* Example */
let num = 10;          // Number
let name = "Zohil";    // String
let isStudent = true;  // Boolean
let person = {name:"Z", age:20}; // Object
let fruits = ["Apple","Banana"]; // Array
    
βœ”

πŸ’» JS Lesson 4: Operators

Operators perform actions on values: arithmetic, comparison, logical, and assignment.

/* Example */
let a = 10;
let b = 5;

// Arithmetic
console.log(a + b); // 15
console.log(a - b); // 5

// Comparison
console.log(a > b); // true

// Logical
console.log(a > 5 && b < 10); // true

// Assignment
a += 5; // a = 15
    
βœ”

πŸ’» JS Lesson 5: Functions

Functions are reusable blocks of code that perform tasks.

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

greet("Zohil"); // Output: Hello Zohil
    
βœ”

πŸ’» JS Lesson 6: Conditional Statements

Use if, else if, and else to make decisions in your code.

/* Example */
let age = 18;

if(age >= 18){
  console.log("You are an adult");
} else {
  console.log("You are a minor");
}
    
βœ”

πŸ’» JS Lesson 7: Loops

Loops repeat code multiple times. Common types are for, while, and for…of.

/* Example */
// For loop
for(let i=1; i<=5; i++){
  console.log(i);
}

// While loop
let j = 1;
while(j <= 5){
  console.log(j);
  j++;
}
    
βœ”

πŸ’» JS Lesson 8: Arrays

Arrays store multiple values in a single variable.

/* Example */
let fruits = ["Apple","Banana","Orange"];

// Access
console.log(fruits[0]); // Apple

// Add
fruits.push("Mango");

// Remove
fruits.pop();

// Loop through array
for(let fruit of fruits){
  console.log(fruit);
}
    
βœ”

πŸ’» JS Lesson 9: Objects

Objects store related data as key-value pairs.

/* Example */
let person = {
  name: "Zohil",
  age: 20,
  country: "Afghanistan"
};

// Access
console.log(person.name); // Zohil

// Update
person.age = 21;
console.log(person.age); // 21
    
βœ”

πŸ’» JS Lesson 10: Events

Events allow your website to respond to user actions like clicks and keypresses.

/* Example */
<button id="btn">Click Me</button>

<script>
  let button = document.getElementById("btn");
  button.addEventListener("click", function(){
    alert("Button clicked!");
  });
</script>
    
βœ”

πŸ’» JS Lesson 11: DOM Manipulation

The DOM (Document Object Model) allows JavaScript to access and change HTML elements dynamically.

/* Example */
<h1 id="title">Hello</h1>
<button id="changeBtn">Change Text</button>

<script>
let title = document.getElementById("title");
let btn = document.getElementById("changeBtn");

btn.addEventListener("click", function(){
  title.textContent = "Hello, JavaScript!";
});
</script>
    
βœ”

πŸ’» JS Lesson 12: Strings

Strings are sequences of characters. JS provides many methods to manipulate strings.

/* Example */
let name = "Zohil Rahimzai";

console.log(name.length);        // Length of string
console.log(name.toUpperCase()); // Convert to uppercase
console.log(name.toLowerCase()); // Convert to lowercase
console.log(name.includes("Rah")); // true
console.log(name.slice(0,5));     // "Zohil"
    
βœ”

πŸ’» JS Lesson 13: Numbers

JS has numbers and provides methods for math operations.

/* Example */
let a = 10.567;

console.log(Math.round(a));  // 11
console.log(Math.floor(a));  // 10
console.log(Math.ceil(a));   // 11
console.log(a.toFixed(2));   // "10.57"
console.log(Math.random());  // Random number 0-1
    
βœ”

πŸ’» JS Lesson 14: Type Conversion

JS can convert data types automatically or manually.

/* Example */
let num = "123";
console.log(Number(num)); // 123
console.log(String(123)); // "123"
console.log(Boolean(0));  // false
console.log(Boolean(1));  // true
    
βœ”

πŸ’» JS Lesson 15: Template Literals

Template literals allow you to include variables inside strings easily using backticks (`).

/* Example */
let name = "Zohil";
let age = 20;

let message = `Hello ${name}, you are ${age} years old.`;
console.log(message); // Hello Zohil, you are 20 years old.
    
βœ”

πŸ’» JS Lesson 16: Advanced Array Methods

JS arrays have many methods for manipulation like map, filter, and forEach.

/* Example */
let numbers = [1, 2, 3, 4, 5];

// forEach
numbers.forEach(n => console.log(n));

// map (creates new array)
let squares = numbers.map(n => n * n);
console.log(squares); // [1,4,9,16,25]

// filter
let even = numbers.filter(n => n % 2 === 0);
console.log(even); // [2,4]
    
βœ”

πŸ’» JS Lesson 17: Advanced Objects

Objects can have nested properties, methods, and dynamic keys.

/* Example */
let person = {
  name: "Zohil",
  age: 20,
  greet: function(){
    console.log(`Hello, I am ${this.name}`);
  }
};

person.greet(); // Hello, I am Zohil

// Dynamic key
let key = "country";
person[key] = "Afghanistan";
console.log(person.country); // Afghanistan
    
βœ”

πŸ’» JS Lesson 18: Destructuring

Destructuring allows extracting values from arrays or objects easily.

/* Example */
// Array destructuring
let colors = ["Red","Green","Blue"];
let [first, second] = colors;
console.log(first, second); // Red Green

// Object destructuring
let person = {name:"Zohil", age:20};
let {name, age} = person;
console.log(name, age); // Zohil 20
    
βœ”

πŸ’» JS Lesson 19: Spread & Rest Operators

The spread operator ... expands arrays/objects; rest operator collects values into an array.

/* Example */
// Spread
let arr1 = [1,2];
let arr2 = [...arr1,3,4];
console.log(arr2); // [1,2,3,4]

// Rest
function sum(...nums){
  return nums.reduce((a,b) => a+b, 0);
}
console.log(sum(1,2,3,4)); // 10
    
βœ”

πŸ’» JS Lesson 20: Functions Advanced (Arrow Functions & Callbacks)

Arrow functions are shorter syntax, and callbacks let you pass functions as arguments.

/* Example */
// Arrow function
const greet = name => console.log(`Hello ${name}`);
greet("Zohil");

// Callback function
function calculate(a,b, callback){
  return callback(a,b);
}

function add(x,y){ return x+y; }
console.log(calculate(5,3, add)); // 8
    
βœ”

πŸ’» JS Lesson 21: ES6 Modules

ES6 modules allow you to split your code into separate files using export and import.

/* Example: module.js */
export const greet = (name) => {
  console.log(`Hello ${name}`);
};

/* Example: main.js */
import { greet } from './module.js';
greet("Zohil"); // Hello Zohil
    
βœ”

πŸ’» JS Lesson 22: localStorage & sessionStorage

Store data in the browser using localStorage (persistent) or sessionStorage (temporary).

/* Example */
// Save data
localStorage.setItem("name", "Zohil");
sessionStorage.setItem("age", "20");

// Get data
console.log(localStorage.getItem("name")); // Zohil
console.log(sessionStorage.getItem("age")); // 20

// Remove data
localStorage.removeItem("name");
sessionStorage.clear();
    
βœ”

πŸ’» JS Lesson 23: JSON (JavaScript Object Notation)

JSON is a format to store and transfer data. JS can convert objects to JSON and back.

/* Example */
let person = {name:"Zohil", age:20};

// Convert to JSON
let jsonData = JSON.stringify(person);
console.log(jsonData); // '{"name":"Zohil","age":20}'

// Convert JSON to object
let obj = JSON.parse(jsonData);
console.log(obj.name); // Zohil
    
βœ”

πŸ’» JS Lesson 24: try/catch

Use try/catch to handle errors and prevent your program from crashing.

/* Example */
try {
  let result = riskyFunction(); // may throw error
  console.log(result);
} catch(error) {
  console.log("Error occurred: " + error);
} finally {
  console.log("Execution finished");
}
    
βœ”

πŸ’» JS Lesson 25: Error Handling

JS provides built-in errors like ReferenceError, TypeError, and RangeError. You can also create custom errors.

/* Example */
try {
  let x = y; // y is undefined
} catch(error) {
  console.log(error.name); // ReferenceError
  console.log(error.message); // y is not defined
}

// Custom error
function checkAge(age){
  if(age < 18){
    throw new Error("Too young!");
  }
  return "Allowed";
}

console.log(checkAge(15)); // Error: Too young!
    
βœ”

πŸ’» JS Lesson 26: Promises

Promises handle asynchronous operations. They can be pending, fulfilled, or rejected.

/* Example */
let promise = new Promise((resolve, reject) => {
  let success = true;
  if(success){
    resolve("Task completed!");
  } else {
    reject("Task failed!");
  }
});

promise
  .then(result => console.log(result))
  .catch(error => console.log(error));
    
βœ”

πŸ’» JS Lesson 27: Async/Await

Async/Await is a cleaner way to handle asynchronous code instead of chaining then calls.

/* Example */
function delay(ms){
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function greet(){
  console.log("Start");
  await delay(2000);
  console.log("Hello after 2 seconds");
}

greet();
    
βœ”

πŸ’» JS Lesson 28: Fetch API

The Fetch API is used to get data from servers asynchronously.

/* Example */
fetch("https://jsonplaceholder.typicode.com/users")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log("Error:", error));
    
βœ”

πŸ’» JS Lesson 29: setTimeout & setInterval

setTimeout runs code after a delay. setInterval runs code repeatedly at intervals.

/* Example */
// setTimeout
setTimeout(() => {
  console.log("Executed after 2 seconds");
}, 2000);

// setInterval
let count = 0;
let interval = setInterval(() => {
  console.log("Interval count: " + count);
  count++;
  if(count > 3) clearInterval(interval);
}, 1000);
    
βœ”

πŸ’» JS Lesson 30: Event Loop

The Event Loop manages asynchronous tasks in JavaScript, making sure non-blocking code executes properly.

/* Example */
console.log("Start");

setTimeout(() => {
  console.log("Timeout finished");
}, 0);

console.log("End");

// Output order: Start β†’ End β†’ Timeout finished
    
βœ”

πŸ’» JS Lesson 31: Classes

Classes are blueprints for creating objects with properties and methods.

/* Example */
class Person {
  constructor(name, age){
    this.name = name;
    this.age = age;
  }
  greet(){
    console.log(`Hello, my name is ${this.name}`);
  }
}

let zohil = new Person("Zohil", 20);
zohil.greet(); // Hello, my name is Zohil
    
βœ”

πŸ’» JS Lesson 32: Constructor Method

The constructor method initializes new objects created from a class.

/* Example */
class Student {
  constructor(name, grade){
    this.name = name;
    this.grade = grade;
  }
}

let student1 = new Student("Ali", "A");
console.log(student1.name, student1.grade); // Ali A
    
βœ”

πŸ’» JS Lesson 33: Inheritance

Inheritance allows a class to use properties and methods of another class using extends.

/* Example */
class Person {
  constructor(name){
    this.name = name;
  }
  greet(){
    console.log(`Hello, I am ${this.name}`);
  }
}

class Student extends Person {
  constructor(name, grade){
    super(name);
    this.grade = grade;
  }
  showGrade(){
    console.log(`Grade: ${this.grade}`);
  }
}

let ali = new Student("Ali", "A");
ali.greet();      // Hello, I am Ali
ali.showGrade();  // Grade: A
    
βœ”

πŸ’» JS Lesson 34: Modules Advanced

Advanced module usage includes default exports and importing multiple functions or objects.

/* Example: module.js */
export default function greet(name){
  console.log(`Hello ${name}`);
}

export const sayBye = name => console.log(`Bye ${name}`);

/* Example: main.js */
import greet, { sayBye } from './module.js';

greet("Zohil"); // Hello Zohil
sayBye("Zohil"); // Bye Zohil
    
βœ”

πŸ’» JS Lesson 35: DOM Events Advanced

Advanced event handling includes delegation, capturing, and removing listeners.

/* Example */
<ul id="list">
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

<script>
let ul = document.getElementById("list");

// Event delegation
ul.addEventListener("click", function(e){
  if(e.target.tagName === "LI"){
    alert(`You clicked ${e.target.textContent}`);
  }
});
</script>
    
βœ”

πŸ’» JS Lesson 36: Regular Expressions (RegEx)

Regular expressions are patterns to match or search text.

/* Example */
let text = "My email is zohil@example.com";
let regex = /\w+@\w+\.\w+/;

console.log(text.match(regex)); // ["zohil@example.com"]
console.log(regex.test(text));  // true
    
βœ”

πŸ’» JS Lesson 37: Storage Advanced (localStorage & sessionStorage)

Advanced storage: storing objects and JSON in browser storage.

/* Example */
let user = {name:"Zohil", age:20};

// Save object
localStorage.setItem("user", JSON.stringify(user));

// Get object
let storedUser = JSON.parse(localStorage.getItem("user"));
console.log(storedUser.name); // Zohil
    
βœ”

πŸ’» JS Lesson 38: Timers Advanced

Advanced usage of setTimeout and setInterval including stopping timers.

/* Example */
let count = 0;
let interval = setInterval(() => {
  console.log("Count: " + count);
  count++;
  if(count > 5) clearInterval(interval); // stop interval
}, 1000);

setTimeout(() => {
  console.log("Timeout finished after 3 seconds");
}, 3000);
    
βœ”

πŸ’» JS Lesson 39: Debugging

Use console.log, debugger, and browser DevTools to debug your code.

/* Example */
let numbers = [1,2,3,4,5];

for(let i=0; i
    
βœ”

πŸ’» JS Lesson 40: Final Project Example

Combine everything you learned: DOM, events, arrays, objects, storage, and async code.

/* Example: To-Do List App */
<input id="taskInput">
<button id="addBtn">Add</button>
<ul id="taskList"></ul>

<script>
let taskInput = document.getElementById("taskInput");
let addBtn = document.getElementById("addBtn");
let taskList = document.getElementById("taskList");

addBtn.addEventListener("click", () => {
  let task = taskInput.value;
  if(task){
    let li = document.createElement("li");
    li.textContent = task;
    taskList.appendChild(li);
    taskInput.value = "";
  }
});
</script>
    
πŸŽ‰ Congratulations! You have completed all JavaScript lessons!
Keep practicing and building amazing web pages and Applications!

πŸ’‘ JavaScript Questions & Answers

❓ What is JavaScript?
JavaScript is a programming language used to make websites interactive, control browser behavior, and handle dynamic content.
❓ What are variables in JavaScript?
Variables are used to store data values. They can be declared using var, let, or const.
❓ What is the difference between let, const, and var?
var is function-scoped, let is block-scoped and can be updated, const is block-scoped and cannot be reassigned.
❓ What are data types in JavaScript?
JavaScript data types include: Number, String, Boolean, Null, Undefined, Symbol, BigInt, and Object.
❓ What is a function in JavaScript?
A function is a reusable block of code that performs a specific task. Example:
function greet()
{ console.log("Hello!"); }
❓ What is the difference between function declaration and function expression?
Function declarations are hoisted and can be called before they are defined. Function expressions are not hoisted and are usually assigned to variables.
❓ What are arrow functions?
Arrow functions are a shorter syntax for writing functions using =>. Example:
const add = (a, b) => a + b;
❓ What is the difference between == and ===?
== checks value equality (performs type coercion), while === checks value and type equality (strict equality).
❓ What are arrays in JavaScript?
Arrays are ordered collections of values. Example: let arr = [1, 2, 3];
❓ What are objects in JavaScript?
Objects are collections of key-value pairs. Example: let obj = {name: "John", age: 30};
❓ What is the difference between null and undefined?
null represents an intentional empty value, while undefined means a variable has been declared but not assigned a value.
❓ What are loops in JavaScript?
Loops are used to repeat code. Common loops: for, while, and do...while.
❓ What is an event in JavaScript?
Events are actions that occur in the browser, like clicks or keypresses. Example: button.addEventListener("click", doSomething);
❓ What is the difference between var, let, and const scope?
var is function-scoped, let and const are block-scoped (only accessible inside {} where they are defined).
❓ What is the DOM?
The DOM (Document Object Model) is a representation of HTML elements as objects, which JavaScript can manipulate to change the page dynamically.
❓ How do you select elements in the DOM?
Common methods: getElementById(), getElementsByClassName(), querySelector(), querySelectorAll().
❓ What is the difference between innerHTML and textContent?
innerHTML returns HTML content including tags, while textContent returns only the text without HTML tags.
❓ What are JavaScript events listeners?
Event listeners are functions that run when a specific event happens on an element. Example: element.addEventListener("click", handler).
❓ What are JavaScript promises?
Promises are objects that represent the eventual completion (or failure) of an asynchronous operation. Example: fetch(url).then(response => response.json()).
❓ What is async/await in JavaScript?
async/await is syntax for handling promises more easily. async declares a function, and await pauses execution until the promise resolves.
❓ What is the difference between call, apply, and bind?
call invokes a function with a given this and arguments individually. apply uses an array of arguments. bind returns a new function with this bound.
❓ What is the difference between localStorage, sessionStorage, and cookies?
localStorage stores data permanently, sessionStorage stores data until the tab is closed, and cookies store small amounts of data sent with every HTTP request.
❓ What is the difference between synchronous and asynchronous JavaScript?
Synchronous JavaScript executes code line by line, while asynchronous JavaScript can execute operations in the background without blocking the main thread.
❓ What is the difference between var, function hoisting, and let/const?
var and function declarations are hoisted (accessible before definition), let and const are not hoisted in the same way.
❓ What is a closure in JavaScript?
A closure is a function that has access to variables from its outer function even after the outer function has returned.
❓ What are JavaScript modules?
Modules allow you to split code into separate files and use import and export to share functionality between files.

🎯 JavaScript Interview Questions

❓ What is JavaScript?
JavaScript is a programming language used to make websites interactive, manipulate the DOM, and handle dynamic content.
❓ What are the different data types in JavaScript?
JavaScript data types include Number, String, Boolean, Null, Undefined, Symbol, BigInt, and Object.
❓ What is the difference between var, let, and const?
var is function-scoped, let and const are block-scoped. const cannot be reassigned.
❓ What are functions in JavaScript?
Functions are reusable blocks of code that perform specific tasks. Example: function greet() { console.log("Hello"); }
❓ What is the difference between function declaration and function expression?
Function declarations are hoisted and can be called before definition. Function expressions are not hoisted and are often assigned to variables.
❓ What are arrow functions?
Arrow functions are a shorter syntax for functions using =>. Example: const add = (a, b) => a + b;
❓ What is the difference between == and ===?
== checks value equality (with type coercion), === checks value and type equality (strict equality).
❓ What are arrays in JavaScript?
Arrays are ordered collections of values. Example: let arr = [1, 2, 3];
❓ What are objects in JavaScript?
Objects are collections of key-value pairs. Example: let obj = {name: "John", age: 30};
❓ What is the DOM in JavaScript?
The DOM (Document Object Model) represents HTML elements as objects that JavaScript can manipulate dynamically.
❓ How do you select elements in the DOM?
Methods include getElementById(), getElementsByClassName(), querySelector(), and querySelectorAll().
❓ What is event delegation in JavaScript?
Event delegation is a technique where a single event listener is added to a parent element to handle events on its children, improving performance.
❓ What are JavaScript promises?
Promises represent the eventual completion or failure of an asynchronous operation. Example: fetch(url).then(response => response.json())
❓ What is async/await?
async functions return promises, and await pauses execution until the promise resolves, making asynchronous code easier to read.
❓ What is a closure?
A closure is a function that remembers variables from its outer scope even after the outer function has finished executing.
❓ What are JavaScript modules?
Modules allow code to be split into files and shared using export and import statements.
❓ What is the difference between localStorage, sessionStorage, and cookies?
localStorage stores data permanently, sessionStorage stores data until the tab closes, and cookies store small amounts of data sent with HTTP requests.
❓ What is the difference between synchronous and asynchronous JavaScript?
Synchronous code executes line by line, blocking further execution. Asynchronous code runs in the background without blocking the main thread.
❓ What is the difference between call, apply, and bind?
call invokes a function with a given this and arguments individually, apply uses an array, and bind returns a new function with this bound.
❓ How do you make JavaScript code accessible and maintainable?
Use semantic HTML with JS, separate JS from HTML, use clear variable names, comments, consistent code style, and follow best practices for event handling and DOM manipulation.

πŸ“ JavaScript Quiz: Test Your Knowledge

1. What does JS stand for?

2. Which symbol is used for comments in JavaScript?

3. How do you declare a variable in modern JavaScript?

4. Which function is used to display a message in the console?

5. Which operator is used for strict equality comparison?

6. Which method converts a string to a number in JavaScript?

7. How do you create a function in JavaScript?

8. Which keyword is used to define a constant?

9. Which method is used to add an element at the end of an array?

10. Which event occurs when a user clicks on an HTML element?

11. Which array method removes the first element?

12. Which object stores key-value pairs in JavaScript?

13. How do you write an if statement in JavaScript?

14. Which method converts a JSON string into a JavaScript object?

×