Tom
Tom

Reputation: 2075

Calling a function in a While loop

I am trying to understand why these two pieces of code do not provide the same input, and why the first piece returns 'undefined'?

var myFunction = function() {
Math.floor(Math.random() * 2);
};

while(myFunction === 0){
    console.log("Test");
    myFunction();
 }

console.log("Return");

Second piece:

var myFunction = Math.floor(Math.random() * 2);

 while(myFunction === 0){
    console.log("Test");
    myfunction = Math.floor(Math.random() * 2);
 };

console.log("Return");

Upvotes: 0

Views: 97

Answers (1)

Erik
Erik

Reputation: 3636

There's quite a few issues here. I'll go over them:

1) None of your functions have return statements, so none of them return any value

2) In your first piece, you compare myFunction (which is a function) with an integer (which will never be the same). You probably want to put some parentheses in the if statement so you compare the function's return value. (This also makes the call inside the while body useless, since you do nothing with the return value anyway)

3) in your second piece, you assign a number to myFunction. This is mostly confusing, but it does explain why this piece of code works: you didn't actually create a function.

4) Also in your second piece, you have different casing between myFunction and myfunction, which are not the same variable.

Upvotes: 3

Related Questions