Difference Between JavaScript Var, Let and Const Variables.

Table of contents

No heading

No headings in the article.

As a JavaScript beginnner, I found it hard differentiating between the diffe> rent variable types and the right way to use them, but with time, I got to understand the key differences and that I seek to demistify through this article.

First off, lets talk about the declaration scopes in JavaScript:

1. Global Scope 2. Local Scope

Global Scope - Global scoped variables are variables that when declared can be accessed anywhere in the code window. Practically they are variables declared outside of functions.

Local Scope - Local scoped variables can only be declared and used within a function meaning that the variable cannot be called outside the function.

Differentiating between Var, Let and Const Var - Then var keyword is used to declare a variable that is basically global scoped. Before the ES6 implementation of JavaScript, Var was the only way available to declare variables in JavaScript, but with ES6 came the Let and Const keywords, which are basically block scoped. The var keyword can also be redeclared.

Let - The let keyword is used to declare block scoped variables. When this is used, it means the variable cannot be called outside the function or block. The only outlying difference between this keyword and the var keyword is that this is block scoped. It can also be redeclared in within the function or block.

Const - The const keyword is also a block scoped keyword, but the major highlight is that is not reusable; In the sense that once declared, it can't be redeclared, both within and outside the block where it is defined.

Conclusion - Var can be called anywhere in the codeblock, siince it is a global keyword, it can also be redeclared. Let can also be redeclared but can't be called outside the block. Const can't be redeclared after initial declaration.