Javascript variables

Javascript variables

Javascript variables

Hey folks. We shall go through one of the basic units of storage - variables.

  • Variables are containers that store values.
  • Javascript is dynamically typed language - run time data types i.e, a variable can be used to store any type of data - be it strings, integers, floating numbers etc.

Naming of variables

  • Variables are also known as identifiers similar to other programming languages.Variable naming has certain rules to be followed.

    • variable name can begin only with a letter or underscore ( _ ).
    • variable names can contain letters(a-z/A-Z), numbers(0-9) and dollar sign($).
    • variable names can not contain any space or tabs.
    • variable names are case-sensitive.
        var place1 = "Hassan";
        let _phoneNumber = 9001001121;
        const name$ = "Meghana";
        const NAME$ = "Deepika"; //name$ and NAME$ are different variables - case sensitive
        let country name = "INDIA" //error -can not contain spaces
      

Ways to declare a variable


- var (ES5)
- let and const(ES6)

1. Using var keyword

  • Note: typeof operator returns a string indicating the data type of the variable

  • var keyword is used to declare variables which can be used globally.

      var coins = 1
      typeof a //returns type of the value variable 'coins' holds 
      "number"
    
      coins = true
      typeof a
      "boolean"
    
      coins = []
      typeof a 
      "object"
    
      coins = null
      typeof a 
      "object"
    
      var coins = "Javascript" //redeclaration of same variable allowed when var keyword is used
      typeof a 
      "string"
    

2. Using let keyword

  • let keyword is used to declare variable in local scope of a block statement i.e, these variables can be accessed wherever they are declared only.

      let chocolates = 3;
      chocolates = 0;
      let chocolates = 10; //Syntax error for redeclaration thrown unlike var keyword usage
    

3. Using const keyword

  • const keyword is used to declare variable in local scope where it can be accessed but cannot be reinitialised and redeclared

      const chocolates = 3;
      chocolates = 10; //Syntax error for re-initialisation thrown unlike var and let keyword usage
    

Comparisons between var, let, const


varletconst
ES5ES6ES6
redeclaration of variable allowedredeclaration not allowedredeclaration not allowed
re-initialisation allowedre-initialisation not allowedre-initialisation not allowed
re-assignment of value to variable allowedre-assignment of value to variableallowedre-assignment of value to variable not allowed
functional/global scopelexical/block scopelexical/block scope
Hoistednot hoistednot hoisted

Thanks everyone for reading. Feel free to connect me on twitter and give feedbacks