Tuesday, June 2, 2015

JavaScript's 9 Native Object Constructors

In JavaScript almost everything is object or act like object. Most values (excluding primitive values) involve object being created or instantiated from constructor function. An object returned from the constructor is called an instance. JavaScript uses native constructor to build everything.

JavaScript has nine native constructors to achieve everything in JavaScript programming language. For example functions are objects created from Function() constructor. String(), Boolean() and Number() constructors are not only construct objects but also provide primitive value for string, Boolean, and number.

  • String()
  • Boolean()
  • Number()
  • Object()
  • Function()
  • Array()
  • RegExp()
  • Error()
  • Date()

To remember these 9 native constructors I have created one acronym "SBN OF A RED". This acronym is easy to learn and also in relevant groups.

To create a number variable in JavaScript there are 2 ways:

  1. var iMyNumberPrimitive = 9;
  2. var iMyNumberObject = new Number(9);
First method is to just create primitive value for number, string or Boolean. Second method create complex object with primitive value. You can see below the behavior of such declarations with console:

Same way we can create other type of variables also. It is good practice to use simple primitive variable declaration always if we want normal variables operations, because JavaScript create complex object when you use constructor and will have many other properties associated with variable.

No comments:

Post a Comment