Primitive types:
- String
- Number
- Boolean
- Undefined
- Null
- Symbol
Symbol is a primitive data type of JavaScript, along with string, number, boolean, null and undefined. It was introduced in ECMAScript 2015. Once you create a symbol, its value is kept private and for internal use.
Reference types. Objects:
- Object
- Array
- Function
- Date
- RegExp
Example
“hello”.length
But how?
new String(“hello”).length;
notice the constructor
1 |
var obj = new String("hello"); |
type of obj –> “object”
typeof String(“hello”) –> “string”
obj.valueOf(); –> “hello”
typeof obj.valueOf(); –> “string”
Only way to create object is by using new String. All others will give you a string.
Similary,
//notice the constructor
1 |
var num = new Number(10); |
typeof num; –> “object”
typeof 10 –> “number”
typeof Number(10) –> “number”
typeof num.valueOf() –> “number”
remember that our num is an object
1 |
var sum = num + 10; |
typeof sum; –> “number”
typeof num; –> “object”
Even though num was used in a numeric operation, it did not get converted to number.
Cannot assign properties and methods to Primitives
For example
1 2 3 |
var num = 10; num.property = "hello"; num.property // undefined |
If we change num to object, then we can assign property and methods:
1 2 3 4 |
//notice the constructor, hence we creating object var num = new Number(10); num.property = "hello"; num.property //gives "hello" |