Skip to content

Types of objects in JavaScript

  • by

JavaScript has several types of objects, including built-in objects like Math and Date, host objects provided by the ECMAScript6, and user-defined objects created by developers.

In JavaScript, there are several types of objects, including:

  1. Built-in Objects:
    • Global objects: like Math, Date, JSON.
    • Fundamental objects: like Object, String, Number, Boolean, Symbol.
    • Error objects: like Error, SyntaxError, TypeError, ReferenceError, and others.
  2. Host Objects:
    • Provided by the environment, such as a web browser or Node.js environment.
    • Examples: window, document, XMLHttpRequest, console, and others.
  3. User-defined Objects:
    • Created by the developer, using Object, Function, Array, or class keyword.

All JavaScript objects have a prototype property that allows them to inherit properties and methods from other objects.

Types of objects in JavaScript example

Simple example code.

<!DOCTYPE html>
<html>
<body>
<script>
    // Global objects
    console.log(Math.PI); 
    console.log(new Date()); 
    console.log(JSON.parse('{"name":"John", "age":30}'));

    // Fundamental objects
    var person = {name: "John", age: 30};
    console.log(typeof person); 

    var str = "Hello, World!";
    console.log(typeof str); 

    var num = 42;
    console.log(typeof num); 

    var bool = true;
    console.log(typeof bool); 

    var sym = Symbol("foo");
    console.log(typeof sym);

    // User-defined Objects
    function Car(make, model, year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    Car.prototype.getMakeModelYear = function() {
        return this.make + ' ' + this.model + ' ' + this.year;
    }

    var myCar = new Car("Honda", "Civic", 2022);
    console.log(myCar.getMakeModelYear());

</script>
</body>
</html>

Output:

Types of objects in JavaScript

Error objects: Error, SyntaxError, TypeError, ReferenceError, and others.

try {
  var x = y + 1; // y is not defined
}
catch(err) {
  console.log(err instanceof ReferenceError); // Output: true
}

Host Objects: Provided by the environment, such as a web browser or Node.js environment.

console.log(window.location.href); // Output: current URL
console.log(document.querySelector("h1").textContent); // Output: text content of the first <h1> element in the document

Comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading