Sign in
Log inSign up

Variables (Let, Var and Const), What you Need to Know.

ECMAScript 2015 (ES6) for React.js (1 of 12)

Johnson Degbor's photo
Johnson Degbor
·Nov 6, 2021·

6 min read

Variables (Let, Var and Const), What you Need to Know.

What are Variables?

Concept 1

Think of the concept of variables as a representative (Mr.Var) of a company. When Mr.Var goes for conferences or inter-business meetings he does not present himself but the company at large, Mr.Var is the company. Any information that has to get to the company has to get through him, all business plans and arrangement needs Mr.Var present.

This crops out the complexity of having every relevant staff at a meeting or business process when Mr.Var is available.

Mr.Var is trusted and efficient with this role of his.

Concept 2

Variable could be seen as boxes in which items(data) could be stored for a more stress-free application (as relating to movement and storage).

This crops out the difficulty of having to move each item independently.

Variables in JavaScript

Javascript has three methods of applying variables:

  1. var
  2. let
  3. const
var string1 = "We";
let string2 = "are"
const string3 = "Variables"

console.log(string1, string2, string3)
//OUTPUT
// We are Variables

We will be looking at the behavior of each of these and how to implement them.

Quick Win: Declaring a variable is initializing a value to be stored in a variable.

var

var (is case sensitive) has the following properties:

  1. It can be redeclared (it can be declared with the var keyword repeatedly):

    var string = "I am the initial value"
    var string = " I am the redeclared value, I'm new here"
    
    console.log(string)
    
    //OUTPUT
    //  I am the redeclared value, I'm new here
    
  2. It can be updated (this time without the var keyword): It replaces the previous value of the string variable

    var string = "I am the initial value"
       string = " I am the updated value, I rule now!!"
    
    console.log(string)
    
    //OUTPUT
    //  I am the redeclared value, I'm new here
    
  3. They were previously used in ES5(predecessor of ES6), they are supported by most browsers than any form of declaration.

    You can test this by visiting the caniuse website.

  4. They are hoisted and when accessed before the declaration they don't return an error: They carry out what is called hoisting, the Engine would not throw an error if it is declared after where it is referenced, although this would return "undefined". This is one of the reasons the var declaration is not encouraged.

    console.log(hoisted);
    var hoisted = "I will return undefine"
    
    //OUTPUT
    //  undefined
    
  5. It is function scoped: When a variable is declared using the "var" keyword within a function it is not accessible beyond that function:

    
    var global = "This is Global from the outside world"
    
    function aBasicfunction(){
    
    var innerGreetings = "Hello to "
    var toWho = "the outside world. "
    return innerGreetings + toWho + global
    
    }
    
    aBasicfunction()
    console.log(innerGreetings)
    
    //OUTPUT
    //  'Hello to the outside world. This is Global from the outside world'
    //ReferenceError: innerGreetings is not defined
    

    As seen above the aBasicfunction() execute fine because it is working with every data within scope, but on the other hand, innerGreetings returns a ReferenceError because it is out of scope.

    This means they are restricted in other code blocks except for functions (it is not limited to "if statement", "try block" etc.) which could lead to errors if not properly implemented.

    var string = "I am the initial Global Scope"
    if(true){
    var string = "I'm I limited to this scope?"
    } 
    
    console.log(string)
    
    //OUTPUT
    //  "I'm I limited to this scope?"
    
  6. It stores its element/value in the global object, that is the window object

    var whereILive = "I am also stored in the window object";
    
    console.log(this.whereILive)
    
    //OUTPUT
    //  'I am also stored in the window object'
    

    Let's move to the next and most preferred variable "let".

let

let has some major differences from the ES5 "var". It was recently made with the update from ES5 to ES6. It is most preferred and recommended by developers as it is less prone to hidden future bugs, here are some reasons that make it a better option.

  1. It cannot be redeclared (unlike "var"). This would immediately throw a SyntaxError which would prevent future bugs when there is an extra layer of complexity. This helps developers as it prevents them from changing the data assigned to an already existing variable unknowingly.

     let string = "I am the initial value"
     let string = " I am the redeclared value, I'm new here"
    
     console.log(string)
    
     //OUTPUT
     //  SyntaxError: Identifier 'string' has already been declared.
    
  2. It can be updated (this time without the let keyword): It replaces the previous value of the string variable, this is similar to the "var" keyword

    let string = "I am the initial value"
       string = " I am the updated value, I rule now!!"
    
    console.log(string)
    
    //OUTPUT
    //  I am the redeclared value, I'm new here
    
  3. The "let" keyword for declaring variables was brought about with the release of the ES6 which makes it makes it less compatible than "var", but it still covers a wide range.

    You can view the compatibility of let from the caniuse site.

  4. They are hoisted but cannot be accessed before the declaration. Programs attempting to access the data of the "let" before they are declared are said to be in the Temporal Dead Zone.

    console.log(hoisted);
    let hoisted = "I will return undefined"
    
    //OUTPUT
    //  ReferenceError: hoisted is not defined
    
  5. "let" variables are block-scoped. This means data stored using the let keyword cannot be accessed beyond block-scope that is curly braces e.g functions, throw, for loop, if statements, etc.

    let surname = "Degbor";
    function myName(){
    let firstName = "Johnson";
    console.log(firstName,surname)
    }
    
    console.log(surname)
    myName();
    console.log(firstName)
    
    //OUTPUT RESPECTIVELY
    //'Degbor'
    //'Johnson' 'Degbor'
    //ReferenceError: firstName is not defined
    

    Snippet 2

    for (let i = 0; i < 4; i++) {
    var j = 10;
    }
    console.log(i);
    
    //OUTPUT RESPECTIVELY
    //ReferenceError: firstName is not defined
    
  6. It does not store its values in the global object also referred to as the window object:

    let whereILive = "I am not in the window object, I won't be defined";
    
    console.log(this.whereILive)
    
    //OUTPUT
    //undefined
    

const

Now for the final type of variable const. It is known as a constant variable. const possess all the "let" variable's principle but has just one yet major difference from "let", which is it cannot be updated. Here is a sample snippet below:

   const NEVER_UPDATE = "I will never be redeclared or updated, never"
         NEVER_UPDATE = "Let's see if you will update, const"

   console.log(NEVER_UPDATE)
   //OUTPUT
   //TypeError: Assignment to constant variable.

Most professional developers prefer to use "const" because of this solitary strict ability it possesses, as it is more secured in storing different data types

If you noticed(although not necessarily), I used capital letters for the identifier(name of a variable, in this case, NEVER_UPDATE is the identifier) in the snippet above, this is recognized as a practice for other languages as the developers can easy recollect or identify when they are working with a constant.

Okay, that's about it, let's not leave without a fun exercise and challenge.

Exercise Based on the content above, state the difference between var, let, and const, a link of the exercise should be preferably dropped into the comment. The most well-structured table would be featured in this post and would receive credit and recognition for their material.

Thanks for your time, I will de updating this content soon, if you feel I missed anything important, kingly suggest in the comment

This is just 1 of 12 of the ECMA 2015 (ES6) for React.js.

Stay Tuned.

Shout out to my mentor Great for motivating me to do this.