Ads Top


Native Objects

Native objects are built-in objects in JavaScript. They are pre-defined and are always available to us as long as we are using JavaScipt irrespective of the environment the JavaScript code is running. Some commonly used Native Objects in JavaScript are:
Click on each of the above native objects to know more about it.

Have a look at the following example:


// Using string native object
 var s = new String ("I am a string literal wrapped by an object wrapper");
 console.log(typeof s); //object

//converting string object to string literal
 s = s.toString(); 
 console.log(typeof s); //string

//an example of string literal
 var str = "I am a string literal";
 console.log(typeof str); //string


In the above code snippet, the result of the constructor form of value creation new String("I am a string literal wrapped by an object wrapper") is an object wrapper around the string literal* "I am a string literal wrapped by an object wrapper" value.

*String literal  - string denoted by single or double quotes, also known as primitive string. It is different than string object.

This is also true for number and boolean objects because number and boolean objects are also denoted by new keyword and can be used as native constructors unlike their primitive counterparts.

Host Objects

Host objects are the objects which are created and provided to JavaScript by the environment (host) which hosts the code. Be it in Node environment or in browser, the JavaScript code will behave differently when executed in different JavaScript engines. Since JavaScript always works in the context of the hosting environment, the result of executed code may differ depending on the current host.

One famous host object which developers interact regularly is - console object. It has several methods like .log(), .error(), .table(), dir(), info(), profile() etc. console object is provided by hosting environment so that JavaScript code can interact with the host for development related job. It may perform differently depending on the hosting environment which supplies the console object.


Consider the following code snippet:


bar();

var a = true;
if (a) {
 function bar(){console.log("print a");}
} else {
 function bar(){console.log("print b");}
}



We get the following output if we run this above piece of code in :

Chrome browser
Uncaught TypeError: bar is not a function
node.js
print b
The above code has executed differently in Chrome and node.js because in Chrome, console connects to the developer tools’ console display, whereas in node.js and other server-side JavaScript environments, console as a global instance is configured to write to the standard-output (stdout) and standard-error (stderr) streams of the JavaScript environment.

1 comment:

Powered by Blogger.