Friday, April 27, 2018

Named Function Expression - NFE

Named Function Expression (NFE)  - We are giving a name to Function Expressions.

Before going into NFE, we should understand what is Ordinary Function Expression. Below is example,


let sayTest = function(one) {
  alert(one);
};

Now just add a name to that, (NFE).


let sayTest = function yourName(one) {
  alert(one);
};

It looks like very simple. But everything is designed for some reason. Let check why we are giving name like this?


1. It allows the function to reference itself internally.

2. It will not be visible to outside of the function.


let sayTest = function yourName(one) {
  if (one) {
    alert(one);
  } else {
    yourName("Guest"); // use yourName to re-call itself
  }
};

sayTest(); // Guest

// Error here
yourName(); // Error Here - not visible outside of the function


Come to our final main concept. Why we want this NFE. See below example,


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let sayHi = function yourName(one) {
  if (one) {
    alert(`Hello, ${one}`);
  } else {
    yourName("Guest");  // Because of this line, this code working
    //sayHi ("Guest"); // This will not work.
  }
};

let welcome = sayHi;
sayHi = null;

welcome(); // nested call works here perfectly

Explanation :

1. Here line number 1, yourName is your NFE. 

2. You have used this name inside line number 5.

3. Suppose if you change the line number 5 to like sayHi("Guest"), will throw an error. Why ?

4. Because line number 10, sayHi was assigned to null. So this will be reflected to line number 9 too. So error will be thrown. (There is no sayHi function).

5. To solve that, we should add NFE , Because internal call possible in NFE.





No comments:

Post a Comment