Reputation: 41
I'm learning JS and using chrome dev tools console to run the code. Why does the following code only makes one call to randomNumbe()
if it is inside a for loop?
function randomNumber(){
let randomNumber = Math.random() * 10;
return randomNumber;
}
for(let i=0; i<25; i++){
randomNumber();
}
Now if I change the code call the function inside console.log()
it does make the 25 calls to the function:
function randomNumber(){
let randomNumber = Math.random() * 10;
return randomNumber;
}
for(let i=0; i<25; i++){
console.log(randomNumber());
}
Upvotes: 0
Views: 58
Reputation: 707328
Unless you explicitly add console.log()
statements to your code, the console only shows the final value that your code evaluates to when it finishes running. So, you're only seeing one final value in the console which is expected. If you add a console.log()
statement anywhere inside the loop, you will then get output for every iteration of the loop.
So, your function is getting called on all 25 iterations of the loop, you just weren't seeing any output from it because it didn't generate any specific output.
For example:
function randomNumber(){
let randomNumber = Math.random() * 10;
return randomNumber;
}
for(let i=0; i<25; i++){
let x = randomNumber();
console.log(x); // make some visible output in the loop
}
Upvotes: 2