Introduction
In JavaScript, a function is a block of code that can be executed by calling it by its name. Functions are a fundamental building block in JavaScript and are used to encapsulate and reuse code.
A function is defined using the function keyword, followed by the function name, a set of parentheses, and a block of code within curly braces. Here's an example of a simple function that takes no arguments and returns no value:
function greet() {
console.log("Hello, world!");
}
greet(); //output: "Hello, world!"
To execute the code within a function, you can call the function by its name, followed by a set of parentheses. For example:
function add(a, b) {
return a + b;
}
let result = add(3, 4); // result = 7
Function Declaration
In JavaScript, a function declaration is a way to define a function by using the function keyword, followed by the function name, a set of parentheses, and a block of code within curly braces. The function name is followed by the function keyword, the function parameters are enclosed in parenthesis and the function body is enclosed in curly braces.
Function declarations are hoisted, which means that the JavaScript interpreter moves them to the top of their scope, before any code is executed. This means that you can call a function before it is defined in your code.Here's an example of a simple function declaration:
function greet() {
console.log("Hello, world!");
}
greet(); // Output: "Hello, world!"
In this example, the function greet is defined and declared using the function keyword, and the code block that is executed when the function is called is placed within curly braces.
Function declarations can also take parameters, which allows the function to accept input from the calling code. For example:
function add(a, b) {
return a + b;
}
let result = add(3, 4); // result = 7
In this example, the add function takes two parameters, a and b, and returns the sum of those two values. It's important to note that function declaration should be defined before they are called, otherwise it will throw an error. Function declarations are a common way to define functions in JavaScript and are widely used in the language. They are also easy to understand and use, making them a good choice for many programming tasks.
Function Expression
In JavaScript, a function expression is a way to define a function by assigning it to a variable. It is similar to a function declaration, but instead of using the function keyword, a function expression is assigned to a variable using the assignment operator (=).
Function expressions are not hoisted, which means that the JavaScript interpreter does not move them to the top of their scope before any code is executed. This means that you cannot call a function before it is defined in your code. Here's an example of a simple function expression:
let greet = function() {
console.log("Hello, world!");
}
greet(); // Output: "Hello, world!"
In this example, the function greet is defined and assigned to the variable greet using the assignment operator (=) and the code block that is executed when the function is called is placed within curly braces. Function expressions can also take parameters, which allows the function to accept input from the calling code. For example:
let add = function(a, b) {
return a + b;
}
let result = add(3, 4); // result = 7
In this example, the add function takes two parameters, a and b, and returns the sum of those two values. Function expressions are also often used as callback functions, for example when a function is passed as an argument to another function:
Arrow Function
In JavaScript, an arrow function is a shorthand syntax for defining a function. It is also known as a "fat arrow" function because it uses the "=>" symbol to define the function. Arrow functions were introduced in ECMAScript 6 (ES6) and are considered more concise and easier to read than traditional function expressions or declarations.
Arrow functions have a number of syntax variations depending on the number of arguments and the complexity of the function body. Here's an example of a simple arrow function that takes no arguments and returns a string. For example:
let greet = () => {
return "Hello, world!";
}
console.log(greet()); // Output: "Hello, world!"
In this example, the function greet is defined using an arrow function and the code block that is executed when the function is called is placed within curly braces. Arrow functions can also take parameters and return values:
let add = (a, b) => a + b;
console.log(add(3, 4)); // Output: 7
In this example, the add function takes two parameters, a and b, and returns the sum of those two values. The return statement is implicit, so you don't need to write the return keyword.
Function Declaration VS Function Expression
Function Declaration:
Function Expressions:
These differences influence how functions are defined, used, and hoisted within JavaScript code. Function declarations offer hoisting, allowing them to be called before they're defined, whereas function expressions need to be defined before their usage. Additionally, function expressions provide the flexibility of being anonymous or named.
Function expression And Arrow Function
A function expression is a way of defining a function in JavaScript using the function keyword, such as:
let myFunction = function(parameters) {
// code to be executed
}
An arrow function, also known as a "fat arrow" function, is a shorthand syntax for defining a function in JavaScript and it uses the "=>" symbol, such as:
let myFunction = (parameters) => {
// code to be executed
}
There are some differences between function expression and arrow function, Arrow functions do not have their own this, they use this of the surrounding scope.
In general, arrow functions are shorter and easier to read than function expressions, but they have some limitations. It's a matter of preference which one to use, depending on the specific use case.
Anonymous Function
An anonymous function in JavaScript is a function that is defined without a name. Anonymous functions are often used as arguments for other functions, such as callbacks and event handlers. They can also be assigned to variables and used just like named functions. Here's an example of an anonymous function being assigned to a variable:
let myFunction = function() {
console.log("Hello, world!");
};
myFunction(); // logs "Hello, world!"
Here's an example of an anonymous function being passed as an argument to another function
setTimeout(function() {
console.log("Hello, world!");
}, 1000);
This function will execute after 1 sec of delay. Arrow function also can be used as anonymous function such as
function myFunction(parameters) {
// code to be executed
}
myFunction(arguments);
In general, anonymous functions are used when a function is only needed once and will not be reused elsewhere in the code.
Function invoking
In JavaScript, a function can be invoked or called by using the function's name followed by parentheses, like this:
function myFunction(parameters) {
// code to be executed
}
myFunction(arguments);
The parentheses after the function name are used to pass in any arguments that the function may require. The code inside the function will then execute with the provided arguments.
Functions can also be invoked or called using a function reference, such as a variable that points to the function
let myFunctionReference = myFunction;
myFunctionReference(arguments);
Functions can also be invoked using the call() or apply() methods, which allow you to specify the value of this within the function and pass arguments to the function respectively
myFunction.call(thisValue, arguments);
It's important to note that a function must be defined before it can be invoked. If a function is invoked before it is defined, it will cause an error.
Function calling from other function
In JavaScript, a function can be called from within another function by simply invoking the function by its name, followed by parentheses to include any necessary arguments. For example:
function outerFunction() {
console.log("This is the outer function.");
innerFunction();
}
function innerFunction() {
console.log("This is the inner function.");
}
outerFunction();
In the example above, the outerFunction calls the innerFunction by its name, innerFunction(), and thus the innerFunction is executed.
When the outerFunction is called, it will log "This is the outer function." and then call innerFunction, which will log "This is the inner function."
function as values
In JavaScript, functions are first-class citizens, which means they can be treated like any other value, such as a number or a string. This means that they can be assigned to variables, passed as arguments to other functions, and returned from functions. For example, a function can be assigned to a variable:
let myFunction = function() {
console.log("This is my function.");
};
//It can also be passed as an argument to another function.
function callFunction(func) {
func();
}
callFunction(myFunction);
//It can also be returned from a function.
function returnFunction() {
return function() {
console.log("This function is being returned.");
}
}
let returnedFunction = returnFunction();
returnedFunction();
In the above example, the returnFunction returns an anonymous function that is assigned to the variable returnedFunction, which can then be invoked by invoking returnedFunction();
In JavaScript, functions are also objects, and they have additional properties and methods that can be accessed and used like any other object.
Parameters
In JavaScript, parameters are variables that are used as placeholders for the values that are passed to a function when it is called. These values are known as arguments. When a function is called, the arguments are assigned to the corresponding parameters in the function definition. For example, consider the following function definition:
function add(x, y) {
return x + y;
}
In this example, the function add takes two parameters, x and y. When the function is called, the values passed as arguments are assigned to these parameters, like this
let result = add(5, 3);
In this case, the value 5 is assigned to the parameter x and the value 3 is assigned to the parameter y
arguments
In JavaScript, arguments are the values passed to a function when it is called. These values are assigned to the corresponding parameters in the function definition. For example, consider the following function definition:
function add(x, y) {
return x + y;
}
In this example, the function add takes two parameters, x and y. When the function is called, the values passed as arguments are assigned to these parameters, like this:
let result = add(5, 3);
In JavaScript, arguments are the values passed to a function when it is called. These values are assigned to the corresponding parameters in the function definition. For example, consider the following function definition:
function add(x, y) {
return x + y;
}
In this example, the function add takes two parameters, x and y. When the function is called, the values passed as arguments are assigned to these parameters, like this:
let result = add(5, 3);
In this case, the value 5 is passed as the first argument and the value 3 is passed as the second argument to the function add.
JavaScript also provides the arguments object inside the function, which is an array-like object that contains all the arguments passed to the function
function myFunction() {
console.log(arguments);
}
myFunction(1, "hello", true);
In this example, myFunction is called with three arguments: 1, "hello" and true, and the arguments object inside the function contains [1, "hello", true]
It's worth noting that the arguments object is not an array and it doesn't have array methods like slice, map, filter etc. However, it can be converted to an array using Array.from(arguments) or using spread operator [...arguments]
Arguments Object
In JavaScript, the arguments object is a special object that is available within the scope of all function calls. It contains an array-like collection of the arguments passed to the function. The arguments object allows a function to access the parameters passed to it, even if the function was not defined with a specific number of arguments. This can be useful for creating flexible or reusable functions. However, the arguments object is not an actual Array, and it does not have all of the methods of an Array.
Default Parameter
In JavaScript, default parameters are values that are assigned to a function's parameters if no value is passed to the function when it is called. These default values can be defined in the function's definition, and are used when the function is called without passing any arguments for that parameter. For example, consider the following function definition:
In this example, the function greet takes one parameter, name, which is assigned the default value 'John Doe'. If the function is called without passing an argument for name, it will use the default value. However, if the function is called with an argument for name, that argument will be used instead of the default value:
So, it's a way to assign a default value for a function parameter in case no value is passed to the function during the call.
Passing Arguments: Value vs Veference
In JavaScript, when you pass an argument to a function, the function receives a reference to the value, rather than a copy of the value. This means that when you modify the argument within the function, you are actually modifying the original value. For example, consider the following code:
In this example, the function addFive takes one parameter num and add 5 to it. Here, the variable x is passed as an argument to the function, and the function modifies the value of num to be 15. However, the original value of x remains unchanged.
On the other hand, when passing objects and arrays, the function gets a reference to the original object or array, and any modification made within the function affects the original object or array
In this example, the function addOne takes an array as a parameter and add one element to it. Here, the original array arr is passed as an argument to the function and the function modifies the original array by adding an element to it.
In short, when passing primitive data types (numbers, strings, booleans, etc.) to a function, JavaScript passes the value, which means that the function cannot modify the original value. When passing objects and arrays to a function, JavaScript passes a reference to the original value, which means that the function can modify the original value.
First Class Function
In JavaScript, all functions are first-class citizens, which means they can be treated like any other value, such as a number or string. This means that a function can be:
- Assigned to a variable:
- Passed as an argument to another function:
- Returned as a value from a function
In the first example, the function add is assigned to a variable, in the second example the function double is passed as an argument to the map method, and in the third example, an anonymous function is returned as a value from the createCounter function.
It's important to note that functions in javascript are first class object, which means they are also objects and have properties and methods just like any other object.
High Order Function
A higher-order function is a function that takes one or more functions as arguments and/or returns a function as its result. In JavaScript, functions are first-class citizens, meaning they can be passed around just like any other data type (e.g. numbers, strings, etc.). For example:
Here operateOnTwoNumbers is a higher-order function because it takes a function (operatorFunc) as an argument and returns the result of calling that function with the given x and y values.
Callback function
A callback function in JavaScript is a function that is passed as an argument to another function, which is then invoked by that function at a later time. The function that is passed as an argument is called the "callback function," and the function that receives it as an argument and invokes it at a later time is called the "higher-order function." For example:
Here add is a callback function that is passed to the operateOnTwoNumbers function, which invokes the add function with the x and y values passed to it as arguments and returns the result.
Callback functions are often used in JavaScript to handle asynchronous operations. For example, a function that retrieves data from a server may take a callback function as an argument, which is then invoked once the data has been retrieved.
Here, getData is a higher-order function that takes a URL and a callback function as arguments. It uses the fetch function to retrieve data from the specified URL, and then invokes the callback function with the retrieved data as an argument
SetTimeOut
setTimeout is a JavaScript function that allows you to schedule a function to be executed after a specified amount of time (in milliseconds). It takes two arguments: a callback function, and the number of milliseconds to wait before executing the callback function. For example:
In this example, the sayHello function will be executed after 2 seconds (2000 milliseconds). It's also possible to pass an anonymous function as a callback to setTimeout:
You can also clear or cancel a scheduled timeout by using clearTimeout(timeoutId) where the timeoutId is returned by setTimeout function.
setTimeout is often used in JavaScript to create timed events or to delay the execution of certain code. It is also commonly used to create animations, loading screens, and other interactive effects.
SetInterval
setInterval is a JavaScript function that allows you to schedule a function to be executed repeatedly at a specified interval of time (in milliseconds). It takes two arguments: a callback function, and the number of milliseconds to wait between each execution of the callback function. For example:
setInterval is a JavaScript function that allows you to schedule a function to be executed repeatedly at a specified interval of time (in milliseconds). It takes two arguments: a callback function, and the number of milliseconds to wait between each execution of the callback function. For example:
In this example, the incrementCounter function will be executed every 1 second (1000 milliseconds) and it will increment the count by 1 and print it on the console. It's also possible to pass an anonymous function as a callback to setInterval:
You can also clear or cancel a scheduled interval by using clearInterval(intervalId) where the intervalId is returned by setInterval function
setInterval is often used in JavaScript to create timed events or to execute code periodically. It can be used to create animations, loading screens, and other interactive effects. It is also commonly used to perform background tasks or to periodically check for new data
Function Returning A Function
A function returning a function in JavaScript is a function that returns another function as its output. This is also known as Higher-Order Function. For example:
In this example, createCounter is a higher-order function that returns a function that can be used to increment a count variable. The createCounter function creates a new variable count and returns an inner function that increments the count variable and returns its value. When we call the createCounter() function, it returns the inner function, which we can assign to a variable counter. Then, every time we call the counter() function, it increments the count variable and returns its value. Another example would be as below
Here, createAdder is a higher-order function that takes an argument x and returns a new function that takes an argument y and returns the sum of x and y. The returned function is assigned to the variable add5, which can be used to add 5 to any number.
This technique is often used in JavaScript to create reusable and composable functions, to create closures, and to create functions with a specific context or state.
Are The call And Apply Methods
In JavaScript, the call() and apply() methods are used to call a function and set the value of the this keyword inside the function. Both methods can be used to invoke a function and pass arguments to it, but they are used in slightly different ways.
The call() method is used to invoke a function and pass the arguments to it as separate values. For example:
In this example, the call() method is used to invoke the sayHello function and pass the arguments "John" and 30 to it. The first argument passed to the call() method is the value of this inside the function. In this case, we passed null which means that this will be null inside the function.
The apply() method is similar to the call() method, but it is used to pass the arguments to the function as an array. For example:
In this example, the apply() method is used to invoke the sayHello function and pass the arguments ["John", 30] to it as an array. Again, the first argument passed to the apply() method is the value of this inside the function.
Both call() and apply() are useful when you want to reuse a function with different contexts or states, or when you want to invoke a function and pass it arguments from an array.
call() and apply() are similar, but call() is slightly more performant than apply() when passing arguments, because apply() must convert the arguments passed to it into an array before passing them to the function, while call() can pass the arguments directly.
the bind method
In JavaScript, the bind() method is used to create a new function that is bound to a specific value of the this keyword. It returns a new function with the same body and parameters as the original function, but with a this value that is permanently set to the first argument passed to the bind() method. For example:
In this example, getFullName is a function that returns the full name of the person object. We use the bind() method to create a new function getPersonName that is bound to the person object. Then, when we call the getPersonName() function, it returns the full name of the person object, because the this keyword inside the function is set to the person object. Another example would be as below:
Here, the add function takes two parameters and returns the sum of those parameters and this.x. The bind method is used to create a new function bound that is bound to the obj object. So, when we call bound(1, 2), it will return 13, the sum of 1+2+this.x where this.x is 10
The bind() method is useful when you want to create a function that is permanently bound to a specific value of this, or when you want to create a new function that inherits the behavior of an existing function but with a different context or state.
Immediately Invoked Function Expression
An Immediately Invoked Function Expression (IIFE) is a JavaScript function that is immediately executed after it is defined. It is a pattern that is often used to create a new scope for variables, to avoid variable hoisting, or to create a self-executing anonymous function.
An IIFE is defined using the function expression syntax, and it is immediately invoked by adding a pair of parentheses after the function definition. The parentheses are used to invoke the function, just like a regular function call. Here is an example of an IIFE:
In this example, the function is defined using the function expression syntax, and it is immediately invoked by adding a pair of parentheses after the function definition. This function doesn't take any arguments and doesn't return any value. Inside it, it declares a variable message and logs it. Another example with argument and return value:
In this example, the function takes two arguments a and b and returns the sum of them. It is immediately invoked with arguments 10 and 20. The returned value from the function 30 is stored in the variable result and logs it.
IIFEs are useful when you want to create a new scope for variables, to avoid variable hoisting, or to create a self-executing anonymous function. It is also useful when you want to create a local scope for your functions and variables and avoid polluting the global scope.
Closure
In JavaScript, a closure is a function that has access to the variables in the scope in which it was defined, even if that scope is no longer in use. This means that a closure has access to the variables and functions that were in scope when the closure was created, and it can continue to access those variables even after the scope has ended. Here is an example of a closure:
In this example, the makeCounter function returns a new function that increments a counter. When the makeCounter function is called, it creates a new scope with the variable count initialized to 0. The returned function has access to the count variable, even though the makeCounter function has completed its execution. When we call the counter() function, it returns the current value of count and then increments it. Another example
Here, the outerFunction takes an argument x and returns a function innerFunction which takes another argument y and returns the sum of x and y. The innerFunction has access to the x variable even though the outerFunction has completed its execution. When we call the outerFunction(5), it returns the innerFunction which is stored in the variable add5. Now, when we call add5(3) it returns 8 and add5(4) returns 9
Closures are useful for creating private variables and methods, for creating function factories, and for implementing function decorators and other functional programming patterns.