JavaScript Objects Introduction

This discussion of JavaScript objects is based on the book by Douglas Crockford called JavaScript: The Good Parts.

Simple Types

The simple types of JavaScript are numbers, strings, booleans (true and false), null, and undefined. All other values are objects.

Looking at for information on JS objects is very helpful. Here is some code from that web site.

<!DOCTYPE html>
<p>Creating a JavaScript Object.</p>
<p id="demo"></p>
var car = {type:"Fiat", model:"500", color:"white"};
document.getElementById("demo").innerHTML = car.type + " " + car.model;

In the browser, this is what it produces:


JS objects are created with var objectname {}. Objects are variables too. But objects can contain many values. This code assigns many values (Fiat, 500, white) to a variable named car. The values are written as name:value pairs (name and value separated by a colon). JavaScript objects are containers for named values. The name:values pairs (in JavaScript objects) are called properties.

JavaScript object notation uses the same syntax as JSON, which stands for JavaScript Object Notation.

Methods are actions that can be performed on objects. Methods are stored in properties as function definitions. JavaScript objects are containers for named values called properties or methods.

<p id="demo"></p>
var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    fullName : function() {
       return this.firstName + " " + this.lastName;
document.getElementById("demo").innerHTML = person.fullName();

The above code produces: John Doe

New Keyword

When a JavaScript variable is declared with the keyword new, the variable is created as an object. Do not declare strings, numbers or booleans as objects. They complicate your code and slow down execution speed.

var x = new String();        // Declares x as a String object
var y = new Number();        // Declares y as a Number object
var z = new Boolean();       // Declares z as a Boolean object

Leave a comment

Your email address will not be published. Required fields are marked *