The Wayback Machine - https://web.archive.org/web/20240906181937/https://www.geeksforgeeks.org/functions-in-javascript/
Open In App

Functions in JavaScript

Last Updated : 13 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A function in JavaScript is a reusable block of code that performs a specific task. You define it once, and then you can run (or “call”) it whenever you need that task done in your program.

A JavaScript function runs when it is “called” by some part of your code.

Syntax: The basic syntax to create a function in JavaScript is shown below.

function functionName(Parameter1, Parameter2, ...)
{
    // Function body
}

To create a function in JavaScript, we have to first use the keyword function, separated by the name of the function and parameters within parenthesis. The part of the function inside the curly braces {} is the body of the function.

In javascript, functions can be used in the same way as variables for assignments, or calculations.

Why Functions?

  • Functions can be used multiple times, reducing redundancy.
  • Break down complex problems into manageable pieces.
  • Manage complexity by hiding implementation details.
  • Can call themselves to solve problems recursively.

Function Invocation

The function code you have written will be executed whenever it is called.

  • Triggered by an event (e.g., a button click by a user).
  • When explicitly called from JavaScript code.
  • Automatically executed, such as in self-invoking functions.

Function Definition

Before, using a user-defined function in JavaScript we have to create one. We can use the above syntax to create a function in JavaScript.

A function definition is sometimes also termed a function declaration or function statement. Below are the rules for creating a function in JavaScript:

  • Every function should begin with the keyword function followed by,
  • A user-defined function name that should be unique,
  • A list of parameters enclosed within parentheses and separated by commas,
  • A list of statements composing the body of the function enclosed within curly braces {}.

Example: This example shows a basic declaration of a function in javascript.

JavaScript
function calcAddition(number1, number2) { 
    return number1 + number2; 
}
console.log(calcAddition(6,9));

Output
15

In the above example, we have created a function named calcAddition, 

  • This function accepts two numbers as parameters and returns the addition of these two numbers.
  • Accessing the function with just the function name without () will return the function object instead of the function result.

There are three ways of writing a function in JavaScript:

Function Declaration: It declares a function with a function keyword. The function declaration must have a function name.

Syntax:

function geeksforGeeks(paramA, paramB) {
    // Set of statements
}

Function Expression

It is similar to a function declaration without the function name. Function expressions can be stored in a variable assignment. 

Syntax:

let geeksforGeeks= function(paramA, paramB) {
    // Set of statements
}

Example: This example explains the usage of the Function expression.

JavaScript
const square = function (number) {
      return number * number;
};
const x = square(4); // x gets the value 16
console.log(x);

Output
16

Functions as Variable Values

Functions can be used the same way as you use variables.

Example:

// Function to convert Fahrenheit to Celsius
function toCelsius(fahrenheit) {
    return (fahrenheit - 32) * 5/9;
  }
  
  // Using the function to convert temperature
  let temperatureInFahrenheit = 77;
  let temperatureInCelsius = toCelsius(temperatureInFahrenheit);
  let text = "The temperature is " + temperatureInCelsius + " Celsius";

Arrow Function:

Arrow Function is one of the most used and efficient methods to create a function in JavaScript because of its comparatively easy implementation. It is a simplified as well as a more compact version of a regular or normal function expression or syntax.

Syntax:

let function_name = (argument1, argument2 ,..) => expression

Example: This example describes the usage of the Arrow function.

JavaScript
const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];

const a2 = a.map(function (s) {
    return s.length;
});

console.log("Normal way ", a2); // [8, 6, 7, 9]

const a3 = a.map((s) => s.length);

console.log("Using Arrow Function ", a3); // [8, 6, 7, 9]

Output
Normal way  [ 8, 6, 7, 9 ]
Using Arrow Function  [ 8, 6, 7, 9 ]

Function Parameters

