JavaScript Functions

Functions are a fundamental concept in JavaScript that allows you to group code into reusable blocks. A function is a set of statements that performs a task or calculates a value.

This section will cover creating, calling, and using functions, including parameters, arguments, return values, and arrow functions.

Functions help in organizing code, making it more modular and reusable. By using functions, you can avoid repeating code, make your programs more readable, and manage complexity.

function greet() {
  console.log('Hello, World!');
}

In this example, greet is a function that prints "Hello, World!" to the console.

You've Already Used Functions

You've already used some built-in functions in JavaScript; here are some examples you might remember:

  • console.log(): A function that prints messages to the console.
  • document.querySelector(): A function that selects an element from the DOM.
  • split(): A method (function associated with an object) splits a string into an array.

These functions are helpful little premade solutions to common problems you might face. So, as you can imagine, wouldn't it be helpful if you could create your helper functions to reuse and solve problems?

Well, after this section, you'll be able to do that.

Creating Functions

Functions are created using the function keyword, followed by a name, a list of parameters enclosed in parentheses, and a block of code enclosed in curly braces:

function sayHello() {
  console.log('Hello!');
}

Calling Functions

Once a function is defined, you can call it by using its name followed by parentheses.

function sayHello() {
  console.log('Hello!');
}

sayHello(); // Outputs: Hello!

Parameters and Arguments

Functions can take parameters, which are variables that act as placeholders for the values that are passed to the function. When you call the function, you provide arguments, which are the actual values for the parameters.

Let's create a function that greets a user by name:

function greet(name) {
  console.log('Hello, ' + name + '!');
}

greet('Alice'); // Outputs: Hello, Alice!
greet('Bob');   // Outputs: Hello, Bob!

In this example, name is a parameter, and 'Alice' and 'Bob' are arguments. We can then use name inside our function as a placeholder for the values passed.

Multiple Parameters

Functions can accept multiple parameters, separated by commas. Let's look at it in action by creating a function that will take two numbers and add them together:

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

add(2, 3); // Outputs: 5
add(5, 7); // Outputs: 12

In this example, a and b are parameters, and 2, 3, 5, and 7 are arguments.

Return Values

Functions can return a value using the return statement. The value can then be used in other parts of the program. There probably isn't a lot of use in just logging things as we have in previous examples, but by being able to get a value from a function, we can start to create groups of reusable logic to use anywhere in our apps:

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

const result = add(2, 3);
console.log(result); // Outputs: 5

In this example, the add function returns the sum of a and b. The return statement stops the function execution and specifies a value to be returned to the function caller.

Functions with No Return Value

If a function does not include a return statement, it returns undefined by default.

function sayHello() {
  console.log('Hello!');
}

const result = sayHello();
console.log(result);

In this example, sayHello does not return a value, so the result is undefined.

Function Expressions

Functions can also be defined using function expressions. In a function expression, a function is created and assigned to a variable.

const greet = function(name) {
  console.log('Hello, ' + name + '!');
};

greet('Alice'); // Outputs: Hello, Alice!

Arrow Functions

Arrow functions provide a more concise syntax for writing functions. They are created using the => (arrow) syntax.

const functionName = (parameters) => {
  // Code to be executed
}

And for a full example:

const greet = (name) => {
  console.log('Hello, ' + name + '!');
};

greet('Alice'); // Outputs: Hello, Alice!

For single-line functions with a single parameter, you can omit the parentheses and curly braces:

const greet = name => console.log('Hello, ' + name + '!');

greet('Bob'); // Outputs: Hello, Bob!

Implicit Return

Arrow functions can implicitly return a value if the function body contains only a single expression. In this case, you can omit the return keyword and the curly braces.

Example:

const add = (a, b) => a + b;

const result = add(2, 3);
console.log(result); // Outputs: 5

In this example, add is an arrow function that implicitly returns the result of a + b.

Explicit Return

If you want to include more than one line of code in the function body or make the return value explicit, use curly braces and the return keyword:

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

const result = add(2, 3);
console.log(result); // Outputs: 5

For clarity, here's another example with a single parameter and implicit return:

Implicit Return Example:

const double = n => n * 2;

const result = double(4);
console.log(result); // Outputs: 8

Explicit Return Example:

const double = n => {
  return n * 2;
};

const result = double(4);
console.log(result); // Outputs: 8

In these examples, double is an arrow function that doubles the input value n. The first example uses an implicit return, while the second uses an explicit one.

Arrow functions make your code more concise and are especially useful for short functions where the abbreviated syntax does not compromise readability.

Function Scope

