Declare Variables

Declare Variables

A variable stores the data value that can be changed later on.

The following reserved keyword can be used to declare a variable

  • Using let

     The following example creates the variable with the default value as null

    CODE1

     

     Using "=" operator allows us to assign value to our variable

    CODE2

     

     On the following example last assignment will be the value of the variable.

    CODE3

     

     We can also make the variable creation and assignment in single liner

    CODE4

     

     Multiple variables could be defined in a single line by using comma (,) charachter

    CODE5

     

     Although it can be defined in a single, to read code better we suggest to use multiple line on variable creation

    CODE6

     

  • Using const

     To create the variable with const keyword would make it unchangable.

    CODE7

     

     Second line of the following code would fail as the variable defined with const keyword which makes it unchangable.

    CODE8

     

  • Using var

     var keyword is very similiar to let keyword. The only difference is var has no block scope

    CODE9

     

     This will work as var creates the variable dynamicly when it executes the line

    CODE10

     

    This will fail as let creates the variable in the same or above level block

    CODE11

     

    On the following code function1 can access the global variable message1 and local variable message2. The last line will fail as message2 is part of function1 local variable

    CODE12