Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 28, 2022 10:51 am GMT

Understanding Javascript Normal Function VS Arrow Function

Sometimes in our code we use javascript regular functions and also a function called arrow function.Both are functions but there are certain difference between them.

1.First we see the syntactical difference between them.

//normal functionfunction normalFunc() {  console.log('hi');}normalFunc(); //hi//arrow functionlet arrFunc = () => {  console.log('i am arrow function');};arrFunc(); //i am arrow function

2.Accessing the 'this' key word.
Arrow function doesn't have it's own this key world.It works something like lexical scoping.

But normal function always have its own this key word and it is the global this or window or the parent object where it has been declared.

let person = {  name: 'Jhone',  gfg1: () => {    console.log('hello ' + this.name); // hello undefined  },  gfg2() {    console.log('hi ' + this.name); // hi Jhone  },};person.gfg1();person.gfg2();

3.In arrow function we can not access the arguments object but in normal function we can.

//normal functionfunction food(a, b, c) {  console.log(arguments);}food('rice', 'milk', 'fish'); // {0: "rice", 1: "milk", 2: "fish"}//arrow functionlet fruits = (a, b, c) => {  console.log(...arguments); //ReferenceError: arguments is not defined};fruits('apple', 'banana', 'berry');

4.Using normal function to return something you have to use return statement but in arrow function you can use implicit return.

//normal functionfunction nFunc() {  return 'i am normal function';}console.log(nFunc());//arrow functionlet arrFunc = () => 'i am arrow function';console.log(arrFunc());

5.Normal javascript functios are constructible but arrow funtions are not. You can not create constructor function usig arrow functon but with notmal functions you can.

  function nFunc(name, email) {  this.name = name;  this.email = email;}let preson = new nFunc('jony', '[email protected]');console.log("name: ",preson.name,' ',"email: ",preson.email); // name: jony email: [email protected]

Original Link: https://dev.to/naimahmedshuvo/understanding-javascript-normal-function-vs-arrow-function-4mpc

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To