Understanding the Basics of JavaScript Functions
Functions are another important part of the JavaScript language. They help us bundle a piece of code that performs a single task into a single unit, which we can then invoke as many times and anywhere we want. Functions are called first-class citizens in JavaScript because they can be passed into other functions as values or parameters and can also be returned from a function. There are various types of functions in JavaScript, like callback functions, arrow functions, etc. We'll look into them slowly. So let's start.
Introduction - How create a function
Suppose I want to write a function that will take the age of a person and tell whether he or she is eligible for driving or not.
// this is how we define a function in JavaScript, using function keyword
function canIDrive(age){
//here we are doing conditional checking with if-else
if(age<18) { // if age is less than 18 we return false:boolean
return false;
}
else { // if age is not less than 18 we return true:boolean
return true;
}
}// these braces define the scope of the function (opening and closing braces)
// here we are invoking or calling the function
const result=canIDrive(28) //since the function is returning a value we need to store it
console.log(result);
Now let's break down the code one by one.
function
this keyword is used to declare a function.
function canIDrive(age)
this is called the function definition or function signature. This defines what is the name of the function(canIDrive). What are the parameters that It accepts. They are the inputs that a function takes and performs some operations on it.
(age)
within the first brackets after the name of the functions, you can define any parameters you want. If your function doesn't require any parameter, you can keep it empty like this ()
.
{
The first curly brace defines the opening of function and the }
The last curly brace defines the closing of the function, with in this lies the scope of the function. Your function code needs to be within this bound. The code in this area is often referred to as statements.
Every function returns some value after the code execution, it returns the value to the place from where the function was invoked at first, as you can see in my code I have returned true or false and I have stored the value in const result
. If you want to return some value that your code has calculated you can use return
keyword, it is always the last line of function code, any code after the return statement will be ignored. If it doesn't return anything, there's no need to use the keyword. Often you will also see people use return;
to exit out of the execution of the function, because the return line is always the last, and function execution is terminated after it. This is also a technique often used.
canIDrive(18)
This is how you invoke or call a function. The syntax is simple, function name followed by brackets where you can pass arguments or values that the function accepts or requires. If it doesn't take any argument keep it blank. Here is the syntax once again for you <function Name>(<arguments>)
.
As I have already told if the function returns some value, you can store it by defining a variable in front of the function invocation. As you can see in my code I have written const result = canIDrive(18)
. I have stored the value that canIDrive
the function returns in a const variable named result
. If the function does not return anything then I log the value result. It would give me undefined.
Arguments and parameters
The variables that you define in the function definition are known as function parameters. and when you invoke a function the value that you pass to the variable is known as a function arguments.
Default arguments: Suppose you want that if the user doesn't provide any value for an argument it should not cause any problem, so in that case you can provide default arguments. The syntax is very simple when you define the function definition, for that variable in the parameter you can add a default value by using an =
operator. Just like this.
function greetings(name="guest"){
console.log(`Hello ${name}`);
}
greetings(); // Hello guest
Here if you want, you can pass a name or leave it blank.
How to handle variable arguments
Let's take an example. Suppose you want to create a function that takes in numbers and adds them, the problem is you don't know how many numbers the user will provide. If it is known, you can define as many variables as parameters to handle the number of arguments. But you don't know, so here you can use the rest or spread operator. Here is an example of the function.
function addNumbers(...numbers){
const result = numbers.reduce((total,number)=>{
return total+number;
});
return result;
}
console.log(addNumbers(2,3,4,5,6));
Here, I have created a function named addNumbers
. You can see it has only one parameter, numbers
, but I have used ...
, called the spread or rest operator. This operator allows us to accept as many arguments as we want and stores them in an array. We can then access this array through the numbers
variable. I have used the reduce function (think of it as an enhanced looping mechanism) to access all the values in the numbers
array and add them together to get the result. So this is how you can accept variable arguments in JavaScript function.
Hoisting of functions
In JavaScript, there is a concept of hoisting. You can call the function before it's defined and it will not cause any error. Although hoisting in itself is many folds more than that, for now think of it like this. Here's an example.
myfun();
function myfun(){
console.log("This is the function");
}
// this will execute the function without any error
Hoisting is a very interesting and a very important topic, you can learn more about it here Hoisting.
That's all about the basics of functions. There are topics like scope, Types of functions and hoisting(in depth)that we will cover in the future. I hope you found this short blog helpful. For a deeper understanding, please visit the official documentation. I've tried to provide the basics in a beginner-friendly way. Don't forget to like and share this blog with your fellow learners. For more detailed videos on similar topics, you can follow my Youtube channel and facebook page. Thank you for your time, and I hope I was helpful to you.