JavaScript Variable Types (var, const, let)

 ← Dev Articles
👍 0
👎 0

There are 3 types of variables commonly used in javascript.  The main difference with the let type it's block scope.  If it's defined inside of a block it can't be accessed outside of the block.   Let's look at each in more detail:

const

Variables defined with const cannot be Redeclared
Variables defined with const cannot be Reassigned
Variables defined with const have Block Scope


// INCORRECT - must be assigned a value when it's declared.
const x;  
x = 1.999;

// INCORRECT - it cannot be reassigned a value
const x = 1.999;

x = 8;  

// IF defined inside of a block it has block scope. Look at example below:
if( somecondition )
{
   const x = 9;
}
// x cannot be access here outside of the "block", curly brackets.
// Below are valid usage of const:
// Example 1:
if( condition )
{
   const x = 8;
   console.log(x);
}

// Example 2:
const x = 8;
if( condition )
{
   console.log(x);
}