Home > front end >  Can we call the parameter of a function inside of it?
Can we call the parameter of a function inside of it?

Time:01-18

I have started learning promises in JS, and there are (resolve, reject) which are passed to promise. After some actions in the function you call resolve() if there is everything OK and reject() if not. So, that's why I am asking about this.

Can we actually call the parameters of a function inside of it? Actually, if I put () after the parameter inside a function in VS Code, it is highlighted as a function.

Sorry, if there is some issues with explaining. I am not a native speaker...

There is an example: (what is stack() actually?)

const iGotIt = true;

const f = (stack, overflow) => {
    if (iGotIt) {
        stack({
            newKnowledge: 'Finally',
            message: ':)'
        })
    }
}

CodePudding user response:

It depends on the function parameter, since it may not be a function.

For example:

myFunction(data, callback){
  const result = do_something_with_data();
  callback(result);
}

myFunction(0, result => {
  do_something_with_result();
}); //works

myFunction(1, console.log); //works

myFunction(2, 0); //doesn't work, 0 is not a function.

CodePudding user response:

what is stack() actually?

It's the first parameter in the f function.

The f function expects the first parameter to itself also be a function, and one which accepts at least one parameter which is an object.

But what stack actually is depends on what gets passed to f.

For example, consider this usage in which a function is passed as the first parameter:

const iGotIt = true;

const f = (stack, overflow) => {
    if (iGotIt) {
        stack({
            newKnowledge: 'Finally',
            message: ':)'
        })
    }
}

f(x => console.log(x));

Then invoking stack() invokes the function that was provided. Alternatively, consider this example:

const iGotIt = true;

const f = (stack, overflow) => {
    if (iGotIt) {
        stack({
            newKnowledge: 'Finally',
            message: ':)'
        })
    }
}

f();

This fails because nothing was provided, so stack is undefined. Or this example:

const iGotIt = true;

const f = (stack, overflow) => {
    if (iGotIt) {
        stack({
            newKnowledge: 'Finally',
            message: ':)'
        })
    }
}

f('test');

This also fails, because a string is not a function and can't be invoked like one.

  • Related