0

Example 1:

(function () {
  let encryptionKey = Math.floor((Math.random() + 1)*4);
  console.log (encryptionKey >= 6);
})();
    
console.log(encryptionKey);    //encryptionKey is not defined 

Example 2:

(function () {
  encryptionKey = Math.floor((Math.random() + 1)*4);
  console.log (encryptionKey >= 6);
})();
  
console.log(encryptionKey);   //encryptionKey is logged in the console without any errors

Trying to find out why the value is displayed in the second example.

Phil
  • 157,677
  • 23
  • 242
  • 245
Roshan
  • 3
  • 1
  • Read about scoping in relation to javascript variables, particularly how it applies to `let` – Jon P Oct 20 '20 at 23:09
  • 1
    Also, [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode). – Phix Oct 20 '20 at 23:10
  • Second one you have created a global variable, so can be seen outside the closure. – Keith Oct 20 '20 at 23:11

1 Answers1

1

Scope of the variables declared without var/let/const keywords become global irrespective of where it is declared. Global variables can be accessed from anywhere in the web page.

MHD
  • 1,245
  • 2
  • 12
  • 18