While Loops my own exercise!


#1

<PLEASE USE THIS TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/learn-javascript-loops/lessons/loops/exercises/while?action=lesson_resume&course_redirect=introduction-to-javascript

<Below this line, in what way does your code behave incorrectly? Include ALL error messages.>
Well i’ve notice that with the final code from the exercise, the first value logged into the console was always the let currentCard=“something”;

So I wanted to make the first value that is logged to be also a random one… The code runs well (i think) but if the random currentCard is not ‘Spade’ it doesn’t logs hearts, clubs or diamonds.

What is the problem?

/home/ccuser/workspace/learn-javascript-loops-L1E6/main.js:8
console.log(currentCard);
^

ReferenceError: currentCard is not defined
at Object. (/home/ccuser/workspace/learn-javascript-loops-L1E6/main.js:8:14)
at Module._compile (module.js:571:32)
at Object.Module._extensions…js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:427:7)
at startup (bootstrap_node.js:151:9)
at bootstrap_node.js:542:3

```

let cards = [‘Diamond’, ‘Spade’, ‘Heart’, ‘Club’];

let currentCard = cards [Math.floor(Math.random()*4)];

while (currentCard!==‘Spade’) {
console.log(currentCard);

let currentCard = cards [Math.floor(Math.random()*4)];
}

if(currentCard=‘Spade’) {
console.log(‘Spade’);
}

<do not remove the three backticks above>

#2

Inside the while loop, using let scopes the variable to the loop block. Remove let so the global variable is not shadowed by the block varaible.


#3

Thanks mtf. It works fine, and, most important, I understood your explication! :wink:


#4

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