← Back to Chapters

JavaScript Functions

⚙️ JavaScript Functions

✨ Quick Overview

In JavaScript, a function is a reusable block of code that performs a specific task. You can define it once and execute (invoke) it whenever you need. Functions help you:

  • Reuse code instead of repeating it.
  • Organize logic into small, manageable pieces.
  • Work with dynamic data using parameters and return values.
  • Control this context using call(), apply(), and bind().
  • Maintain state and data privacy using closures.

? Key Concepts

  • Function Declaration – uses the function keyword with a name.
  • Function Expression – a function stored in a variable.
  • Arrow Function – shorter syntax, does not bind its own this.
  • Parameters & Arguments – values passed into a function.
  • Return Value – the result that a function sends back using return.
  • call(), apply(), bind() – control how this and arguments are passed.
  • Closures – functions that remember their outer scope.
  • Callbacks – functions passed as arguments to other functions.
  • Hoisting – function declarations are moved to the top at compile time.
  • Anonymous Functions – functions without a name, often used as callbacks.

? Syntax & Theory

Basic Declaration

A typical function declaration looks like this:

? View Code Example
function greet(name) {
  return "Hello, " + name + "!";
}

Parameters & Return

Functions can accept parameters (inputs) and return a value using the return keyword:

? View Code Example
function add(a, b) {
  return a + b;
}

let result = add(4, 6);
console.log(result);
// 10

Function Forms

JavaScript supports multiple ways to define functions:

  • Declaration – hoisted, can be called before definition.
  • Expression – stored in a variable, not hoisted.
  • Arrow Function – shorter syntax, no own this.

? Code Examples: Function Definitions

Here are different ways to define and use functions in JavaScript:

? View Code Example
// Function declaration
function greet(name) {
  return "Hello, " + name + "!";
}

// Function expression
const greet2 = function(name) {
  return "Hi, " + name + "!";
};

// Arrow function (ES6+)
const greet3 = (name) => "Hey, " + name + "!";

// Simple function example
function greetWorld() {
  console.log("Hello, world!");
}

greetWorld();

? Parameters & Default Values

Functions can accept parameters to work with dynamic data and can use default parameters.

? View Code Example
function multiply(a, b) {
  return a * b;
}

console.log(multiply(4, 5));
// 20

// Default parameters
function greet(name = "Guest") {
  return "Welcome, " + name;
}

console.log(greet());
// Welcome, Guest

? call(), apply(), bind()

The methods call(), apply(), and bind() let you control the value of this inside a function.

? View Code Example
function introduce(city) {
  return this.name + " lives in " + city;
}

const person = { name: "Alice" };

// call() - arguments listed one by one
console.log(introduce.call(person, "Paris"));
// Alice lives in Paris

// apply() - arguments passed as an array
console.log(introduce.apply(person, ["London"]));
// Alice lives in London

// bind() - returns a new bound function
const boundIntroduce = introduce.bind(person);
console.log(boundIntroduce("New York"));
// Alice lives in New York

? Closures & Inner Functions

A closure is a function that remembers the environment in which it was created, even after that outer function has finished executing.

? View Code Example
function outer() {
  let count = 0;

  return function inner() {
    count++;
    return count;
  };
}

const counter = outer();
console.log(counter());
console.log(counter());
console.log(counter());

// Function inside another function
function outerFn() {
  function innerFn() {
    console.log("Inner function");
  }

  innerFn();
}

outerFn();

// Function with a loop
function printNumbers(n) {
  for (let i = 1; i <= n; i++) {
    console.log(i);
  }
}

printNumbers(5);

⚡ Arrow, Anonymous & Callback Functions

Arrow functions are concise, anonymous functions are often used as arguments, and callbacks are functions passed into other functions.

? View Code Example
// Arrow functions
const square = (n) => n * n;
console.log(square(7));
// 49

const greetArrow = name => `Hello, ${name}!`;
console.log(greetArrow("Alice"));
// Hello, Alice!

// Anonymous function with setTimeout
setTimeout(function() {
  console.log("This runs after 1 second");
}, 1000);

// Callback function example
function greetUser(name, callback) {
  console.log("Hello, " + name);
  callback();
}

function sayBye() {
  console.log("Goodbye!");
}

greetUser("John", sayBye);

? Function Hoisting

Function declarations are hoisted, so they can be called before they are defined. Function expressions are not hoisted.

? View Code Example
// Function declaration hoisting
sayHello();

function sayHello() {
  console.log("Hi!");
}

// Function expression is NOT hoisted
// sayBye(); // ❌ Error if uncommented
const sayBye = function() {
  console.log("Bye!");
};

? Live Output & Explanation

? What Happens When This Runs?

Consider this small program:

? View Code Example
function add(a, b) {
  return a + b;
}

function printSum(x, y) {
  const total = add(x, y);
  console.log("Sum is:", total);
}

printSum(3, 7);

Step-by-step:

  1. add(a, b) adds two numbers and returns the result.
  2. printSum(x, y) calls add(x, y) and stores the result in total.
  3. console.log("Sum is:", total) prints the result.
  4. Calling printSum(3, 7) outputs: Sum is: 10.

?️ Common Use Cases

  • Validating user input (e.g., checking if a form field is empty).
  • Performing calculations (tax, discounts, totals).
  • Handling events (clicks, key presses, mouse movements).
  • Reusing logic across multiple parts of an application.
  • Working with APIs (processing data returned from a server).

? Tips & Best Practices

  • Give functions meaningful names that describe what they do.
  • Keep functions small and focused on a single task.
  • Use default parameters to avoid undefined arguments.
  • Use call(), apply(), and bind() to control this when needed.
  • Avoid using arrow functions as object methods when you rely on this.
  • Use closures to create private variables and maintain state safely.
  • Prefer pure functions (no side effects) where possible to make code easier to test.

? Try It Yourself

  • Write a function called isEven that takes a number and returns true if it is even, otherwise false.
  • Create a function sumArray that takes an array of numbers and returns their sum.
  • Write a function reverseString that takes a string and returns it reversed.
  • Make a function findMax that returns the largest number from an array.
  • Write a function factorial that returns the factorial of a given number.
  • Create a function capitalizeWords that capitalizes the first letter of each word in a string.
  • Write a function countVowels that counts the number of vowels in a string.
  • Create a function uniqueElements that returns an array with only unique elements from the input array.