I am not able to understand exactly what is difference between primitive and non primitive data types in JavaScript even it is declared using same name i.e var.
问题:
回答1:
Data Types (JavaScript):
Primary Data Types
The primary (primitive) data types are:
String, Number, Boolean
Composite Data Types
The composite (reference) data types are:
Object, Array
Special Data Types
The special data types are:
Null, Undefined
Click here for details:
var test1 = 1;
var test2 = "Something";
var test3 = true;
var test4 = {};
var test5 = new Array();
var test6 = new Date();
var test7;
var test8 = null;
alert(typeof (test1)); //number
alert(typeof (test2)); //string
alert(typeof (test3)); //boolean
alert(typeof (test4)); //object
alert(typeof (test5)); //object
alert(typeof (test6)); //object
alert(typeof (test7)); //undefined
alert(typeof (test8)); //object
回答2:
Javascript has five primitive data types: 1. number 2. string 3. boolean 4. undefined 5. null
Anything that doesn’t belong to any of these five primitive types is considered an object.
First 3 data types has a corresponding object constructor. For example
var word = "something";
And then as an object:
var word = new String("something");
For object constructor notice the new
keyword. It creates object reference.
Another thing to notice that
var greeting = "something";
var word = new String("something");
greeting == word ----> True as their value is same
greeting === word -----> False because there value same but type is different .
As for var keyword being same for all the cases,remember that Javascript is dynamically typed language. That means it resolves data type checking during runtime rather than compile time(like Java, C++ ).
This makes javascript extremely powerful. Though this unique feature has drawback too. Please co through this wikipedia for details: https://en.wikipedia.org/wiki/Type_system#Static_and_dynamic_type_checking_in_practice
Hope this helps.
回答3:
According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
Primitive Data types in ES6 are: Boolean Null Undefined Number String Symbol
The other data type which is not a primitive one is Object
Primitive data types are immutable values.