Scope determines the visibility and accessibility of variables within a function. In the next section, we will examine scope in more detail. But for now, all you need to know is that variables defined inside a function are not accessible outside the function.

Let's look at an example:

function greet() {
  const message = 'Hello, World!';
  console.log(message);
}

greet(); // Outputs: Hello, World!
console.log(message); // Error: message is not defined

In this example, message is defined inside the greet function and is not accessible outside of it. We get an error if we try to access it outside of the function.

Default Parameters

You can assign default values to function parameters. If no argument is provided for a parameter with a default value, the default value is used.

Example:

function greet(name = 'Guest') {
  console.log('Hello, ' + name + '!');
}

greet('Alice'); // Outputs: Hello, Alice!
greet(); // Outputs: Hello, Guest!

In this example, 'Guest' is the default value for the name parameter.

Examples of Functions in Practice

Example: Calculating the Area of a Rectangle

function calculateArea(width, height) {
  return width * height;
}

const area = calculateArea(5, 10);
console.log('Area:', area); // Outputs: Area: 50

Example: Converting Fahrenheit to Celsius

function toCelsius(fahrenheit) {
  return (fahrenheit - 32) * 5 / 9;
}

const celsius = toCelsius(98);
console.log('Celsius:', celsius); // Outputs: Celsius: 36.666666666666664

Example: Finding the Maximum of Two Numbers

function findMax(a, b) {
  if (a > b) {
    return a;
  } else {
    return b;
  }
}

const max = findMax(5, 10);
console.log('Max:', max); // Outputs: Max: 10

Skills to Practice

Now that you have learned about functions, here are some exercises to help you practice and reinforce these new concepts. Try to complete these exercises to understand better how to create, call, and use functions in JavaScript.

  1. Creating Functions: Write a function that prints "Goodbye, World!" to the console.

    • Example: function sayGoodbye() { console.log('Goodbye, World!'); }
  2. Calling Functions: Call the function you just created to see the output.

    • Example: sayGoodbye();
  3. Parameters and Arguments: Create a function that takes a name as a parameter and prints "Goodbye, [name]!" to the console.

    • Example: function sayGoodbye(name) { console.log('Goodbye, ' + name + '!'); }
  4. Multiple Parameters: Write a function that takes two numbers as parameters and prints their sum.

    • Example: function printSum(a, b) { console.log(a + b); }
  5. Return Values: Create a function that takes two numbers and returns their sum.

    • Example: function sum(a, b) { return a + b; }
    • Practice using this function and printing the result: const result = sum(3, 7); console.log(result);
  6. Functions with No Return Value: Write a function that takes a number and prints whether it is even or odd. The function should not return anything.

    • Example: function checkEvenOdd(number) { if (number % 2 === 0) { console.log('Even'); } else { console.log('Odd'); } }
  7. Function Expressions: Convert one of the functions you wrote above into a function expression.

    • Example: const checkEvenOdd = function(number) { if (number % 2 === 0) { console.log('Even'); } else { console.log('Odd'); } };
  8. Arrow Functions: Rewrite one of the functions you wrote above using arrow function syntax.

    • Example: const sum = (a, b) => a + b;
  9. Implicit Return: Create an arrow function that takes a number and returns its square, using implicit return.

    • Example: const square = n => n * n;
    • Practice using this function: const result = square(5); console.log(result);
  10. Explicit Return: Create an arrow function that takes a number and returns its square, using explicit return.

    • Example: const square = n => { return n * n; };
    • Practice using this function: const result = square(5); console.log(result);
  11. Function Scope: Write a function that defines a variable inside it and tries to access that variable outside the function to see the scope behavior.

    • Example:
    function testScope() {
      const message = 'Inside function';
      console.log(message); // Should print 'Inside function'
    }
    testScope();
    console.log(message); // Should give an error
    
  12. Default Parameters: Create a function with a default parameter and call it with and without the argument.

    • Example: function greet(name = 'Guest') { console.log('Hello, ' + name + '!'); }
    • Practice calling this function: greet('Alice'); greet();

Practicing these skills will help you become more comfortable using JavaScript functions.

Functions help you break down complex tasks into smaller, manageable parts, making your code easier to read, maintain, and debug.

Think of functions as small machines. You give them some input (parameters), they do some work (function body), and then they give you some output (return value). Here’s a simple mental model to understand functions:

  1. Input: Parameters are like the ingredients you provide to a recipe.
  2. Processing: The function body is like the instructions in a recipe, telling you what to do with the ingredients.
  3. Output: The return value is like the final dish you get after following the recipe.

In the next section, we will learn about "Scope" in your JavaScript applications.

BeginnerJavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.