Javascript 101
1.2 Variables
1.2 Variables
Variable Declaration and Assignment
Variables are declared using the var
keyword. JS is dynamically typed (i.e.
the type of variables can change at runtime). For example, you can assign an
integer to a variable and along the way assign a string to the same variable
(thus changing the type of the variable to string type). typeof
is a special
operator for getting the type of a variable (in string format).
var a = 5;console.log(a + " " + typeof a); //5 numbera = "hello";console.log(a + " " + typeof a); //hello string
//declare multiple variablesvar n1, n2;
Datatypes
JS has 6 primitive data types: undefined
, null
, number
, string
,
boolean
, and symbol
. You can choose to enclose strings with single quotes
('
) or double quotes ("
) - just use the matching type of quotes. There is
also the object
type for complex type. You can also assign functions to a
variable.
typeof 1; //numbertypeof 1.12; //numbertypeof "Tom"; //stringtypeof true; //booleanString(1234); //"1234"typeof String(1234); //string
typeof { name: "John" }; //objecttypeof [1, 2, 3]; //objecttypeof new Date(); //object
var f = function () {};typeof f; //function
Undefined vs Not Defined
Other than assigning proper values to a variable, there are also other special
values (null
and undefined
) in Javascript. Note that undefined
is not the
same as not defined
. A variable takes on the value of undefined
if it is
declared but not assigned any value. Whereas, if you try to access a variable
that is not declared, an error is thrown indicating that the variable is
not defined
(or not declared).
var c = null;console.log(c + " " + typeof c); //null object
var b; //same as b = undefinedconsole.log(b + " " + typeof b); //undefined undefinedconsole.log(d + " " + typeof d); //Error: d is not defined
undefined + "abc"; //"undefinedabc"undefined + "1"; //undefined1
typeof (undefined + "abc"); //string
Auto Type Conversion
Javascript does auto type conversion when you assign a value to a variable. It tries its best to determine the type of your variable/expression. JS also performs type coercion when an expression contains multiple types. You are allowed to concatenate different data types (e.g. a string with a number) like in the case of Java.
1 / 10; //0.10.9 + 0.1; //1
1 / "10"; //0.1"10" * "2"; //20
1 + "10"; //"110""10" + 1; //"101"+"10" + 1; //11"123" - 3; //120
1 + true; //2true + "hello"; //"truehello"
Number("100") + 200; //300Number(" "); //0 (same as Number(""))
Like with most programming languages, when handling numeric arithmetic, NaN
(Not a Number) and Infinity
cases are usually quite weird.
undefined + 1; //NaNtypeof NaN; // number
1 / 0; //Infinitytypeof (1 / 0); //numbertypeof Infinity; //number
1 / 0 - 1; //InfinityInfinity - Infinity; //NaNInfinity + Infinity; //InfinityInfinity * Infinity; //InfinityInfinity / Infinity; //NaN