English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript basic tutorial

JavaScript objects

JavaScript functions

JS HTML DOM

JS browser BOM

AJAX basic tutorial

JavaScript reference manual

JavaScript Object Creation

Objects are composed ofpropertiesandMethodsThe collection of data types.

Like many other programming languages, JavaScript objects can be compared to objects in real life.

In JavaScript, almost everything is an object:

  • Strings can be objects (if defined with the new keyword)

  • Numbers can be objects (if defined with the new keyword)

  • Boolean values can be objects (if defined with the new keyword)

  • Dates are always objects

  • Mathematics is always an object

  • Arrays are always objects

  • Regular expressions are always objects

  • Functions are always objects

  • Object is an object

All JavaScript values except primitives are objects.

JavaScript primitives

Primitive values are values that have no properties or methods.

In JavaScript, there are5types of primitive:

  • string

  • number

  • boolean

  • null

  • undefined

Objects are variables

JavaScript variables can only contain one value.

var user = "oldtoolbag.com";
Test and See‹/›

Objects are also variables, but objects can contain many values.

Objects can be written asname: valueThey are listed, and separated by colons ():

var user = {firstName: "Vishal", lastName: "Jodari", age:22, location: "New Delhi"};
Test and See‹/›

JavaScript objects are collections of unordered properties.

Object properties

Properties are associations between names and values in an object and can contain any data type.

Properties are usually the characteristics of an object.

propertiesproperty values
firstNameVishal
lastNameQiao Dali
age22
locationNew Delhi

You will learn more about properties in the next chapter.

Object methods

Methods are functions as object property values, so they are tasks that an object can perform.

Methods are stored as properties asfunction definition.

propertiesappropriate values
firstNameVishal
lastNameQiao Dali
age22
locationNew Delhi
getNamefunction() { return this.firstName + " " + this.lastName;}

Note:is a function stored as a property.

Creating a JavaScript object

JavaScript has many predefined objects. In addition, you can create your own objects.

There are many ways to create a new object:

  • UsingObject literals, which uses curly braces: {}

  • UsingObject constructor, which uses new Object()

  • Or, you can create a function firstConstructor   , and then instantiate an object by calling the function

Using object literals

UsingObject literalsThis is the simplest way to create a JavaScript object.

UsingObject literalsYou can define and create an object in a single statement.

The following example creates a new JavaScript object with four properties:

var user = {firstName: "Vishal", lastName: "Jodari", age:22, location: "New Delhi"};
Test and See‹/›

Object definitions can span multiple lines:

var user = {
  firstName: "Vishal",
  lastName: "Qiao Dali",
  age: 22,
  location: "New Delhi"
};
Test and See‹/›

Using new Object()

UsingObject constructorThis is another way to create a JavaScript object.

The following example creates a new JavaScript object with four properties:

var user = new Object();
user.firstName = "Vishal";
user.lastName = "Qiao Dali";
user.age = 22;
user.location = "New Delhi";
Test and See‹/›

The two examples above are completely the same. There is no need to use new Object().

UsingObject literalsis the more common and preferred method because it is less likely to produce inconsistent and unexpected results.

Using a constructor

Additionally, you can create an object in the following two steps:

  • By writingConstructorDefine an object type (conventionally using uppercase first letter)

  • Example of creating an object using the new keyword

The following example defines an object type by writing a constructor:

  function User(fname, lname, age, loc) {
   this.firstName = fname;
   this.lastName = lname;
   this.age = age;
   this.location = loc;
  }

Now we can create a user nameduser1objects, as shown below:

var user1 = new User("Vishal", "Jodari", 22, "New Delhi");
Test and See‹/›

We will discuss this in the later part of this tutorialConstructor.

JavaScript objects are mutable

Mutation is a variable that can be changed. In JavaScript, only objects and arrays are mutable, not primitive values.

Mutable objectsis an object whose state can be modified after it is created.

Immutableare objects that cannot be changed once the object is created.

stringsandnumbersisImmutable. Let's understand this with an example:

  var immutableString = "Hello";
  
  // In the above code, a new object with a string value is created.
  
  immutableString = immutableString + "World";
  
  // Now we will append "World" to the existing value.

After appending "immutableString" to the string value, the following events will occur:

  • The existing value of "immutableString" is retrieved

  • "World" is appended to the existing value of "immutableString"

  • Then the result value is allocated to the new memory block

  • Now, the "immutableString" object points to the newly created memory space

  • The memory space created previously is now available for garbage collection

Objects are mutable: they are addressed by reference rather than by value.

If user is an object, the following statement will not create a copy of the user:

  var x = user;  // This will not create a copy of user.

Object x is not a copy of user; it is user. x and user are the same object.

Any changes to x will also change user, because x and user are the same object.

var user = {firstName: "Vishal", lastName: "Jodari", age:22, location: "New Delhi"};
var x = user;
x.location = "Goa";// This will change both x.location and user.location at the same time
Test and See‹/›

Compare Objects

In JavaScript, objects are reference types. Even if two different objects have the same properties, they will never be equal.

// Two variables, two objects with the same properties
var fruit = {name: "apple"};
var fruitbear = {name: "apple"};
fruit == fruitbear;  // Return false
fruit === fruitbear; // Return false
Test and See‹/›

Only comparing the same object reference with itself will result in true:

// Two variables, one object
var fruit = {name: "apple"};
var fruitbear = fruit;  // Assign the fruit object reference to fruitbear
// Here, fruit and fruitbear both point to the same object
fruit == fruitbear; // Return true
fruit === fruitbear; // Return true
Test and See‹/›