Table of Contents
Back Button
Back to Chapter
No items found.

JavaScript Variables

Introduction

In Javascript, Variables are used to store data values.

All Javascript variables must have a unique names. The unique names are termed as identifier in Javascript.

Example : name , age , total etc.

Rules to Write Javascript Variables.

The Generals Rules for unique indentifiers (variables) are :

  • Names can contain letters, digits, underscores, and dollar signs.
  • var firstProject;    // ✅ Valid
    var project1;        // ✅ Valid
    var my_project;      // ✅ Valid
    var proj$;           // ✅ Valid
  • Names must begin with a letter
  • var firstProject;    // ✅ Valid
    var project1;        // ✅ Valid

    var 1project;        // ❌ Invalid
    var 123;             // ❌ Invalid
    var *name;           // ❌ Invalid
  • Names can also begin with ( $ ) and ( _ )
  • var $firstProject;     // ✅ Valid
    var _project1;         // ✅ Valid

    var *name;             // ❌ Invalid
    var &project;          // ❌ Invalid
    var %name;             // ❌ Invalid
  • Names are case sensitive (x and X are different variables)
  • var firstProject; and var firstproject; are 2 different variables.
  • Reserved words (like JavaScript keywords i.e float, byte, char, private) cannot be used as names of variables.

Using Variables

previously you have learned, how to store data in variables. Now, let's see how to use variables.

var x;
var y = 10;
var z = 5;
x = y + z;
console.log(x);

Here,

y stores the value 10.

z stores the value 5;

now for x, we have a sum of y and z.

so , value of x will be  y + z  i.e.  10 + 5

console.log(x) is used to print the data in the console tab. here the value of x i.e.  15  will be printed in the console tab.

Note :

  1. When you declare any new variable like var x; it is no value stored in it. so whenever you try to print the variable it will print undefined which means it has no value in it.
  2. If you have declared a variable with value 10 and want to change that value, you can reassign new value to that variable.
  3. For Example :
  4. var x = 50;
    x = 75;
  5. Value of x is changed to 75.

Assign Many Variables in One Statement.

You can declare many variables in a single statement.

For Example :

var name="javascript" , age=25;

Note:

Don't Forget to write the string element in double quotes (" ")

All Data Types integers , float , double , string, char  can be used in Javascript as var . There is no need to define it separately, var holds properties of all Data Types.

Ask queries
Contact Us on Whatsapp
Hi, How Can We Help You?