-
Notifications
You must be signed in to change notification settings - Fork 0
11 Functions
Biswajit Sundara edited this page May 1, 2023
·
1 revision
Java Script functions really help in achieving code re usability and ensuring modular design approach.
Java script functions can be categorized in five ways
- Anonymous function
- Regular function
- Function expression
- New function
- Arrow function
Anonymous function is the java script function that doesn't have a name.
- This is not recommended for regular use.
- The syntax of the function is
function(){}
- This is useful when we pass a function as an argument to another function
setTimeout(function () {
console.log('Execute later after 1 second')
}, 1000);
- Self invoking functions are anonymous functions and it doesn't require any calls to execute the function
- These are immediately invoked function
- It doesn't pollute the global scope and forgotten immediately after the execution.
(function () {
console.log('Hello');
})();
Regular function is the default way of writing the functions and is recommended to use.
Function starts with keyword function and followed by function name
function display(){
console.log('Hello');
}
using the function name we can call it
display();
function add(a,b){
return a+b;
}
x=add(2,3);
console.log(x);
When the function is assigned to a constant/variable, it's called function expression.
- We can have named or anonymous function expression
- Declared functions are
hoistedbut function expressions are nothoisted - The declared functions will be available to the entire application
- However function expressions are available to the code below its initialization.
const sum = function(a,b) {
return a+b;
}
console.log(sum(2,3));
const sum = function add(a,b) {
return a+b;
}
console.log(sum(2,3));
Java script has a built in function constructor Function()
let addnum= new Function("a","b","return a+b");
console.log(addnum(4,5));
It depends on the situation to create the functions this way. Usually functions are created other ways.