Functions are reusable blocks of code that perform specific tasks. They help make your code more organized, readable, and maintainable.
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Function expression
const add = function(a, b) {
return a + b;
};
// Arrow function
const multiply = (a, b) => a * b;
// Using the functions
console.log(greet("Alice")); // "Hello, Alice!"
console.log(add(5, 3)); // 8
console.log(multiply(4, 2)); // 8
Variables allow you to store and manage data in your programs. Understanding variable scope and how to use let, const, and var properly is crucial for writing effective JavaScript.
// Variable declarations
let count = 0; // Can be reassigned
const PI = 3.14159; // Cannot be reassigned
var oldWay = true; // Function-scoped (avoid using var)
// Scope demonstration
function demonstrateScope() {
let blockScoped = "I'm only visible in this function";
if (true) {
let innerVariable = "I'm only visible in this block";
console.log(blockScoped); // Works fine
console.log(innerVariable); // Works fine
}
// console.log(innerVariable); // Would cause an error - not defined here
}
// Variable types
let string = "Hello";
let number = 42;
let boolean = true;
let array = [1, 2, 3];
let object = { name: "JavaScript", purpose: "Programming" };
When approaching a new problem, follow these steps: