Functions in JavaScript

Functions in JavaScript

This article explains functions in JavaScript.

YouTube Video

Functions in JavaScript

Functions in JavaScript are blocks of reusable code used to perform specific tasks. Using functions improves code readability and makes maintenance easier. Functions can be defined in several ways and manipulated flexibly using arguments and return values.

Ways to Define Functions

Function Declaration

Functions can be defined using the function keyword. Function declarations are hoisted before the code runs, so they can be called before they are defined.

1console.log(greet("Everyone")); // Hello, Everyone
2
3function greet(name) {
4    return "Hello, " + name;
5}
6
7console.log(greet("Alice")); // Hello, Alice

In this example, because the greet function is called before its declaration, Hello, Everyone and Hello, Alice are displayed.

Function Expression

Functions can also be defined by assigning them to a variable. In this case, the function is not hoisted and can only be called after it is defined.

1const greet = function(name) {
2    return "Hello, " + name;
3};
4
5console.log(greet("Bob")); // Hello, Bob

In this example, Hello, Bob will be displayed.

Arrow Function

Arrow functions are a way to define functions with a shorter syntax. They are particularly useful when using anonymous functions (functions without a name). Arrow functions also have a different behavior regarding the this keyword.

 1const greet = (name) => {
 2    return "Hello, " + name;
 3};
 4
 5// When it can be expressed in a single line,
 6// `return` and curly braces can be omitted
 7const greetShort = name => "Hello, " + name;
 8
 9console.log(greet("Charlie")); // Hello, Charlie
10console.log(greetShort("Dave")); // Hello, Dave

Functions can be declared as greet and greetShort in this example. If the function is one line, you can omit the {} (curly braces) like greetShort.

Elements of a Function

Arguments

Values passed to a function are called arguments. By specifying arguments when defining a function, you can pass values when calling the function.

1function add(a, b) {
2    return a + b;
3}
4
5console.log(add(2, 3)); // 5

Default Arguments

You can specify a default value if no value is passed to the arguments.

1function greet(name = "Guest") {
2    return "Hello, " + name;
3}
4
5console.log(greet()); // Hello, Guest
6console.log(greet("Alice")); // Hello, Alice

In this example, if greet() is called, the default Guest is used.

Return Value

You can return a return value from a function using the return statement. If there is no return statement, the function returns undefined.

1function greet(name) {
2    console.log('Hello, ' + name + '!');
3}
4function square(num) {
5    return num * num;
6}
7
8console.log(square(4)); // 16
9console.log(greet('Alice')); // undefined

In this example, since greet does not return a value, the return value is undefined.

Anonymous Function

A function without a name is called an anonymous function. They are often used as function expressions or arrow functions.

1const double = function(num) {
2    return num * 2;
3};
4
5console.log(double(5)); // 10

Immediately Invoked Function Expression (IIFE)

An Immediately Invoked Function Expression (IIFE) is a function that is executed as soon as it is defined. It is usually used to control scope.

1/* Example of IIFE: Immediately Invoked Function Expression */
2(function() {
3    console.log("This is an IIFE");
4})(); // This is an IIFE

It is executed as soon as it is declared.

Callback Function

Passing a function as an argument to another function, for later execution, is called a callback function. It is frequently used in asynchronous processing and event handling.

1function processData(callback) {
2    let data = "Processed Data";
3    callback(data);
4}
5
6processData(function(result) {
7    console.log(result); // Processed Data
8});

In this example, a function that outputs a value to the console is passed as a callback function.

Recursive Function

Calling a function itself is called recursion, and a function that performs repetitive processing using this is called a recursive function. For example, a function to calculate a factorial can be implemented using recursion as follows.

 1function factorial(n) {
 2    if (n === 0) {
 3        return 1;
 4    } else {
 5        return n * factorial(n - 1);
 6    }
 7}
 8
 9console.log(factorial(5));
10// Output : 120
11// (5 * 4 * 3 * 2 * 1 = 120)

In this example, the factorial of 5, which is 120, will be displayed.

this Keyword

The this used inside a function indicates which object the function is referring to. In a regular function, it refers to the calling object, but in arrow functions, it retains the this of the scope in which it was defined.

 1const obj = {
 2    name: "Alice",
 3    greet: function() {
 4        console.log(this.name); // Refers to "Alice"
 5    }
 6};
 7
 8obj.greet(); // Alice
 9
10const obj2 = {
11    name: "Bob",
12    greet: () => {
13        // Arrow function refers to the outer scope (undefined here)
14        console.log(this.name);
15    }
16};
17
18obj2.greet(); // undefined

The greet of the obj variable is declared using the function keyword. Therefore, the this keyword refers to the object of the obj variable. On the other hand, the greet of the obj2 variable is declared using an arrow function. Therefore, the this keyword refers to the object in the outer scope and is undefined in this example.

Function Scope and Closures

Variables defined inside a function cannot be accessed from outside the function. This is called function scope. There is also a feature called closure that retains the scope at the point when the function is defined.

 1function outer() {
 2    let outerVar = "I am outer!";
 3
 4    function inner() {
 5        console.log(outerVar); // Can access outerVar
 6    }
 7
 8    return inner;
 9}
10
11const innerFunc = outer();
12innerFunc(); // I am outer!

In this example, the inner function can access the outerVar variable because it retains the scope in which it was defined.

Summary

  • There are various ways to define functions, including function declarations, function expressions, and arrow functions.
  • Functions can take arguments and return values.
  • There are special usages such as callback functions and recursive functions.
  • Care must be taken with the handling of this, as arrow functions and regular functions behave differently.
  • Closures can be used to access internal variables from outside the scope.

Functions are one of the important concepts in JavaScript, leveraging its flexible structure.

You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.

YouTube Video