DEV Community

Cover image for Arrow Funcion In javascript
Mahima Bhardwaj
Mahima Bhardwaj

Posted on • Updated on

Arrow Funcion In javascript


Image description**

First we need tho understand what is function

**
Function- It is Block of statement which take input as parameter and perform some operation on that input and return them as output.
**

*Syntax of Normal Function *

**
function HelloWorld()// function defintion
{
console.log("Hii")
}
HelloWorld();// function calling

Now, we need to understand
--What is Arrow Function??
Arrow Function-{()=>}-concise way of writing javascript function in shorter way.
Introduced in ES6 version.It is anonymous function without a name.
Syntax of Normal Arrow Function

const hello=()=>
{
console.log("hello world");
}
hello();

Arrow Function with parameters
const add=(a,b)=>
{
return a+b;
}
console.log(add(2,3))

Simpler way of writing Arrow Function
const diff=(a,b)=>a-b;
console.log(diff(2,1))

Note :- arguments keyword are not available in arrow function.

Spread Operator in arrow Function

const Number=(...num)=> console.log(num)
Number(2,3,4,5,10) // [2,3,4,5,10]

First we need to understand what is Hoisting in javascript so calling a function before defining it Known as Function Hoisting.
It does not give any difference in normal function for ex
multiply(3,2))//6
function multiply(a,b)
{
console.log(a*b);
}

But is not allowed in arrow function it will show error.

before , discussing this keyword in arrow function let's see the working of this keyword in normal function declared inside object.

const obj=
{
name:'Radhika',
myFunction: function()
{
console.log(this.name)
},
};
obj.myFunction// 'Radhika'

Here , in above code this keyword is working for this object only but if we declare this keyword inside arrow function it will show value as undefined let see the code of it.



const obj=
{
  value:20,
  myFunction: ()=>
{
  console.log(this.value)
},
};
obj.myFunction()// undefined `


the reason behind is this that this keyword inside arrow function work for window not for that object inside which it is declared in case of arrow function.




Enter fullscreen mode Exit fullscreen mode

Top comments (0)