Till now, we have heard a lot about function parameters but haven’t discussed them in detail. Parameters are additional information passed to a function. For example, in the above example, the task of the function calcAddition is to calculate the addition of two numbers. These two numbers on which we want to perform the addition operation are passed to this function as parameters. The parameters are passed to the function within parentheses after the function name and separated by commas. A function in JavaScript can have any number of parameters and also at the same time, a function in JavaScript can not have a single parameter.

Example: In this example, we pass the argument to the function.

JavaScript
function multiply(a, b) {
    b = typeof b !== "undefined" ? b : 1;
    return a * b;
}

console.log(multiply(69));

Output
69

Calling Functions

After defining a function, the next step is to call them to make use of the function. We can call a function by using the function name separated by the value of parameters enclosed between the parenthesis and a semicolon at the end. The below syntax shows how to call functions in JavaScript:

Syntax:

functionName( Value1, Value2, ..);

Example: Below is a sample program that illustrates the working of functions in JavaScript: 

JavaScript
function welcomeMsg(name) {
    return ("Hello " + name + " welcome to GeeksforGeeks");

}

// creating a variable
let nameVal = "Admin";

// calling the function
console.log(welcomeMsg(nameVal));

Output
Hello Admin welcome to GeeksforGeeks

Return Statement

There are some situations when we want to return some values from a function after performing some operations. In such cases, we can make use of the return statement in JavaScript. This is an optional statement and most of the time the last statement in a JavaScript function. Look at our first example with the function named as calcAddition. This function is calculating two numbers and then returns the result. 

Syntax: The most basic syntax for using the return statement is:

return value;

The return statement begins with the keyword return separated by the value which we want to return from it. We can use an expression also instead of directly returning the value.

More>>

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.

Functions in JavaScript – FAQs

What is a function in JavaScript?

A function is a reusable block of code designed to perform a particular task. Functions can take inputs, process them, and return a result.

How do you define a function?

Functions can be defined using function declarations or function expressions.

What is a function declaration?

A function declaration defines a function with the specified parameters and code block. The function can be called before it is defined due to hoisting.

What is a function expression?

A function expression defines a function inside an expression. The function can be anonymous and is not hoisted, so it cannot be called before it is defined.

What are arrow functions?

Arrow functions provide a shorter syntax for writing functions. They do not have their own this context and are not hoisted.

