My answer assumes that by Without specifying undefined
you mean a call like that:
theFunction.apply(["ali", "Developer"]);
When you use call
or apply
, the first parameter is the execution context (variable this
inside theFunction
). The two examples set it to undefined
, so this
inside theFunction
will evaluate to undefined
. For example:
function theFunction(name, profession) {
console.log(this); // logs `undefined`
console.log("My name is " + name + " and I am a " + profession + " . ");
}
theFunction.apply(undefined, ["ali", "Developer"]);
Here is the thread explaining why one would use undefined
as execution context.
Now, to your question. If you omit undefined
in your call is like that:
theFunction.apply(["ali", "Developer"]);
the execution context - this
- is set to ["ali", "Developer"]
, and name
and profession
are evaluated as undefined
since you only pass one parameter to apply
, that is why you're getting "My name is undefined and I am a undefined"
call
and apply
are usually used when you want to change the execution context of the function. You're probably using apply
to turn array of arguments into separate arguments. To do that, you need to set the same execution context as the one that would have been if you called the function without apply:
theFunction("John", "fireman"); // `this` points to `window`
theFunction.apply(this, ["John", "fireman"]); // `this` points to `window`