Scope in JavaScript

by Dakota Larson

My internship here at Sundog has allowed me to explore the intricacies of JavaScript. While not as convoluted as privacy, scope in JavaScript hasn’t always been straightforward.

For many years, the only level of scope that JavaScript had besides global, was function level scope. This could create unexpected issues.

In most other programming languages, the final print statement will always print 5 because most programming languages use block level scope. In other words, the variable assignment in the conditional has no impact on the code outside the conditional block.

Luckily, this can be avoided with better name choice, and by declaring all variables at the top of functions.

Interestingly, function scoped variables are “hoisted” and thus always available in some form throughout the function. Therefore, declaring variables at the top of functions is most in line with how the code is processed by a computer.

Despite this unique characteristic of JavaScript, advancements to the language in recent years have added support for block level scope. This is done using two new keywords, const and let.

The difference between the keywords is reassignment. Variables declared with const cannot be reassigned to another variable. On the other hand, variables declared with let have that ability.

It should also be noted that variable hoisting that was mentioned earlier does not apply to variables declared with const and let. Therefore, if one tries to access a variable declared with const or let before it has been declared, then an error will be raised.

Finally, this relatively new feature of JavaScript is widely supported, even by Internet Explorer. While it is part of ES6, if this is the only feature of the version being used, then compilation into ES5 may not be necessary.

Function level scope is not the most challenging JavaScript concept to understand, however, the latest features of the language have done away with what some might consider a pointless complication to the language.

Recent Posts

Browser Compatibility
Dakota Larson
Scope in JavaScript
Dakota Larson
Privacy In JavaScript
Dakota Larson

Archives

Categories