JavaScript Const vs. Var vs. Let: A Comprehensive Guide for All Time
JavaScript in Plain English, a Medium blog, has an interesting article called “JavaScript Const vs. Var vs. Let: A Comprehensive Guide for All Time”, which… as it says on the tin, walks through a fairly comprehensive discussion of javascript’s var
, let
, and const
keywords, and when to use them.
Along the way, it talks about “hoisting” - the mechanism where JavaScript will reorder your code at runtime - and the impact that has on your code, and how to manage variable declarations with proper scope.
The rules seem fairly simple, though: use let
if the reference is mutable, use const
if it is not, and use var
if you don’t care about your fellow coders much. (This is a really poor summary, obviously, and JavaScript’s const
declarations are much like Java’s final
declarations and C’s const
as well - the reference is immutable, but the thing it points to might not be.)