Functions in JavaScript
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.
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.
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 ,..) => expressionExample: This example describes the usage of the Arrow function.
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.
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:
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.
Functions:
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.

