Search⌘ K

Safer Code With let and const

Explore how to write safer and cleaner JavaScript code by using let and const instead of var. Understand block scoping, reduce reliance on older patterns like IIFE, and learn why const is preferred for defining variables to minimize errors and improve code readability.

var does not have block scope and, in the past, that led developers to use a JavaScript design pattern known as Immediately Invoked Function Expression (IIFE) or the Self-Executing Anonymous Function. This pattern was also used to hide variables and functions from outside visibility.

Immediately Invoked Function Expression (IIFE)

In this pattern, lines of code are wrapped inside an anonymous function that is immediately executed.

Why IIFE

For example, in the following code, the variable sqrt, defined within the block, is hoistedHoisting to the top of the file and becomes unintentionally available outside of the ...