An Introduction to Functions in JavaScript

An Introduction to Functions in JavaScript

·

2 min read

Table of contents

In JavaScript, a function is a block of code that can be reused throughout a program. Functions are defined using the function keyword, followed by a name, a set of parameters, and a block of code (the function body). Once a function is defined, it can be called or invoked by using its name followed by parentheses.

Functions can take one or multiple parameters, which are the values passed to the function when it is called. These parameters can be used within the function body to perform calculations or operations. Functions can also return a value, which is the output of the function and can be assigned to a variable or used in an expression.

Functions are used to organize and modularize code, making it more readable, reusable, and maintainable.

Syntax

function name_of_function (param1, param2,...) {
    // javascript statements
    return something;
}

There are also two types of functions in javascript :

  1. Function Declaration: They are defined using the function keyword followed by the function name, and it doesn't require a semi-colon to end the function, it's hoisted and can be called before it is defined.

  2. Function Expression: They are defined by assigning an anonymous function to a variable, they are not hoisted and can be called after the function is defined.

Examples:

Function Declaration:

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

Function Expression:

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

Functions also have some other forms like arrow functions, which are shorter and more concise way to write function expressions.

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

It can also be simplified further if the function only returns a value

Copy codelet add = (a, b) =>  a + b;

You can use them in your program by calling the function by its name and passing the required arguments if any, for example :

Copy codelet result = add(1, 2); // result = 3

Functions provide many benefits in JavaScript such as code reusability, better organization, and separation of concerns.