Calling a function within While loop


#1


https://www.codecademy.com/en/courses/javascript-beginner-en-qDwp0/0/3?curriculum_id=506324b3a7dffd00020bf661


I am struggling to understand why these two pieces of code behave differently. The first one which calls the function within the While loop does not appear to work?


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

console.log("Return");

Does not do the same as this:

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

console.log("Return");

Thanks in advance for any help!


#2

Capitalize the f in myfunction.


#3

Hi that was a typo in my post, doesn't fix it in the live code. Thanks!


#4

In the first code, myFunction returns "undefined" when you run it. It will never evaluate to 0 and execute "Test".

In the 2nd code, myFunction will run and equal 0 or 1. When the value is 0, "Test" logs to the console and runs again until it evaluates to 1.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.