Js Functions
functions is a piece of code that we use to reduce code repeatability
Syntax:
function function_name(parameters){
//code to be executed
}
// calling function with custom arguments
function_name(arguments);
Spread and rest operator as parameter and arguments
//Rest
function sum(...nums){
let total=0;
for(let i of nums){
total+=nums;
}
return total;
}
console.log(sum(1,2))
console.log(sum(1,2,3,4,5))
/* we can give any numbers of arguments and ...nums will take
all the arguments and convert it to array */
//Spread
function sum(num1,num2,num3){
return num1+num2+num3;
}
const nums=[1,2,3];
console.log(sum(...nums));
/*...nums will pass array elements as arguments and
pass the required parameters*/
/* if no. of parameters are greater than
elements in array then it will give NaN as output */
Objects as parameter
// we write object parameter as anyobject
function handelObject(anyobject){
// to access any keyed collections
console.log(anyobject.key_name)
}
const user={
name:"aakash"
}
handelObject(user)
Arrow function (this function)
const user ={
username:"aakash",
price: 321,
welcomeMessage: function (){
console.log(`${this.username} , welcome to website`);
/* this keyword refers to the context where a piece of code
such as a function's body is supposed to run */
}
}
user.welcomeMessage();
user.username="anand";
user.welcomeMessage();
// In browser if we print this then it will give window as a object
/* we can only use this in object not in function */
const welcome = function () {
let user = "aakash"
console.log(user);
}
const welcome = function () {
let user = "aakash"
console.log(user);
}
Implicit and explicit return
// explicit return when we use return word
const sum = (num1,num2) => {
return num1+num2
}
//implicit return when we use parenthesis
const sum = (num1,num2) => (num1+num2)
// to return an object
({name:"aaksh"})
Immediately invoked function expression (IIFE)
(Function defination)()
(function welcome(){
console.log("hello")})()
( () => {
console.log("dhjv")})()
// it will provide error so use semicolom
//we can also give parameters and arguments to the function
( (parameter) => {
// code to be executed
})(argument);
//names iife is function with name
// unnamed iife is function with without name