JS Variables


JS variable types include number, string, array, boolean and object. JS variables do not need to be declared before use. However you can always use the keyword new to declare the variables.

Declare a variable:

x=3; //Do not need to declare
var x; //Declare a variable, not initialized
var x=null;
var x=3;
var x= new Number(3);
var x=3, y=[1,3,5,2], z="perschon";


String variable:

var s = "perschon";
var len = s.length; //7
s += " javascript"; //s="perschon javascript"

Click here for detailed string functions.

Array variable:

var arr = new Array(1,4,6,9);
var arr = [1,4,6,9]; //the same
//Another way
var arr = new Array;
arr[0] = 1;
arr[1] = 4;
arr[2] = 6;
arr[3] = 9;
//Associative array
var arr = {"city" : "New York", "country" : "USA"};
var arr = new Array;
arr["city] = "New York";
arr["country"] = "USA";


Boolean variable includes true and false. false can also be represented by 0, null, undefined, NaN or "". true can also be represented by all characters that are not false, e.g. 1, a, ...

if (true) alert("true"); //alert box showed
if (1) alert("true"); //alert box showed
if (0) alert("true"); //alert box NOT showed
if ("") alert("true"); //alert box NOT showed
if ('a') alert("true"); //alert box showed


javascript Objects:

var obj = {"city" : "New York", "country" : "USA"};

Click here for more JS Objects tutorial.

constructor property can be used to check the variable's constructing prototype:

var x = 3;
var y = x.constructor;
//y = "function Number() {[native code]}"


convert.idontcarewhatyouthink.net © 2021  Terms of Use | Home