Codetainer LogoCodetainer Acad

Lessons

Lesson 20: Functions

🧩 Lesson 20: JavaScript Functions

Functions are like machines in your code. You give them input (called parameters) and they give you output (via return). You can call them over and over again.

πŸ“¦ Function Declaration

This is the most classic way to define a function.


function greet(name) {
  return "Hello, " + name + "!";
}

console.log(greet("Joe")); // Hello, Joe!

πŸ’‘ Function Expression

You can store a function in a variable. This is called a function expression.


const add = function (a, b) {
  return a + b;
};

console.log(add(2, 3)); // 5

⚑ Arrow Functions

Arrow functions are shorter and neater. Great for quick logic, especially in callbacks.


// Basic version
const sayHi = (name) => {
  return "Hi " + name;
};

// Even shorter if one-line
const double = x => x * 2;

console.log(sayHi("Ada"));  // Hi Ada
console.log(double(4));     // 8

😢 Anonymous Functions

Functions without a name. Often used as callbacks.


setTimeout(function () {
  console.log("Hello after 2 seconds");
}, 2000);

βš™οΈ IIFE (Immediately Invoked Function Expression)

A function that runs immediately after it’s defined. Wrapped in parentheses.


(function () {
  console.log("I run immediately!");
})();

πŸ” Callback Functions

Passing a function as an argument to another function. Powerful for async logic, events, etc.


function processUserInput(callback) {
  const name = "Joe";
  callback(name);
}

processUserInput(function (name) {
  console.log("Welcome, " + name);
});

🧠 Parameters vs Arguments

  • Parameters are like placeholders (in the function)
  • Arguments are the actual values you pass in

πŸ› οΈ Default Parameters

You can give parameters a default value in case none is passed.


function greet(name = "friend") {
  return "Hello, " + name;
}

console.log(greet());       // Hello, friend
console.log(greet("Joe"));  // Hello, Joe

πŸ”„ Returning vs Not Returning

Use return to send a result back. If you don’t use it, the function returns undefined.


function add(a, b) {
  return a + b;
}

function logSum(a, b) {
  console.log(a + b);
}

console.log(add(2, 3));    // 5
console.log(logSum(2, 3)); // Logs 5, but returns undefined

πŸš€ Summary

  • Use function to define reusable logic
  • Arrow functions are shorter and neater
  • Functions can take parameters and return results
  • They can be named or anonymous
  • Use IIFE to run logic instantly
  • Functions can be passed as arguments (callbacks)

Functions are the building blocks of logic. In the next lesson, we’ll dive into Selecting Elements in the DOM, the fun part of using Javascript with HTML and CSS.

CodetainerAcad