Example: const name = (parameters) => { // code to be executed };

How do you call a function?

You call a function by using its name followed by parentheses, which may include arguments.



Previous Article
Next Article

Similar Reads

Difference between Regular functions and Arrow functions
This article discusses the major differences between regular functions and arrow functions. Arrow functions - a new feature introduced in ES6 - enable writing concise functions in JavaScript. While both regular and arrow functions work in a similar manner, there are certain interesting differences between them, as discussed below. Syntax: Regular f
2 min read
JavaScript Course Functions in JavaScript
Javascript functions are code blocks that are mainly used to perform a particular function. We can execute a function as many times as we want by calling it(invoking it). Function Structure: To create a function, we use function() declaration. // Anonymous function function(){ // function...body } // function with a name function displayMessage(){
4 min read
Explore the concept of JavaScript Function Scope and different types of JavaScript Functions
JavaScript is based on functional programming. Therefore, functions are fundamental building blocks of JavaScript. So the function is called first-class citizens in JavaScript. Syntax: Define a functionfunction functionName(parameters) { // SET OF STATEMENTS } Call a functionfunctionName(arguments); The function execution stops when all the stateme
10 min read
Must use JavaScript Array Functions – Part 3
Previous articles: Must use JavaScript Array Functions -Part 1 Must use JavaScript Array Functions -Part 2 In this article, we are going to discuss the following JavaScript array functions prototype.reduce()prototype.concat()prototype.sort()prototype.reverse() JavaScript Array.Prototype.reduce(): Array.prototype.reduce() function is used when the p
5 min read
Array of functions in JavaScript
Given an array containing functions and the task is to access its element in different ways using JavaScript. Approach: Declare an array of functions.The array of functions works with indexes like an array function. Example 1: In this example, the function call is initiated from the element of the array but the function is defined somewhere else. W
2 min read
JavaScript encodeURI(), decodeURI() and its components Functions
Encoding and Decoding URI and URI components is a usual task in web development while making a GET request to API with query params. Many times construct a URL string with query params and in order to understand it, the response server needs to decode this URL. Browsers automatically encode the URL i.e. converts some special characters to other res
3 min read
How to set default parameter value in JavaScript functions ?
In general all the JavaScript functions have a default value of undefined but we can overwrite it by specifying a particular value. This prevents breaking of the code in case of missing inputs. Let us first take a look at a problem and then we'll take a look at how default values for function parameters address that problem. Let's first create a si
2 min read
Higher-Order Arrow Functions in JavaScript
Prerequisite: Arrow Functions A Higher-Order function is a function that receives a function as an argument otherwise returns the function as output. The higher-Order Arrow function implies using arrow functions (in ES6) along with Higher-Order functions. Needs of Higher Order Arrow Function: In a general way, the programmer instructs on how to per
6 min read
Difference between decodeURIComponent() and decodeURI() functions in JavaScript
Both decodeURI() and decodeURIComponent() are Javascript global functions that are used for decoding encoded URI (Uniform Resource Identifier). JavaScript decodeURI() function: It decodes a string previously encoded by the encodeURI() function. It returns a decoded URI by replacing each UTF-8 escape sequence with the characters it represents. Synta
2 min read
How to store JavaScript functions in a queue and execute in that order?
In this article, the task is to execute the functions in the order defined in the queue with the help of JavaScript. There are two approaches that are discussed below. Approach 1: Declare the functions and use the array push() method to push the functions in the array. Later traverse the array and execute the functions one by one. Example: This exa
2 min read
Pure Functions in JavaScript
A Pure Function is a function (a block of code) that always returns the same result if the same arguments are passed. It does not depend on any state or data change during a program’s execution. Rather, it only depends on its input arguments. Also, a pure function does not produce any observable side effects such as network requests or data mutatio
2 min read
How to get the index of the function in an array of functions which executed the fastest in JavaScript ?
In this example, we will learn how to get the index of the function in an array of functions that is executed the fastest in JavaScript. Example: Input: fun[] = [ hello, hello1, hello2 ] Output: index of fastest is 0. Explanation: Function hello execute fastest in all functions. Input: fun[] = [ while1, while2, while3 ] Output: index of fastest fun
4 min read
How to chain asynchronous functions in JavaScript ?
JavaScript is a single-threaded, asynchronous programming language. Thus, some time-consuming operations like I/O, accessing the database, network calls, etc. are performed asynchronously so that it does not interrupt things in the only JS thread. This can be done by asynchronous code like promises or async functions (which basically are cleaner pr
3 min read
Difference between unescape() and escape() functions in JavaScript
In this article, we will learn about the escape() & unescape() functions in JavaScript. We will understand the purpose of using both these functions through the example. Later in this article, we will discuss the difference between escape() & unescape() functions. Let's discuss the escape() function. JavaScript escape() function: This funct
4 min read
What is a typical use case for anonymous functions in JavaScript ?
In this article, we will try to understand what exactly an Anonymous function is, and how we could declare it using the syntax provided in JavaScript further we will see some examples (use-cases) where we can use anonymous functions to get our results in the console. Before proceeding with the examples or use cases of anonymous functions, let's bri
4 min read
Understanding the Difference between Pure and Impure Functions in JavaScript
In this article, we will see the concepts of pure and impure functions in JavaScript, along with understanding their differences, & basic implementation for a better understanding of the concepts. Pure Functions: This function always returns the same output as given the same input parameters. Pure functions only depend on their input parameters
5 min read
All about Functions and Scopes in JavaScript
In this article, we will cover all the basic concepts of JS functions, callbacks, scopes, closures in-depth which would help you to - understand different types of function declarations.make better use of functions.understand how different scopes and scope chain works in JS.learn about closures and how to use them.We will understand all these conce
10 min read
How to find min/max values without Math functions in JavaScript ?
In this article, we will learn how to find the minimum and maximum values in an array without using Math functions. We know that Math.max() returns the maximum number passed in an array whereas Math.min() returns the minimum number passed. Approach: The same functionality of the Math functions can be implemented using a loop that will iterate the n
3 min read
How Inheritance works in Constructor Functions in JavaScript ?
Here, we will discuss inheriting a constructor function in JavaScript. Constructor functions define the prototype of the properties an object will contain. Using the constructor function, we can create a new object after passing the required parameters. Inheriting a previously defined constructor function means using the parameters of the previousl
3 min read
Difference between Anonymous and Named functions in JavaScript
In JavaScript or in any programming language per say, functions, loops, mathematical operators and variables are the most widely used tools. This article will tell you about the difference between anonymous functions and named functions. We will discuss all the required concepts in this article to know the named and anonymous functions in and out.
4 min read
How to make variables private in Constructor functions in JavaScript ?
In Javascript there's no specific way to make variables private in a Constructor function. If a variable is genuinely private, meaning it cannot be accessible from the outside. A constructor is a function that generates a new instance of a class, sometimes referred to as an "object." A constructor's job is to build an object and assign or set value
2 min read
How to pass primitive/object types through functions in JavaScript ?
In this article, we learn how JavaScript primitive/object types passed through functions. First, we will see, what are primitive and object data types in JavaScript: 1. Primitive data type: The predefined data types that are provided by JavaScript are called primitive data type. The primitive data types in JavaScript are: String: A String is a coll
4 min read
How to append new information and rethrowing errors in nested functions in JavaScript ?
In this article, we will see how we may append new information and rethrow errors in nested functions in JavaScript with the help of certain theoretical explanations & understand them through the illustrations. This article is divided into 2 sections, i.e. in the 1st section, we'll understand how to append the new information while throwing an
5 min read
JavaScript Nested functions
In JavaScript, Functions within another function are called “Nested function.” These nested functions have access to the variables and parameters of the outer (enclosing) function, creating a scope hierarchy. A function can have one or more inner functions. Syntax:// Outer function function outerFunction() { // Nested function function nestedFuncti
2 min read
Different ways of writing functions in JavaScript
JavaScript Function is a block of code that is designed to perform a task and executed when it is been called or invoked. Below are the ways of writing functions in JavaScript: Table of Content Function DeclarationFunction ExpressionArrow FunctionsFunction DeclarationFunction Declaration is the traditional way to define a function. It is somehow si
2 min read
Call multiple JavaScript functions in onclick event
To Call multiple JavaScript functions in onclick event, we have different approaches. In this article, we are going to see how to call multiple JavaScript functions in onClick event. Below are the approaches to calling multiple JavaScript functions in onclick event: Table of Content Calling all functions at onceCalling one function that contains re
2 min read
Most useful JavaScript Array Functions – Part 1
In this article, we are going to discuss the following two JavaScript array functions. Both of these functions are widely used in industry and make the JavaScript code clean, modularized, and easy to understand. Array.prototype.every()Array.prototype.some()Array.prototype.every(): This function is used when you need to validate each element of a gi
6 min read
Most useful JavaScript Array Functions – Part 2
In Most useful JavaScript Array Functions – Part 1, we discussed two array functions namely Array.Prototype.Every() and Array.prototype.some(). It is important to note that both of these array functions accessed the array elements but did not modify/change the array itself. Today we are going to look at 2 array methods that modify the array and ret
7 min read
What are factory functions in JavaScript ?
In JavaScript, a factory function is a function that returns an object. It is a way of creating and returning objects in a more controlled and customizable manner. Factory functions are a form of design pattern that enables the creation of objects with specific properties and behaviors. Why it is useful?If we have complex logic, and we have to crea
2 min read
What is the Syntax for Declaring Functions in JavaScript ?
Generally, in JavaScript, the function keyword is used to declare a variable. But, there are some more ways available in JavaScript that can be used to declare functions as explained below: Using function keyword: This is the most common way to declare functions in JavaScript by using the function keyword before the name of the function.Declaring a
1 min read