This guide explains key JavaScript concepts with short explanations and simple examples.
let & constRule: Use const for fixed values, let for values that may change.
const TAX_RATE = 0.15;
let subtotal = 200;
let total = subtotal + (subtotal * TAX_RATE);
console.log(total); // 230
JavaScript supports numbers, strings, booleans, arrays, and objects.
let student = {
name: "Sara",
age: 19,
active: true,
subjects: ["Math", "CS"]
};
console.log(student.name); // Sara
Use if...else for branching, or the ternary operator for short conditions.
let temperature = 35;
if (temperature > 30) {
console.log("Hot day!");
} else {
console.log("Cool day!");
}
let advice = (temperature > 30) ? "Drink water" : "Wear a jacket";
console.log(advice);
for loops repeat a set number of times, while loops repeat until false.
let colors = ["Red", "Green", "Blue"];
// for loop
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
// while loop
let j = 0;
while (j < colors.length) {
console.log(colors[j]);
j++;
}
Use map() to transform items, filter() to select items, and destructuring to extract values.
let animals = ["Cat", "Dog", "Elephant", "Lion"];
let [first, second] = animals;
console.log(first, second); // Cat Dog
let upper = animals.map(a => a.toUpperCase());
console.log(upper);
let longNames = animals.filter(a => a.length > 3);
console.log(longNames);
Functions make reusable code. Defaults provide fallback values if arguments are missing.
function multiply(a = 2, b = 3) {
return a * b;
}
console.log(multiply(4, 5)); // 20
console.log(multiply()); // 6
Objects group data and actions. JSON.stringify() converts them to text.
let car = {
brand: "Toyota",
year: 2022,
drive() {
console.log(this.brand + " is driving.");
}
};
car.drive();
console.log(JSON.stringify(car));
// {"brand":"Toyota","year":2022}
Use try...catch to handle errors without crashing your program.
function divide(a, b) {
try {
if (b === 0) throw "Cannot divide by zero";
return a / b;
} catch (err) {
return "Error: " + err;
}
}
console.log(divide(10, 2)); // 5
console.log(divide(10, 0)); // Error