DEV Community

Cover image for JavaScript: Your guide to understanding functions.
The daily developer
The daily developer

Posted on

JavaScript: Your guide to understanding functions.

Functions are reusable blocks of code that perform specific tasks. They allow programmers to lessen code repetition and keep their code organized.

Think of Functions as Machines used in a factory, where each machine performs a specific task and together they create a product.

In this article we're going to cover:

  1. Function Declaration
  2. Function expression
  3. Scope and Closure
  4. Arrow Functions
  5. Hoisting
  6. Immediately Invoked function expression or IIFE

Function Declaration

We declare a function by using the reserved keyword function along with a name of your choice and parentheses.

function sayHello() {
}
Enter fullscreen mode Exit fullscreen mode

Consider this syntax the blueprint for functions.

Inside the function, we write a code that will perform a task.

function sayHello(){
  console.log("Hello, I am a Function!");
}
Enter fullscreen mode Exit fullscreen mode

In this example, we created a function named sayHello that prints out "Hello, I am a Function!" to the console after invoking it.

The function above will not output anything to the console at the moment because it has not been invoked.

How do we invoke a function?
We simply call the function by its name followed by parentheses.

function sayHello(){
  console.log("Hello, I am a Function!");
}

sayHello(); // Hello, I am a Function!
Enter fullscreen mode Exit fullscreen mode

Parameters and Arguments

Parameters are placeholders for values that a function can accept when creating it. Arguments are the values passed to the function when invoking it.

 function sayHello(name) {
  console.log(`Hello, I am ${name}`);
}

sayHello("John"); //Hello, I am John
Enter fullscreen mode Exit fullscreen mode

In the example above, the parameter name is a placeholder for the value passed as an argument. You can pass your name for example as an argument to the function and it will print out your name instead of "John".

In Other words, parameters are like blank spaces that expect to be filled with values when you're about to use the function. Arguments are the actual values you want to pass that will replace these blank spaces.

Default parameter

A default parameter is a parameter that was assigned a value when declaring a function. This is useful when a user does not pass an argument to the function. The assigned value of the parameter will act as an argument. Think of it as a backup argument.

function sayHello(name="User"){
  console.log(`Hello, ${name}`);
}

sayHello("John"); // Hello, John
sayHello(); //Hello, User
Enter fullscreen mode Exit fullscreen mode

Rest Parameter and Spread Operator

The rest parameter is important, it helps you pass an unlimited number of parameters to a function instead of using multiple parameters.

Here's an example of a function with multiple parameters:

function names(a,b,c,d,e) {
    console.log(`My students names:, ${a}, ${b}, ${c}, ${d}, ${e}`);
}

names("John", "Jane", "Todd", "Michael", "Lenny");
//My students names:, John, Jane, Todd, Michael, Lenny

Enter fullscreen mode Exit fullscreen mode

This function takes 5 arguments that are the names of students and displays them.
But what if we have more than 5 students?
What if we have 10 or 15 students?
We could give our function 10 or 15 parameters but there's a better way to do it and that is by using the rest operator.

function names(...name) {
    console.log(`My students names: ${name}`);
}

names("John", "Jane", "Todd", "Michael", "Lenny", "Draco", "Harry", "Ginny");
//My students names: John,Jane,Todd,Michael,Lenny,Draco,Harry,Ginny
Enter fullscreen mode Exit fullscreen mode

Return Statement

return is a reserved keyword that will tell the function to stop executing. When return is used inside a function, the function will have a value, otherwise its value will be undefined.

function names(a,b,c,d,e) {
    console.log(`My students names:, ${a}, ${b}, ${c}, ${d}, ${e}`);
}

names("John", "Jane", "Todd", "Michael", "Lenny");

console.log(names("John", "Jane", "Todd", "Michael", "Lenny")); //undefined.
Enter fullscreen mode Exit fullscreen mode

In this example we did not use the return keyword, meaning this function returns a value of undefined. Note that if you want your function to give back a meaningful result please specify a return statement

function sayHello() {
  return "Hello, I am a function";
}

console.log(sayHello()); //Hello, I am a function
Enter fullscreen mode Exit fullscreen mode

Keep in mind the return statement will not print out anything to the console unless console.log() is used.

The return statement can be assigned to variable and used in another part of your code to complete a task. Remember the machine example.

Function expression

A function expression is when you define a function by assigning it to a variable which allow us to use the returned value in other parts of our code.

const calculateRectangleArea = function(width, height) {
    return width * height;
};

const width = 5;
const height = 8;
const area = calculateRectangleArea(width, height);

console.log(`The area of the rectangle is: ${area}`); //The area of the rectangle is: 40
Enter fullscreen mode Exit fullscreen mode

Scope and Closure

When a variable is declared or accessed, the term "scope" is used. It specifies how variables are visible and usable throughout your code. JavaScript has two scope types:

  • Global Scope: global scope variables are declared outside of any function. they are also accessible anywhere inside the code, including functions.
const globalVar = "I'm in the global scope";

function printGlobalVar() {
    console.log(globalVar); 
}

printGlobalVar(); //I'm in the global scope
Enter fullscreen mode Exit fullscreen mode
  • Local Scope: local scope variables are variables declared inside a block of code such as inside a function, or loops which we'll be seeing later in this series.
function greeting() {
    const message = "Hello, from the local scope!";
    console.log(message);
}

greeting(); // Hello, from the local scope!
Enter fullscreen mode Exit fullscreen mode
  • Closures involve a combination of functions that work together. Imagine it as a tiny bubble that wraps around other functions. inside this bubble, All of the bubble's variables and parameters are stored inside of it and can still be used after the outer functions (the bubble) have finished.
function outer() {
    const outerVar = "I'm from the outer function";

    function inner() {
        console.log(outerVar); // inner function has access to outerVar
    }

    return inner;
}

const closureFunction = outer(); // outer function has finished executing, but inner still remembers outerVar
closureFunction(); // Output: "I'm from the outer function"

Enter fullscreen mode Exit fullscreen mode

Arrow functions

Arrow functions make it easy and efficient to define functions. They were first introduced in ES6 and provide a more concise syntax for creating functions than traditional function expressions. In other words it's a shorthand to define a function. Just like a regular function it can also receive parameters. In the body of the arrow function you can omit the curly braces {} and the return statement .

const sum = (a, b) => a+b

console.log(sum(1, 2)); //3
Enter fullscreen mode Exit fullscreen mode

this
if the function has one parameter the parentheses can be omitted

 const printName = (name) => console.log(`My name is: ${name}`);

printName("John");// My name is: John
Enter fullscreen mode Exit fullscreen mode

Hoisting

The concept of hoisting is when function invocations are moved to the top of the source code. This means you can use functions before they are declared in your code.

sayHello(); // Output: "Hello!"
function sayHello() {
    console.log("Hello!");
}
Enter fullscreen mode Exit fullscreen mode

This concept is also applies to variables.

console.log(name); //undefined
let name= "john";
console.log(name);  //john
Enter fullscreen mode Exit fullscreen mode

the first console.log() statement will print undefined, and then the variable is assigned the value of john.

Immediately invoked function expression

Immediately invoked function expression or iife for short is a function that is defined in parentheses that wrap around it and followed by another pair of parentheses that immediately invoke it.

(function() {
    const secretMessage = "This is an iife!";
    console.log(secretMessage);
})(); //This is an iife!
Enter fullscreen mode Exit fullscreen mode

This type of function is used when you want to isolate variables from the outer scope or write modular code without affecting the global scope.

Top comments (0)