In this article, we will be exploring the concept of functions in JavaScript and its various components. Understanding how to create and use functions is a crucial aspect of coding in JavaScript. This article is suitable for those who already have a basic knowledge of JavaScript [Here is my article on
Introduction to JavaScript
, which you might want to check out before going ahead].We will be discussing function syntax, parameters, return statements, function declaration methods, and optional arguments. If you are interested in diving deeper into the language, then by the end of this article, you will have a comprehensive understanding of functions in JavaScript and be equipped with the skills to write efficient, maintainable, and scalable code.
Definition:
A function in JavaScript performs a specific task and allows developers to define reusable blocks of code multiple times. Itโs a powerful tool for organizing and structuring code. Functions can accept parameters, and they can return values. And be nested within other functions. Functions can be used to encapsulate complex logic and make code more readable and maintainable.
Syntax:
function functionName(parameters) {
// code to be executed
}
// To call the function
functionName(parameters);
Where:
functionName
is the name of the function (It can be any valid identifier name).parameters
is an optional list of parameters defined in parenthesis separated by commas, which can be used within the function. Parameters behave like normal variables but their initial values are given by the caller of the function.The code to be executed goes inside the curly braces
{}
.
Example:
Let's see a very basic example of a function:
Where we are going to create a function with a name add
& to perform some operations using +
operator. When we call the function add
, it will give us an addition of two numbers.
function add(value1, value2) {
let addition = value1 + value2;
return addition;
}
let sum1 = add(10, 10);
console.log(sum1);
let sum2 = add(4, 6);
console.log(sum2);
In the above example, we defined a function add
that takes in 2 parameters value1
and value2
and performs the addition of value1
and value2
and stores the result in a variable addition
. Then we called the add
function twice, once with the arguments 10
and 10
, and once the arguments 4
and 6
. And we stored the results of these two calls in the variables sum1
and sum2
, respectively, and then logged into the console.
Checkout the output in Browser's console:
Functions are helpful to reuse when we require the same operation multiple times. Because of it, we don't need to write the same block of code so many times. We can just call a function whenever we need it.
Return Statement:
The return
statement is used to return a value from a function. When a return statement is run, the function stops executing and returns the specified value to the caller.
If a function doesnโt have a return statement, it returns
undefined
.For example: (without
return
statement)function add(value1, value2) { let addition = value1 + value2; } let sum1 = add(10, 10); console.log(sum1);
There is no
return
statement, so this function will not output any result other thanundefined
.But if we add a
return
statement in the function, then we will get the value from the function:For example: (with
return
statement)
Function declaring methods:
In JavaScript, there are three ways to declare a function: function declaration, function expression, and arrow function expression. Each way has its syntax, use cases, and behaviour. We will examine the differences between the 3 ways to declare a function in JavaScript.
Function Declaration:
Function declarations are defined using the function
keyword followed by a name and a pair of parentheses ()
. The code within the curly braces {}
is the body of the function.
Example:
function add(value1, value2) {
let addition = value1 + value2;
return addition;
}
We used the function declaration method to declare a function named add
that takes two arguments, value1
& value2
, performs an addition operation & stores the result in a variable addition
. The function then returns the value of addition
.
Function declarations are hoisted, which means they are accessible throughout the entire code, even though the functions declare below the lines of code that need them. Program control moves them to the top of their scope. They can be available for all the codes in that scope.
For example:
let sum1 = add(10, 10);
console.log(sum1);
function add(value1, value2) {
let addition = value1 + value2;
return addition;
}
In this code, the function declaration function add(value1, value2) {...}
is hoisted to the top of the code, meaning that it's accessible throughout the entire code block, even before it's declared.
Therefore, when the line let sum1 = add(10, 10);
is executed, it can access the function add
without any issues, even though the function definition comes after the function call.
See the output in the image below:
Function Expression:
Function expressions are similar to function declarations, but are assigned to a variable. This way, a function can be stored in a variable and passed as an argument to other functions. Function expressions are not hoisted, meaning that they can only be accessed after they have been declared in the code.
Example:
const add = function (value1, value2) {
let addition = value1 + value2;
return addition;
}
Here we declared the same function from above using the function expression method. The function takes two arguments, value1
& value2
, and performs an addition operation, storing the result in a variable addition
. The function then returns the value of addition
.
Arrow Function Expression:
Arrow functions are a shorthand way of writing functions in JavaScript. The syntax is more concise compared to function expressions.
For example:
const add = (value1, value2) => {
let addition = value1 + value2;
return addition;
}
Now we used the arrow function syntax to define the same function, here arrow comes after the list of parameters and is followed by the function's body.
Points to keep in mind about the arrow function:
Arrow functions are also not hoisted, just like Function expressions.
Arrow functions do not have their own
this
keyword and cannot be used as constructors.If you know more about constructor functions and
this
keyword, you might want to read my other article onObjects in JavaScript
where I have explained everything in detail about them.
Remember when there is a single expression with one parameter, then there is no need for braces and parenthesis.
let add = value => return value + value;
// long syntax:
let add = (value) => {return value + value;};
Note: Do not confuse the arrow function sign
=>
with greater than or equal to>=
.
Optional Arguments in Function:
JavaScript works more smartly when it comes to handling extra arguments or less than required by the function. If we pass too many arguments it will ignore the extra ones and if we do not assign an adequate amount of it, the missing parameters get assigned the value undefined
.
Let's see how this would be helpful:
Example 1:
function add(value1, value2) {
if (value2 === undefined) {
return `There is only one operand ${value1}. Give both to add.`
} else {
return value1 + value2;
}
}
console.log(add(25));
In this example, we declared a function that takes two arguments. The function checks if the second argument is undefined or not. If it's undefined, the function returns a string message "There is only one operand ${value1}. Give both to add."
. If the second argument is not undefined
, the function performs the addition of value1 + value2
& returns the result. The second argument in this case is considered an optional argument and the function still works even if it's not provided.
The outputs would be in Browser's console:
Example 2:
We can define a default value of parameters in case of the argument is not given by the caller of the function:
function add(value1, value2 = 10) {
return value1 + value2;
}
console.log(add(14, 6));
console.log(add(15));
In this example, we have defined a function that takes two parameters. The second parameter value2
has a default value of 10, which means that if no value is passed, it will default to 10. The function then returns the sum of the two values.
First, we logged the result of calling the function with two arguments 14
and 6
which results in 20
.
Next, we logged the result of calling the function with only one argument 15
, in this case, the value of value2
becomes 10
by default and it demonstrates how the default value works.
The outputs would be in Browser's console:
Conclusion:
Functions play a crucial role in JavaScript programming. They allow for the creation of reusable and modular code, making it easier to maintain and debug complex applications. Understanding the different ways to declare functions, pass parameters, and return values is important for writing efficient and effective code. By mastering functions, developers can write code that is both powerful and organized. Whether you are just starting or have been writing JavaScript for years, there is always something new to learn and discover about functions in this versatile language.
A Function is one of the six fundamentals of JavaScript. In this article, we have learned about it. I have also covered the other five fundamentals in my articles individually. You can find them below:
Thank you for reading. Feel free to comment on this, if found it useful.
Happy learning.๐๐๐