DEV Community 👩‍💻👨‍💻

Emmanuel Onah
Emmanuel Onah

Posted on

Everything you need to know about var, let and const.

Key points used in this article

Scope: Refers to a lexical environment at which variables and functions (be it expression or statement) are declared and made accessible as precedence.

Hoisting: A mechanism used by the JavaScript engine to take all variables and function declarations to the top of their respective scopes. If an engine supports JIT compilation, then it's in the JIT compilation phase that hoisting happens else during interpretation.

Things to know about var

  • var is global and function scoped based only, e.g:

Image description

  • var allows variable redeclaration(which doesn't make sense) and redefinition(which makes sense) within a singular scope, e.g:

Image description

  • during hoisting, if a variable is accessed before its declarations as var variable, the compiler will hoist the var variable to the top of its scope with an implicit value of undefined, e.g:

Image description

  • var variables declared inside block scope like if-statement, loops are not scoped meaning they can be accessed outside the block. e.g:

Image description

Things to know about let

  • let is global, and block(anything with { }) scoped e.g:

Image description

  • let doesn't allow redeclaration within a singular scope but allows redefinition, e.g:

Image description

  • during hoisting, if a let variable is accessed before the declaration, the compiler throws a Reference error, unlike the var where an undefined value will be implicitly assigned, e.g:

Image description

Things to know about const

  • const has the same features as the let above. The only difference is that its read-only and doesn't allow redefinition, but allows mutation for objects(e.g obj.propertyOrMethod =newValue ) if not frozen(Object.freeze(obj)) e.g:

Image description

In conclusion, var, let and const is not bad in my opinion it just depends on how you understand your program, but rarely do we use var this day.

Top comments (1)

lukeshiru profile image
Luke Shiru

Instead of using screenshots for your code snippets, try using code blocks directly in the article:

const likeThis = () => "🎉";
Enter fullscreen mode Exit fullscreen mode

It makes reading the code snippets way easier on mobile, and also more accessible.


18 Useful Github Repositories Every Developer Should Bookmark

18 Useful GitHub repositories every developer should bookmark: everything from learning resources and roadmaps to best practices, system designs, and tools.