1.8K Views

JS106 - Functions Explained

Learn how functions work in JavaScript including declarations, expressions, parameters, return values, and arrow functions.

Functions are one of the most important concepts in JavaScript.
They allow you to group reusable blocks of code and give structure to your programs.

Function Declaration

A function declaration defines a function with a name.

function greet() {
  console.log("Hello");
}
 
greet(); // runs the function

Function With Parameters

Parameters allow you to pass values into a function.

function sayHello(name) {
  console.log("Hello, " + name);
}
 
sayHello("Emre");

A parameter is the variable name inside the function.
An argument is the actual value passed when calling the function.


Returning Values

Functions can return values using the return keyword.

function add(a, b) {
  return a + b;
}
 
let result = add(3, 4); // 7

Once return is executed, the function stops running.


Function Expression

Functions can also be stored in variables.

const multiply = function(x, y) {
  return x * y;
};
 
console.log(multiply(2, 5)); // 10

Function expressions are useful when passing functions as arguments.


Arrow Functions (ES6+)

Arrow functions offer a shorter syntax.

const greet = () => {
  console.log("Hi!");
};

With parameters:

const square = (n) => n * n;

Arrow functions automatically return the expression when written without braces.


Default Parameters

You can assign default values to parameters.

function welcome(name = "Guest") {
  console.log("Welcome, " + name);
}
 
welcome(); // Welcome, Guest
welcome("Emre");

Rest Parameters

Rest parameters gather multiple arguments into an array.

function sum(...numbers) {
  return numbers.reduce((a, b) => a + b, 0);
}
 
console.log(sum(1, 2, 3, 4)); // 10

Higher-Order Functions

A higher-order function is one that takes another function as an argument.

function applyTwice(fn) {
  fn();
  fn();
}
 
applyTwice(() => console.log("Run"));

This is the basis for powerful JS patterns.


Summary

In this lesson, you learned:

  • Function declarations and expressions
  • Parameters and arguments
  • return keyword
  • Arrow functions
  • Default and rest parameters
  • Higher-order functions

In the next lesson, we will explore arrays and objects — the core data structures of JavaScript.