Students Empire

Learn Something New
Home

Variables


Everything in Javascript is case-sensitive.

variables, function names, and operators are all case-sensitive.

A variable named test is different from a variable named Test.

Identifiers

An identifier is the name of a variable, function, property, or function argument.

Javascript identifiers may be one or more characters in the following format:

  • The first character must be a letter, an underscore _, or a dollar sign $.
  • All other characters may be letters, underscores, dollar signs, or numbers.

Keywords, reserved words, true, false, and null cannot be used as identifiers.

What are variables

Every variable is simply a named placeholder for a value. Javascript variables are loosely typed: a variable can hold any type of data.

var

To define a variable, use the var operator followed by the variable name, like this: var myVariable;

This code defines a variable named myVariable that can be used to hold any type of value.

Without initialization, it holds the special value undefined.

More than one variable

Variable initializations using different data types may be combined into a single statement.

To define more than one variable using a single statement, you can separate each variable and optional initialization with a comma like this:

				var myString = "hi",
				myBoolean = false,
				myInt = 29;
				

Here, three variables are defined and initialized. Inserting line breaks and indenting improve readability.

Variable Scope

Using the var operator to define a variable makes it local to the scope where it was defined.

Defining a variable inside of a function with var means that the variable is local to that function and will be destroyed if the function exits, as shown here:

				function test(){
				   var myVariable = "hi";  //local variable
				}
				test();
				console.log(myVariable); //error!
				

Here, the myVariable variable is defined within a function called test() using var.

Global Variable

To define a variable globally, simply omitting the var operator as follows:

				function test(){
				   myVariable = "hi";  //global variable
				}
				test();
				console.log(myVariable); //"hi"
				

By removing the var operator from the example, the myVariable variable becomes global.

Defining global variables is not recommended. Global variables defined locally are hard to maintain and cause confusion.

Strict mode throws a ReferenceError when an undeclared variable is assigned a value.

Comma Operator

The comma operator allows execution of more than one operation in a single statement.

				var num1=1, num2=2, num3=3;