A comprehensive guide to JavaScript with detailed explanations, practical examples, and best practices for building interactive websites.
JavaScript is a programming language that adds interactivity to websites. It runs in browsers to control webpage behavior, such as updating content, handling user inputs, and communicating with servers.
It works alongside HTML (structure) and CSS (styling) to create dynamic, user-friendly web experiences.
JavaScript code consists of statements that perform tasks. It uses variables, functions, and logic to manipulate data and interact with users.
console.log("Hello, World!");
let name = "Kanishk";
alert(`Welcome, ${name}!`);
This code logs a message to the console and displays a browser alert with a name.
Variables store data for later use. JavaScript has three ways to declare variables:
var
: Older way, function-scoped, can be redeclared.let
: Block-scoped, can be reassigned, preferred for variables.const
: Block-scoped, cannot be reassigned, used for constants.let age = 25;
const name = "Kanishk";
age = 26; // Works
// name = "John"; // Error: Cannot reassign const
console.log(name, age);
This declares a changeable age
and a fixed name
, then logs them.
JavaScript has several data types to represent different kinds of values:
42
, 3.14
)."Hello"
).true
, false
).[1, 2, 3]
).{name: "Kanishk"}
).null
).undefined
).let num = 100;
let text = "JavaScript";
let isActive = true;
let list = [1, 2, 3];
let person = { name: "Kanishk", age: 15 };
let empty = null;
This shows different data types assigned to variables.
Functions are reusable blocks of code that perform specific tasks. They can take inputs (parameters) and return outputs.
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Kanishk"));
const add = (a, b) => a + b;
console.log(add(5, 3)); // 8
The first example greets a user, while the second adds two numbers using a concise arrow function.
Arrays store ordered lists of data. They come with methods to manipulate the list.
push()
: Adds to the end.pop()
: Removes from the end.shift()
: Removes from the start.unshift()
: Adds to the start.map()
: Transforms each element.let fruits = ["apple", "banana"];
fruits.push("orange");
fruits.pop();
console.log(fruits); // ["apple", "banana"]
let doubled = fruits.map(item => item.toUpperCase());
console.log(doubled); // ["APPLE", "BANANA"]
This adds and removes items from an array and transforms it.
Objects store data as key-value pairs, ideal for structured information.
const user = {
name: "Kanishk",
age: 15,
greet() {
return `Hi, I'm ${this.name}`;
}
};
console.log(user.name); // Kanishk
console.log(user.greet()); // Hi, I'm Kanishk
This creates an object with properties and a method, then accesses them.
Conditionals control program flow based on conditions using if
, else
, or switch
.
let age = 15;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
This checks if a user is an adult or minor based on age.
Loops repeat code until a condition is met. Common types include for
, while
, and forEach
.
for (let i = 0; i < 3; i++) {
console.log(i); // 0, 1, 2
}
let numbers = [1, 2, 3];
numbers.forEach(num => console.log(num));
This demonstrates a for
loop and a forEach
loop for arrays.
The Document Object Model (DOM) lets JavaScript interact with HTML elements.
document.getElementById()
: Selects an element by ID.querySelector()
: Selects by CSS selector.innerHTML
: Changes element content.style
: Modifies CSS styles.const title = document.getElementById("title");
title.innerHTML = "Welcome!";
title.style.color = "blue";
This changes the text and color of an element with ID title
.
Events handle user actions like clicks, keypresses, or mouse movements.
const button = document.querySelector("button");
button.addEventListener("click", () => {
alert("Button clicked!");
});
This shows an alert when a button is clicked.
Asynchronous JavaScript handles tasks like fetching data without blocking the program.
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Success!"), 1000);
});
myPromise.then(result => console.log(result));
async function fetchData() {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
}
These examples show a Promise resolving after 1 second and an async function fetching data.
Use try/catch
to handle errors gracefully.
try {
let data = JSON.parse("invalid json");
} catch (error) {
console.error("Error:", error.message);
}
This catches and logs an error when parsing invalid JSON.
Modules organize code by splitting it into reusable files.
// math.js
export const add = (a, b) => a + b;
// main.js
import { add } from './math.js';
console.log(add(2, 3)); // 5
This exports a function from one file and imports it in another.
ES6 (ECMAScript 2015) introduced modern JavaScript features.
let/const
: Block-scoped variables.Arrow Functions
: Concise function syntax.Destructuring
: Unpack arrays/objects.Template Literals
: String interpolation with `
.Spread/Rest
: Handle arrays/objects dynamically.const [a, b] = [1, 2];
const { name, age } = { name: "Kanishk", age: 15 };
console.log(a, b, name, age); // 1, 2, Kanishk, 15
This demonstrates destructuring to extract values.
JSON (JavaScript Object Notation) is a format for storing and exchanging data.
const jsonString = '{"name": "Kanishk", "age": 15}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // Kanishk
const backToJson = JSON.stringify(obj);
console.log(backToJson);
This converts JSON to an object and back to JSON.
The Fetch API makes HTTP requests to fetch data from servers.
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
This fetches data from an API and logs it, handling errors if they occur.
Write clean, efficient, and maintainable JavaScript with these tips:
let
or const
instead of var
.try/catch
.