mirzhal
mirzhal

Reputation: 159

Value is not returned

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

Answers (4)

Anton Globa
Anton Globa

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

Code Maniac
Code Maniac

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

Apolo
Apolo

Reputation: 4050

Here are your problems:

  • in function m, you return the result of alert(mi) which is undefined (= nothing is javascript)
  • in function mirzhal you return a function, so when you execute 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

Quentin
Quentin

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

Related Questions