Mad-D
Mad-D

Reputation: 4669

javascript function execution

I am trying to understand the function call in this scenario, How does state get resolved to viewFunc in addView function definition ( hooks between these ) and takes defaultData as function argument ?

var defaultData = {

  property: [
    {
      name: 'Adam',
      type: 'javascript'
    },
    {
      name: 'Tom',
      type: 'Typescript'
    }
  ]
};

function addView(viewFunc){
  console.log(" 1. Step I");
  viewFunc(defaultData);
  console.log(" 2. Step III ");
}

addView((state)=>{
  console.log(" 3. Step II & lenght of data set : "+state.property.length);
})

Output:

1. Step I
3. Step II & lenght of data set : 2
2. Step III 

Upvotes: 0

Views: 38

Answers (1)

PeterMader
PeterMader

Reputation: 7285

In JavaScript, functions can be passed as parameters to other functions. This is what you are doing when calling addView: you create an anonymous function and pass it to the addView function.

The viewFunc variable now contains a reference to the anonymous function. Like any other function reference, you can call it with arguments. This is what you doing when you pass a reference to the defaultData object to the function that was passed into the addView function.

Function references that are passed as arguments to other functions or returned from another function are called first-class functions.

Upvotes: 2

Related Questions