Reputation: 159
Hey guys I am beginner at JavaScript and I faced the confusion with the way how return works in JavaScript, that is, if you look at the code below I want to get value 5 when mirzhal method is called but I get nothing thus I need your help
let mir = {
mirzhal() {
function m() {
let mi = 5;
return alert(mi);
}
return m;
}
}
mir.mirzhal();
Upvotes: 0
Views: 79
Reputation: 133
It was because the function mirzhal() returns another function.
Try like this:
mir.mirzhal()();
And you can see you alert
Another problem is you try to return result from alert function which does not provide result
Upvotes: 1
Reputation: 37755
You need to return 5
from m
function and also need to call the returned function
let mir = {
mirzhal() {
function m() {
let mi = 5;
return mi;
}
return m;
}
}
console.log(mir.mirzhal()());
Upvotes: 1
Reputation: 4050
Here are your problems:
m
, you return the result of alert(mi)
which is undefined (= nothing is javascript)mirzhal()
your result is a function you need to call.mir.mirzhal()();
will work
This should be better:
let mir = {
mirzhal() {
return 5;
}
}
mir.mirzhal();
Upvotes: 1
Reputation: 943556
return
will return whatever is on the right-hand side of it.
If you want to get 5
then you need to return 5
.
return 5
… and you also need to examine the return value:
const five = mir.mirzhal();
alert(five);
Your current code doesn't return 5. It returns a function.
If you were to call that function, then it would alert 5 (and return the return value of that function).
const a_function = mir.mirzhal();
a_function();
Upvotes: 1