What is JavaScript?
Learn how JavaScript powers interactivity, logic, and dynamic behavior on every modern website.
Understanding JavaScript
JavaScript (JS) is the programming language of the web. While HTML provides structure and CSS handles styling, JavaScript adds behavior and interactivity. From toggling menus and validating forms to building full applications, JavaScript runs directly in the browser — no installation needed.
Core Concepts
Variables
Variables store data. Modern JS uses let and const instead of the older var.
let name = "Suraj"; const age = 22; let isStudent = true;
Functions
Functions are reusable blocks of code. Arrow functions (=>) are the modern shorthand.
// Traditional function
function greet(name) {
return `Hello, ${name}!`;
}
// Arrow function
const greet = (name) => `Hello, ${name}!`;
Arrays & Objects
// Array — ordered collection
const fruits = ["Apple", "Banana", "Cherry"];
// Object — key-value pairs
const user = {
name: "Suraj",
role: "Developer",
skills: ["HTML", "CSS", "JS"]
};
DOM Manipulation
The Document Object Model (DOM) lets JavaScript read and modify HTML elements dynamically:
// Select an element
const title = document.querySelector('h1');
// Change its content
title.textContent = "Hello, World!";
// Add an event listener
title.addEventListener('click', () => {
title.style.color = '#ef4444';
});
Control Flow
// If/Else
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
// Loops
for (let i = 0; i < 5; i++) {
console.log(`Count: ${i}`);
}
// Array methods
const prices = [10, 20, 30];
const doubled = prices.map(p => p * 2);
const total = prices.reduce((sum, p) => sum + p, 0);
Async JavaScript
JavaScript handles asynchronous operations like API calls with Promises and async/await:
// Fetch data from an API
async function getUser() {
const response = await fetch('https://api.example.com/user');
const data = await response.json();
console.log(data.name);
}
🧪 Try It Yourself — Live JavaScript Console
Write JavaScript below and click Run to see the output. Use console.log() to print results.
Best Practices
- Use
constby default;letwhen reassignment is needed - Avoid
var— it has unexpected scoping behavior - Use strict equality (
===) instead of loose equality (==) - Handle errors with try/catch, especially in async code
- Keep functions small and focused on a single task