A JavaScript function is a block of organized, reusable code that is defined to perform a single, relation action. A function is executed when someone calls the function with the name.
Note - I am sharing all my JavaScript Developer Certification study notes here. Please provide your feedback if you see anything wrong or missing. Appreciate your help.
In JavaScript, functions are treated as first-class because they are treated as values. The example of treating function as values are -
- We can assign a function to a variable
- We can store functions in an array
- A function can be passed to another function as an argument
- A function can be assigned to a property of an object.
You can find the video where I have explained everything here. I have also included the video at the end of this post.
Defining a function
A function is defined with the keyword function followed by the name of the function and then the optional functional parameters. Defining a function will not do anything unless you invoke the function. Below code shows a basic example of defining a function and then invoking the same function.
//Defining the function
function sayHello(name) {
console.log("Hello, " + name + " to the world of JavaScript");
}
//invoking the function
sayHello("Shane James");
Function returning value
By default, all functions return value, but in the above example, the return value is undefined. We can define the return and then store the return value in some variable like I have shown in the below example -
function sayHello(name) {
return "Hello, " + name + " to the world of JavaScript";
}
let returnMessage = sayHello("Shane James");
console.log(returnMessage);
Difference between Argument and Parameters
An argument is a value that is being passed to the function while invoking the function.
A parameter is a variable that is listed as part of the function definition.
function sayHello(name) { //name is the function parameter
return "Hello, " + name + " to the world of JavaScript";
}
let returnMessage = sayHello("Shane James"); //"Shane James" is the function argument
console.log(returnMessage);
Why functions are treated as first-class in JavaScript?
As I mentioned before, functions in JavaScript are treated as first-class. We will see some examples below
Assigning a function to a variable
Here I am assigning the function sum to a variable funcSum and then invoking the function.
function sum(num1, num2) {
return num1 + num2;
}
let funcSum = sum;
console.log(funcSum(10, 20));
Store function in an array
Here I am storing the function sum as the third element of the myArray and then invoking the same function by passing the first and second element from the same array.
function sum(num1, num2) {
return num1 + num2;
}
let myArray = [10, 40, sum];
console.log(myArray[2](myArray[0], myArray[1]));
Passing function as an argument to another function
Here I am passing the function innerFunc as an argument to the function outerFunc and then returning another function returnFunc.
function innerFunc(name) {
console.log("Hello " + name);
}
function retunFunc(name) {
return "Bye " + name;
}
function outerFunc(myFunc, name) {
myFunc(name);
return retunFunc(name);
}
let returnVal = outerFunc(innerFunc, "Suidpta Deb");
console.log(returnVal);
Output:
Hello Suidpta Deb
Bye Suidpta Deb
Assigning function to the property of an object
Here I am assigning the function to the property printMessage of the object employee.
var employee = {
name: "Sudipta Deb",
printMessage: function () {
console.log("Welcome " + this.name);
},
};
employee.printMessage();
Arguments Object
Arguments will allow us to re-use the same function with a different set of arguments. In the below example, I am calling the same doSum() method twice, but the number of arguments is different in each scenario. Argument is a special object, which treats the list of arguments in an Array, but it is not having all the methods from Array object available to it. Read the post to understand "JavaScript Array - Everything you need to know".
function doSum() {
let finalSum = 0;
for (let i = 0; i < arguments.length; i++) {
finalSum += arguments[i];
}
console.log("Final Sum: " + finalSum);
}
doSum(100, 200, 300, 400);
doSum(100, 200);
Understand Function Scope
Understanding of function scope is very important as it will explain the life span of variables within a function. I will explain this with some examples -
function sayHi() {
let name = "Sudipta Deb";
}
sayHi();
console.log(name); //ReferenceError
If I execute the above code, I will get ReferenceError. The reason is that the variable name is defied with a function block and thus having function scope. The moment the function execution completes, that variable is no longer available. That is why when I am trying to refer the same variable in console.log, it is throwing me the ReferenceError.
Let's change the function as shown below. This time Hello Sudipta Deb will be printed from the nested function even though the variable is declared outside the nested function. So what happening here is, when the code is trying to refer to the variable name inside the nested function, it is not able to find the variable, so it will try to find the same in the parent function. This process continues until it finds the variable, otherwise, it will show ReferenceError.
function sayHi() {
let name = "Sudipta Deb";
let sayHello = function () {
console.log("Hello " + name);
};
sayHello();
}
sayHi(); //Hello Sudipta Deb
Let's see another example. Here I am using the same variable name in the nested function, but that variable will become out of scope the moment execution of the nested function is over. That is why within the nested function, name is printing different value compared to when name is referenced in outside function.
function sayHi() {
let name = "Sudipta Deb";
let sayHello = function () {
let name = "My name is Sudipta Deb";
console.log("Nested function: " + name); //Nested function: My name is Sudipta Deb
};
sayHello();
console.log("Outside function: " + name); //Outside function: Sudipta Deb
}
sayHi();
But if we override the variable name by not using let inside the nested function, we will get the same result in the both the console statements as shown below -
function sayHi() {
let name = "Sudipta Deb";
let sayHello = function () {
name = "My name is Sudipta Deb";
console.log("Nested function: " + name); //Nested function: My name is Sudipta Deb
};
sayHello();
console.log("Outside function: " + name); //Outside function: My name is Sudipta Deb
}
sayHi();
Understand Block Scope
Block is the portion of the code written in between curly braces i.e. {}. Block scope is the scope of the variables declared within curly braces i.e. within if statement, while statement, for loop, or any set of curly braces other than a function. Note - Variables declared with the var keyword or within function declarations DO NOT have block scope.
Let's go through some examples -
let country = "India";
if (country === "India") {
let capital = "New Delhi";
}
console.log(capital); //ReferenceError: capital is not defined
I will get ReferenceError when trying to access the variable capital. The reason behind this is that capital is defined within the curly braces of the if statement, so the moment execution of if completes, the variable is out of scope.
If I replace the variable declaration from let to var like shown below, I am not getting the error anymore. That means by declaring a variable with var will not associate block scope with that variable and that is the reason to declare a variable with let always and not with var.
let country = "India";
if (country === "India") {
var capital = "New Delhi";
}
console.log(capital); //New Delhi
Now let's modify the code a little bit as shown below -
let country = "India";
let capital = "NA";
if (country === "India") {
let capital = "New Delhi";
console.log(capital); //New Delhi
}
console.log(capital); //NA
This time we are declaring the variable with the same name within the if statement and that is why the console log within the if statement is printing New Delhi, but the moment if statement execution completes, that variable becomes out of scope. That is why the last console log is printing NA, which is the value before the if statement execution started.
To understand the scope in details, please read my post below -
Immediately Invoked Function Expression (IIFE)
Before I start explaining this one, let's understand two key parts -
Function Expression - This means defining a function and then assigning it to a variable.
Immediately Invoked - This means invoking function right away where it's defined.
(function () {
console.log("Hello World"); //Hello World
})();
I hope with this post you have a clear understanding of -
- What functions are in JavaScript?
- How functions are declared and invoked?
- What are function scope and block scope?
- What is "Immediately Invoked Function Expression"?
Video
Further Study
Hello
0 Comments