JS Variables

JavaScript

In this tutorial we will learn about JavaScript variables.

What is variable?

Variables are named container that holds some value.

How we create variables in JavaScript?

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;

How to name a JavaScript variable?

Name of JavaScript variables must be unique and can use only the following characters.

  • Letters a-z A-Z
  • Digit 0-9
  • Dollar sign $
  • Underscore _

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.

Camel Case

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;

Declaring multiple variables

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;

Assigning value to a variable

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;

undefined value

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);

Re-declaring a variable

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"