JavaScript
In this tutorial we will learn about JavaScript variables.
Variables are named container that holds some value.
We use the var
keyword to create or declare a variable in JavaScript.
In the following example we have created a variable name.
var name;
Name of JavaScript variables must be unique and can use only the following characters.
Variable name must not start with a digit and must not use reserved keywords.
Following are some of the valid variable names.
var name;
var age;
var school_name;
var _temp;
Following are invalid variable names.
var 1address; //invalid starts with digit
var student-name; //invalid using the - symbol
Variable names are case sensitive so, name
and Name
are considered as two separate variables.
We can use Camel Case to name variables. Its a typographic convention in which each word starts with a capital letter with no punctuations or space.
Following are some of the valid variable names using camel case.
var UserName;
var StudentAddress;
We can also start the variable name using lower case letter for the first word and then upper case for the following words.
var userName;
var studentAddress;
In order to declare multiple variables we can separate the variables using comma.
In the following example we have created 3 variables.
var studentName, studentID, studentAge;
We use the assignment operator =
to assign value to a variable.
In the following example we have assigned the value 10 to the variable score.
var score = 10;
If a value is not assigned to a variable then it gets the undefined
value.
Following code will print undefined in the browser console.
var score;
console.log(score);
When a variable is re-declared then it retains its previous value.
In the following example we have declared a variable name and set it to "Yusuf Shakeel" and then re-declared it.
var name = "Yusuf Shakeel";
console.log(name); //this will print "Yusuf Shakeel"
var name;
console.log(name); //this will also print "Yusuf Shakeel"
ADVERTISEMENT