My code ran properly without typing 'let' before the variable. So is the let keyword unnecessary?

My code ran properly without typing ‘let’ before the variable. So is the let keyword unnecessary?

The short answer is no, it definitely is still necessary and not using them causes scoping issues :slight_smile:

The longer answer is using let or const creates a variable that is scoped to the block it was created in, so if I have:

function myFunc(num) {
   const doubleNum = num * 2;
   return doubleNum
}

Then the variable doubleNum only exists inside of that function, and trying to access it from anywhere else will throw an error. Not using an appropriate let/const variable specifier means that these scoping rules aren’t followed, instead the variable will be considered a global variable and is accessible from anywhere - this is generally a bad thing, as scope exists for a reason and use of global vars goes against ‘good practice’ principles like encapsulation* and modularity, making it easier for bugs to creep in - their use should be minimized as much as possible or just avoided completely (imo).

If using a tool like ESLint which enforces good practices, or when using JavaScript’s inbuilt strict mode, they will both emit warnings if the let/const is omitted.

* effectively restricting access to data and saying that internal parts of a large data structures shouldn’t (all) be publicly accessible

4 Likes

Got it - Thank you for your reply.

1 Like