Reputation: 13
var hi = function(type) {
if (type == "boss") {
return function(name) {
alert("Hi chief " + name);
};
} else {
return function(name) {
alert("Hi " + name);
};
}
};
hi("boss"); // this will do nothing
var returnedFunction = hi();
returnedFunction("boss"); // prompt "Hi boss"
returnedFunction = hi("boss");
returnedFunction(); // prompt "Hi chief undefined"
returnedFunction("Douglas"); // prompt "Hi chief Douglas";
Ok so I understand pretty much everything that's going on except the first one:
hi("boss"); // this will do nothing
I would expect it to return "Hi chief undefined".
Doesn't the "boss" argument would mean it enters the if statement, where it should execute the function with argument name being undefined: hence you should get "Hi chief undefined".
Any information on how/why I get this behaviour would be most welcome. I am trying to understand and learn the basics of javascript !
Kind regards
Upvotes: 0
Views: 83
Reputation: 1
`
var hi = function(type) {
if (type == "boss") {
return function(name) {
alert("Hi chief " + name);
};
} else {
return function(name) {
alert("Hi " + name);
};
}
};
//return a function not excecuted
// hi();
// x is the returned function
var x = hi("boss");
x("name");
// 2
// hi("boss")("name");
`
Upvotes: -1
Reputation: 655
hi("boss");
This line of code will return
function (name) {
alert("Hi chief " + name);
}
this function.
Now you have to execute it.
in order to execute it just write hi("boss")();
Upvotes: 1
Reputation: 56
It returns only function, it doesn't execute it. You would have to write:
hi("boss")(); // it would print Hi chief undefined
in order to execute it
You could probably say that
hi("boss");
is equaivelnt of writing
function(name) {
alert("Hi chief " + name);
};
While writing
hi("boss")();
is like wiring
function(name) {
alert("Hi chief " + name);
}(); // notiice the ()
Upvotes: 3
Reputation: 4129
Why not just:
var hi = function(type, name) {
if (type == "boss") {
alert("Hi chief " + name);
} else {
alert("Hi " + name);
}
};
Upvotes: 0