Javascript Variables.

Variables

What are variables?

  • Variables are the containers for storing the data.
  • Variable is generally declared by using a keyword "var" followed by a label . When var is declared then a dynamic memory is allocated for the variable.
  • Label is the name which addresses the type of data stored in the variable.
  • For example:
var myName;
  • Semicolon is used to distinguish between seperate elements.
  • When there is nothing intialised to the variable then by default variable is intialised to undefined datatype.

Assigning values to the variables

We assign values to the variables by using an assignment operator "=" . This operator helps to store the data of the variables for the given label.

var myName = "Vignesh";
var value = 5;

In the above code snippet, we can observe that a variable named myName is declared to a string "Vignesh" and also the other variable labelled with value is declared to 5. We can also modify the values in the variables such as

var myName = "Vignesh";
myName = "Viraja";
var value = 5;
value = 21;

Now myName is updated or modified to Viraja and value is modified to 21.

Let and Const

In few cases, the code might get larger and larger and there might be one value which is same throughout the codebase. But due to some mistake when we declare same variable to other value then whole code will be troubleshooted. So to overcome this type of problem we use other keywords called "const".

  • Const keyword is used to declare only the constant values and these values cannot be modified throughout the codebase.
  • If we try to change the const value then it throws an error.
  • Syntax / Example : const pi = 3.14; .

We know that we can modify the variable by:

var x = 10;
var x = 54;

Intially x is declared to 10 then again x is redeclared to 54 and we will get 54 as the output in the console window. As we have seen the variable defined with var is redeclared but there is an another keyword called "let".

  • When a variable is defined with the keyword let then we cannot redeclare the variable by using let keyword. If we do so then it throws an error.
  • Example :
    let b = 'hello';
    let b = 'world'; // SyntaxError: Identifier 'b' has already been declared
    

Hope this gives a summary about the variables. If there is any inaccurate information help me out to correct it