1
let cards = ['Diamond', 'Spade', 'Heart', 'Club'];

let currentCard = 'Heart';

while (currentCard !== 'Spade') {
  console.log(currentCard);
  let currentCard = cards[Math.floor(Math.random() *4)];
}

console.log(currentCard);

Here my concern is about the error that currentCard is not defined , even though I have declared it globally.

So I am thinking that the error message currentCard is not defined should not come.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
alex
  • 11
  • 1

3 Answers3

1

This is because you have defined your variable with let in both your your global scope AND in your while loop. let is scoped by a block scope, so inside your while loop is a different one than in your global scope.

It is crashing on line 6, the console.log just below the while definition. You define your variable inside the while loop in the line below your console.log. Therefore Javascript does not find your variable because it is not defined yet.

from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

Variables declared by let have as their scope the block in which they are defined, as well as in any contained sub-blocks. In this way, let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function

Bas van Dijk
  • 9,933
  • 10
  • 55
  • 91
  • I understand,here I have written console.log(currentCard) outside the while loop so it should refer the global scope variable that is let currentCard = 'Heart'; – alex Mar 07 '18 at 09:42
  • It is crashing on line 6, the console.log just below the while definition. You define your variable inside the while loop in the line below. Therefore Javascript does not find your variable. – Bas van Dijk Mar 07 '18 at 09:46
0

You are redefining currentCard in the while loop. Remove the extra let and it should work.

Hussain Ali Akbar
  • 1,585
  • 2
  • 16
  • 28
0

Your error is coming from the while block's console statement.

So I am thinking that the error message currentCard is not defined should not come.

No, even though you have declared currentCard globally, you have re-declared it in the while loop block and accessed it before you have initialized the same.

Read more about temporal dead zone.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94