0

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 
1
  • 1
    Not sure I understand the question (or why you are unsure). You are passing defaultData to the callback: viewFunc(defaultData);. That's how it gets its value. It's the same as with any other function call. Commented Jun 16, 2017 at 14:59

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the great explanation, However anonymous function doesn't take any argument but the reference to anonymous function (viewFunc) does but it doesn't throw any exception ?
What do you mean? The anonymous function does take an argument, which you named state. Your code is valid and correct.
my bad, I was overthinking. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.