Functions in JavaScript

Functions are the building blocks of JavaScript programs. They let you write code once and reuse it many times. Think of functions as recipes - you write the instructions once, and then you can follow them whenever you need.

What You'll Learn

  • How to define and call functions
  • Function parameters and return values
  • Different ways to create functions
  • Arrow functions and their syntax

Basic Function Syntax

Here's how to create a simple function:

// Function declaration
function greet() {
  console.log("Hello, World!");
}

// Calling the function
greet();
greet(); // You can call it multiple times

Functions with Parameters

Functions become more useful when they can work with different inputs:

// Function with one parameter
function greetPerson(name) {
  console.log("Hello, " + name + "!");
}

greetPerson("Alice");
greetPerson("Bob");
greetPerson("Charlie");

// Function with multiple parameters
function introduce(name, age) {
  console.log("My name is " + name + " and I am " + age + " years old.");
}

introduce("Alice", 25);
introduce("Bob", 30);

Return Values

Functions can send data back using the return keyword:

// Function that returns a value
function add(a, b) {
  return a + b;
}

// Store the result in a variable
let sum = add(5, 3);
console.log("5 + 3 =", sum);

// Use the result directly
console.log("10 + 20 =", add(10, 20));

// Function with multiple calculations
function calculate(x, y) {
  let sum = x + y;
  let product = x * y;
  return product; // Only the product is returned
}

console.log("Result:", calculate(4, 5));

Function Expressions

You can also create functions and assign them to variables:

// Function expression
const multiply = function(a, b) {
  return a * b;
};

console.log("3 * 4 =", multiply(3, 4));
console.log("5 * 6 =", multiply(5, 6));

Arrow Functions

Modern JavaScript has a shorter syntax for functions called arrow functions:

// Traditional function
function square(x) {
  return x * x;
}

// Arrow function (shorter syntax)
const squareArrow = (x) => {
  return x * x;
};

// Even shorter (one parameter, one expression)
const squareShort = x => x * x;

console.log("Square of 5:", square(5));
console.log("Square of 6:", squareArrow(6));
console.log("Square of 7:", squareShort(7));

// Arrow function with multiple parameters
const add = (a, b) => a + b;
console.log("10 + 15 =", add(10, 15));

Practical Examples

Let's create some useful functions:

// Convert Celsius to Fahrenheit
function celsiusToFahrenheit(celsius) {
  return (celsius * 9/5) + 32;
}

console.log("0°C =", celsiusToFahrenheit(0), "°F");
console.log("25°C =", celsiusToFahrenheit(25), "°F");
console.log("100°C =", celsiusToFahrenheit(100), "°F");

// Check if a number is even
function isEven(number) {
  return number % 2 === 0;
}

console.log("Is 4 even?", isEven(4));
console.log("Is 7 even?", isEven(7));

// Calculate the area of a rectangle
const calculateArea = (width, height) => width * height;

console.log("Area of 5x3 rectangle:", calculateArea(5, 3));
console.log("Area of 10x8 rectangle:", calculateArea(10, 8));

Default Parameters

You can provide default values for parameters:

// Function with default parameter
function greetWithDefault(name = "Guest") {
  console.log("Hello, " + name + "!");
}

greetWithDefault("Alice");  // Uses "Alice"
greetWithDefault();         // Uses default "Guest"

// Multiple default parameters
function createProfile(name = "Anonymous", age = 18) {
  console.log(name + " is " + age + " years old");
}

createProfile("Bob", 25);
createProfile("Charlie");
createProfile();

Try It Yourself

Practice creating functions with these exercises:

// 1. Create a function that doubles a number
function double(num) {
  return num * 2;
}
console.log("Double of 5:", double(5));

// 2. Create a function that greets someone by name
function sayHello(name) {
  console.log("Hello, " + name + "!");
}
sayHello("JavaScript");

// 3. Create an arrow function that finds the maximum of two numbers
const max = (a, b) => a > b ? a : b;
console.log("Max of 10 and 20:", max(10, 20));

// 4. Create a function that calculates the perimeter of a rectangle
function perimeter(width, height) {
  return 2 * (width + height);
}
console.log("Perimeter of 5x3 rectangle:", perimeter(5, 3));

// Try creating your own functions!

Key Takeaways

  • Functions help organize and reuse code
  • Functions can accept parameters (inputs) and return values (outputs)
  • There are multiple ways to create functions: declarations, expressions, and arrow functions
  • Arrow functions (=>) provide a shorter syntax for simple functions
  • Default parameters make functions more flexible

Next Steps

Now that you know how to create functions, you're ready to learn about control flow - how to make decisions and repeat actions in your code using if statements and loops!

Pro Tip: When writing functions, give them clear, descriptive names that explain what they do. A function called calculateTotal is much better than one called calc or x. Good names make your code easier to read and understand!

Functions in JavaScript | LearningJavaScript.org