Define variables in Javascript

Description

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.

Initialization

It's possible to define the variable and set its value at the same time.

var myVariable = "hi from java2s.com";

Here, myVariable is defined to hold a string value of "hi from java2s.com".

Since Javascript variables are loosely typed, this initialization doesn't mark the variable as string type.

It is possible to change myVariable's value and type.


var myVariable = "hi";
myVariable = 100;      //legal, but not recommended

In this example, the variable myVariable is first defined as having the string value "hi" and then overwritten with the numeric value 100.

More than one

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.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions