Start your journey into web development
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 βπ» 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 usingvar,let, orconst.β What is the difference between let, const, and var?varis function-scoped,letis block-scoped and can be updated,constis 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?nullrepresents an intentional empty value, whileundefinedmeans 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, anddo...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?varis function-scoped,letandconstare 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?innerHTMLreturns HTML content including tags, whiletextContentreturns 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/awaitis syntax for handling promises more easily.asyncdeclares a function, andawaitpauses execution until the promise resolves.β What is the difference between call, apply, and bind?callinvokes a function with a giventhisand arguments individually.applyuses an array of arguments.bindreturns a new function withthisbound.β What is the difference between localStorage, sessionStorage, and cookies?localStoragestores data permanently,sessionStoragestores 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?varand function declarations are hoisted (accessible before definition),letandconstare 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 useimportandexportto 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?varis function-scoped,letandconstare block-scoped.constcannot 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 includegetElementById(),getElementsByClassName(),querySelector(), andquerySelectorAll().β 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?asyncfunctions return promises, andawaitpauses 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 usingexportandimportstatements.β What is the difference between localStorage, sessionStorage, and cookies?localStoragestores data permanently,sessionStoragestores 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?callinvokes a function with a giventhisand arguments individually,applyuses an array, andbindreturns a new function withthisbound.β 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?
- JavaStyle
- JavaScript
- JustScript
- JungleScript
2. Which symbol is used for comments in JavaScript?
- /* comment */
- ## comment
- // comment
- ** comment **
3. How do you declare a variable in modern JavaScript?
- let myVar;
- variable myVar;
- var myVar;
- constVar myVar;
4. Which function is used to display a message in the console?
- alert()
- print()
- log()
- console.log()
5. Which operator is used for strict equality comparison?
- ==
- ===
- =
- !==
6. Which method converts a string to a number in JavaScript?
- String()
- toNumber()
- Number()
- parseString()
7. How do you create a function in JavaScript?
- function: myFunc() {}
- def myFunc() {}
- func myFunc() {}
- function myFunc() {}
8. Which keyword is used to define a constant?
- let
- const
- var
- static
9. Which method is used to add an element at the end of an array?
- push()
- pop()
- shift()
- unshift()
10. Which event occurs when a user clicks on an HTML element?
- onhover
- onchange
- oninput
- onclick
11. Which array method removes the first element?
- pop()
- push()
- shift()
- unshift()
12. Which object stores key-value pairs in JavaScript?
- Array
- Object
- Function
- Set
13. How do you write an if statement in JavaScript?
- if (condition) {}
- if condition then
- if: condition {}
- if condition {}
14. Which method converts a JSON string into a JavaScript object?
- JSON.stringify()
- JSON.parseInt()
- JSON.parse()
- JSON.toObject()
×![]()