Variables in Javascript
August 3, 2017 Leave a comment
Javascript is type inferenced which mean based on the value it will identify the type and hence we dont have to explicitly specify the type.
There are 3 primitive data types and undefined, null
- Number: These are double precision 64 bit format (there are no Integers, Short, Float so on)
- String: Sequqnces of Unicode Characters (no char type)
- Boolean: It is of type ‘Boolean’ with two possible values ‘true/false’
- undefined: It is of type ‘undefined’ with two possible values ‘undefined’. Value assigned to every declared variable until its defined.
- Ex var value; value = 10; //value between these two statements is value ‘undefined’ of type ‘undefined’
- null: It is of type ‘null’ with two possible values ‘null’.
- In ECMA6, new variable called Symbol is introduced just like ENUMs
Note: There is no scoping information attached to variable declarations and hence all declared variables are by default global.
Variables and Values can be interrogated using ‘typeof’
typeof <variable> typeof <value> var a; console.log(typeof a); a = 10; console.log(typeof a); a = "hello"; console.log(typeof a); a = true; console.log(typeof a); a = null; console.log(typeof a);
Null is a typeof Object
* a=null; typeof a – returns object instead of null, it was a bug in early versions of JS but its not fixed in newer versions bcos it breaks backward compatibility and many web applications will break.
Type Coercion: As JS was introduced to be friendly language with developers and they did type conversion of variables used in the expression and this lead to many confusions and later they fixed it but because of backward compatibility we still live with them. One such issue is ‘==’
- double equals == and triple equals ===
- 12 + “4” -> results in “124” because it looks at expression and finds one is string and other is number and hence coerce number into string so that it can do string concatenation
* JS does a lot of type coercion and hence the behavior is unpredictable lot of times, beware of it
var a = 10; var b = "10"; a == b -> returns true, whereas a === b -> returns false
Values of all types have associated boolean value
- Non zero numbers can be passed to a if loop which returns true
- Non empty strings can be passed to a if loop which returns true
- undefined and null are always false
var a = 10; if(a) { console.log("a is true"); } else { console.log("a is false"); } a = 0; if(a) { console.log("a is true"); } else { console.log("a is false"); } a = "Hello"; if(a) { console.log("a is true"); } else { console.log("a is false"); } a = ""; if(a) { console.log("a is true"); } else { console.log("a is false"); }
Recent Comments