Javascript Primitive Data Types
It’s important to understand that there are 5 primitive data types in Javascript. Knowing these by heart would be a good idea. The 5 data types are:
- Number (All javascript numbers are floating point – meaning a 5 is actually 5.0);
- String: Any string of text.
- Boolean: True or False.
- Undefined: The default state of a variable before a value is assigned to it.
- Null: Equivalent of nothing.
Examples of other data types which are not classified as ‘primitive’ data types would be objects or arrays
DYNAMIC TYPES.
Javascript has dynamic typing, meaning a variable can be any type. In Java for example, a variable equal to “ConquerJS” would be a string.
Java:
String blogName = "ConquerJS";
If I changed my blog’s name to a number I loved for some reason, like 3456729, in Java, I could not change ‘blogName’ to that number. I would have to create a new “int” variable to hold my new blog name (Of course I could always make the new numeric blogName a string by wrapping it in quotes).
Javascript:
in Javascript, variable types are processed dynamically, so I can do the following:
var blogName = "ConquerJS";
blogName = 15; <---- This works, my variable now holds a number.
TYPE COERCION
I can concatenate different data types and javascript will convert those types to one type. For example , if you have
var name = "rup";
var age = 50;
var handsome = false;
I can add them together like
console.log(name + age + handsome);
This will evaluate to a string, since you can’t turn a string into a number most of the time because words are not numbers, but numbers can always be strings, as can Booleans.