Start learning step by step
Check your understanding
Prepare for real interviews
Test your skills
JavaScript (JS) is a programming language that makes your website interactive and dynamic.
/* Example: Show alert */
<script>
alert("Hello, JavaScript!");
</script>
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 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
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
Functions are reusable blocks of code that perform tasks.
/* Example */
function greet(name){
console.log("Hello " + name);
}
greet("Zohil"); // Output: Hello Zohil
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");
}
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++;
}
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);
}
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
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>
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>
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 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 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
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 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]
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
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
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
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
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
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();
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
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 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!
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));
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();
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));
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);
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
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
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
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
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
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>
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
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
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);
Use console.log, debugger, and browser DevTools to debug your code.
/* Example */ let numbers = [1,2,3,4,5]; for(let i=0; i β
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>
var, let, or const.
var is function-scoped, let is block-scoped and can be updated, const is block-scoped and cannot be reassigned.
function greet()
{ console.log("Hello!"); }
=>. Example:
const add = (a, b) => a + b;
== checks value equality (performs type coercion), while === checks value and type equality (strict equality).
let arr = [1, 2, 3];
let obj = {name: "John", age: 30};
null represents an intentional empty value, while undefined means a variable has been declared but not assigned a value.
for, while, and do...while.
button.addEventListener("click", doSomething);
var is function-scoped, let and const are block-scoped (only accessible inside {} where they are defined).
getElementById(), getElementsByClassName(), querySelector(), querySelectorAll().
innerHTML returns HTML content including tags, while textContent returns only the text without HTML tags.
element.addEventListener("click", handler).
fetch(url).then(response => response.json()).
async/await is syntax for handling promises more easily. async declares a function, and await pauses execution until the promise resolves.
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.
localStorage stores data permanently, sessionStorage stores data until the tab is closed, and cookies store small amounts of data sent with every HTTP request.
var and function declarations are hoisted (accessible before definition), let and const are not hoisted in the same way.
import and export to share functionality between files.
var is function-scoped, let and const are block-scoped. const cannot be reassigned.
function greet() { console.log("Hello"); }
=>. Example: const add = (a, b) => a + b;
== checks value equality (with type coercion), === checks value and type equality (strict equality).
let arr = [1, 2, 3];
let obj = {name: "John", age: 30};
getElementById(), getElementsByClassName(), querySelector(), and querySelectorAll().
fetch(url).then(response => response.json())
async functions return promises, and await pauses execution until the promise resolves, making asynchronous code easier to read.
export and import statements.
localStorage stores data permanently, sessionStorage stores data until the tab closes, and cookies store small amounts of data sent with HTTP requests.
call invokes a function with a given this and arguments individually, apply uses an array, and bind returns a new function with this bound.
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?