Warming up the neural circuits...
A function is a reusable block of code that performs a specific task. You define it once and call it whenever you need it.
// Define the function
function greet(name) {
return `Hello, ${name}!`;
}
// Call the function
console.log(greet("Alice")); // "Hello, Alice!"
console.log(greet("Bob")); // "Hello, Bob!"Functions are the building blocks of . Every significant program is built from functions calling other functions.
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5Hoisted — can be called before its definition (more on this later).
const add = function(a, b) {
return a + b;
};
console.log(add(2, 3)); // 5Not hoisted — must be defined before calling.
const add = (a, b) => {
return a + b;
};
// Shorthand: single expression, implicit return
const add = (a, b) => a + b;
//
// Parameters: a and b are named in the definition
function multiply(a, b) {
return a * b;
}
// Arguments: 5 and 3 are the actual values passed
multiply(5, 3); // 15function greet(name = "Guest") {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // "Hello, Alice!"
console.log(greet()); //function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4return StatementEvery function returns a value. If you don't specify return, it returns undefined.
function withReturn() {
return "I have a return value";
}
function withoutReturn() {
const x = 5; // no return statement
}
console.log(withReturn()); // "I have a return value"
console.log(Return exits the function immediately:
function checkAge(age) {
if (age < 18) {
return "Too young"; // exits here
}
return "Welcome!"; // only runs if age >= 18
}Scope determines where a variable is accessible.
const globalVar = "I'm everywhere!";
function test() {
console.log(globalVar); // ✅ accessible
}
console.log(globalVar); // ✅ accessiblefunction test() {
const localVar = "I'm only inside the function";
console.log(localVar); // ✅ accessible
}
console.log(localVar); // ❌ Error! Not defined outsidelet and const only)if (true) {
let blockVar = "I'm scoped to this block";
const alsoBlock = "Me too";
var notBlocked = "I escape the block!"; // var ignores block scope
}
console.log(notBlocked);
function outer() {
const message = "Hello";
function inner() {
console.log(message); // ✅ inner() can access outer()'s variables
}
inner();
}
outer(); // "Hello"A happens when a function "remembers" the variables from its outer scope even after the outer function has finished running.
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); //
The inner function "closes over" the count variable. Even though createCounter() finished, the returned function still has access to count.
// Creating private variables
function createUser(name) {
let password = "";
return {
getName: () => name,
setPassword: (pwd) => { password = pwd; },
checkPassword
JavaScript moves declarations to the top of their scope before execution.
function declarations are hoisted (can be called before definition)sayHello(); // ✅ Works! Function is hoisted
function sayHello() {
console.log("Hello!");
}var is hoisted (but initialized as undefined)console.log(x); // undefined (not Error!)
var x = 5;let and const are hoisted but NOT initialized (Temporal Dead Zone)console.log(y); // ❌ ReferenceError: Cannot access before initialization
let y = 5;Functions can be passed as arguments to other functions:
function processUser(name, callback) {
const message = `Processing ${name}...`;
callback(message);
}
function logMessage(msg) {
console.log(msg);
Arrow functions are commonly used as callbacks:
const numbers = [1, 2, 3, 4, 5];
// Using arrow function as callback
const doubled = numbers.map(n => n * 2);
console.log(doubled
A pure function always returns the same output for the same and doesn't modify anything outside:
// ✅ Pure function
function add(a, b) {
return a + b;
}A function with side effects changes something outside itself:
// ❌ Side effect — modifies an external variable
let total = 0;
function addToTotal(value) {
total += value;
}
// ❌ Side effect — modifies the input
function addTax(item) {
item.price = item
Mistake 1: Forgetting to call the function
function greet() { return "Hello!"; }
console.log(greet); // [Function: greet] — forgot ()
console.log(greet()); // "Hello!" — correctMistake 2: Missing return statement
function double(x) {
x * 2; // ❌ No return!
}
console.log(double(5)); // undefinedMistake 3: Confusing parameters with arguments
function logParams(a, b) {
console.log(a, b);
}
logParams(1, 2, 3, 4); // 1, 2 (extra args ignored, no error)
logParams(1); //let/const have TDZ