JavaScript (4) Objects

1. Types:

The following are the built-in types in JavaScript:

  1. string
  2. number
  3. boolean
  4. null and undefined
  5. object
  6. symbol (new to ES6)

We can use typeof() to check the type of the variable. !! However typeof(null) does not return "null", it returns "object".

typeof(null)
// "object"

2. Objects:

The object type refers to a compound value where you can set properties (named locations) that each hold their own values of any type.

var dog = { 
  name: "doggy", 
  age: 3 
};

// access the properties with . operator
dog.name;
dog.age;

// access the properties with [] operator
dog["name"]
dog["age"]

3. Arrays:

Array in JS can be used to save the values with different types which is different to the array in C.

var arr = [
  "hello",
  42,
  true
];

// access the array with index
arr[0];
arr[1];
arr[2];

typeof(arr); // object

!! Array is an object which does not hold the values in named properties/keys, but rather in numerically indexed positions.


Reference

[1] Kyle Simpson, You Don't Know JS Series, O'Reilly Media (2014)

留言

熱門文章