DEV Community

diego michel
diego michel

Posted on

what is an object in javascript?

An object is an unordered collection of properties, each of which has a name and a value. Property names are usually strings, so we can say that objects map strings to values. This string-to-value mapping goes by various names—you are probably already familiar with the fundamental data structure under the name “hash,” “hashtable,” “dictionary,” or “associative array.

Creating Objects
Objects can be created with object literals, with the new keyword, and with the Object.create() function. The subsections below describe each technique.

Object Literals
The easiest way to create an object is to include an object literal in your JavaScript code. an object literal is a comma-separated list of colon-separated name:value pairs, enclosed within curly braces.

let empty = {};                          // object with no properties
let point = { x: 0, y: 0 };              // Two numeric properties
let p2 = { x: point.x, y: point.y+1 };   // More complex values
let book = {
    "main title": "JavaScript",          // These property names include spaces,
    "sub-title": "The Definitive Guide", // and hyphens, so use string literals.
    for: "all audiences",                // for is reserved, but no quotes.
    author: {                            // The value of this property is
        firstname: "David",              // itself an object.
        surname: "Flanagan"
    }
};
Enter fullscreen mode Exit fullscreen mode

Creating Objects with new
The new operator creates and initializes a new object.

let o = new Object();  // Create an empty object: same as {}.
let a = new Array();   // Create an empty array: same as [].
let d = new Date();    // Create a Date object representing the current time
let r = new Map();     // Create a Map object for key/value mapping

Enter fullscreen mode Exit fullscreen mode

Prototypes
Almost every JavaScript object has a second JavaScript object associated with it. This second object is known as a prototype, and the first object inherits properties from the prototype.

All objects created by object literals have the same prototype object, and we can refer to this prototype object in JavaScript code as Object.prototype

Object.create()
Object.create() creates a new object, using its first argument as the prototype of that object.

const person = {
  isHuman: false,
  printIntroduction: function() {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  }
};

const me = Object.create(person);

me.name = 'Matthew'; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // inherited properties can be overwritten

me.printIntroduction();
// expected output: "My name is Matthew. Am I human? true"

Enter fullscreen mode Exit fullscreen mode

Deleting Properties
The delete operator removes a property from an object. Its single operand should be a property access expression

delete book.author;          // The book object now has no author property.
delete book["main title"];   // Now it doesn't have "main title", either.

Enter fullscreen mode Exit fullscreen mode

Testing Properties
JavaScript objects can be thought of as sets of properties, and it is often useful to be able to test for membership in the set—to check whether an object has a property with a given name

Serializing Objects
Object serialization is the process of converting an object’s state to a string from which it can later be restored. The functions JSON.stringify() and JSON.parse() serialize and restore JavaScript objects.

Object Methods
The toString() Method

The toString() method takes no arguments; it returns a string that somehow represents the value of the object on which it is invoked. JavaScript invokes this method of an object whenever it needs to convert the object to a string

This occurs, for example, when you use the + operator to concatenate a string with an object or when you pass an object to a method that expects a string

let s = { x: 1, y: 1 }.toString();  // s == "[object Object]"

Enter fullscreen mode Exit fullscreen mode

Because this default method does not display much useful information, many classes define their own versions of toString() For example, when an array is converted to a string, you obtain a list of the array elements, themselves ea ch converted to a string, and when a function is converted to a string, you obtain the source code for the function. You might define your own toString() method like this:

let point = {
    x: 1,
    y: 2,
    toString: function() { return `(${this.x}, ${this.y})`; }
};
String(point)    // => "(1, 2)": toString() is used for string conversions

Enter fullscreen mode Exit fullscreen mode

toLocaleString() Method
In addition to the basic toString() method, objects all have a toLocaleString(). The purpose of this method is to return a localized string representation of the object. The default toLocaleString() method defined by Object doesn’t do any localization itself: it simply calls toString() and returns that value

let point = {
    x: 1000,
    y: 2000,
    toString: function() { return `(${this.x}, ${this.y})`; },
    toLocaleString: function() {
        return `(${this.x.toLocaleString()}, ${this.y.toLocaleString()})`;
    }
};
point.toString()        // => "(1000, 2000)"
point.toLocaleString()  // => "(1,000, 2,000)": note thousands separators

Enter fullscreen mode Exit fullscreen mode

The valueOf() Method
The valueOf() method is much like the toString() method, but it is called when JavaScript needs to convert an object to some primitive type other than a string—typically, a number. JavaScript calls this method automatically if an object is used in a context where a primitive value is required

let point = {
    x: 3,
    y: 4,
    valueOf: function() { return Math.hypot(this.x, this.y); }
};
Number(point)  // => 5: valueOf() is used for conversions to numbers
point > 4      // => true
point > 5      // => false
point < 6      // => true

Enter fullscreen mode Exit fullscreen mode

toJSON() Method
Object.prototype doe not actually define a toJSON() method, but the JSON.stringify() method looks for a toJSON() method on any object it is asked to serialize. If this method exists on the object to be serialized, it is invoked, and the return value is serialized, instead of the original object.

let point = {
    x: 1,
    y: 2,
    toString: function() { return `(${this.x}, ${this.y})`; },
    toJSON: function() { return this.toString(); }
};
JSON.stringify([point])   // => '["(1, 2)"]'

Enter fullscreen mode Exit fullscreen mode

Extended Object Literal Syntax
Shorthand Properties
Suppose you have values stored in variables x and y and want to create an object with properties named x and y that hold those values.

let x = 1, y = 2;
let o = {
    x: x,
    y: y
};

Enter fullscreen mode Exit fullscreen mode

In ES6 and later, you can drop the colon and one copy of the identifier and end up with much simpler code:

let x = 1, y = 2;
let o = { x, y };
o.x + o.y  // => 3v

Enter fullscreen mode Exit fullscreen mode

Computed Property Names
Sometimes you need to create an object with a specific property, but the name of that property is not a compile-time constant that you can type literally in your source code. Instead, the property name you need is stored in a variable or is the return value of a function that you invoke.

const PROPERTY_NAME = "p1";
function computePropertyName() { return "p" + 2; }

let o = {};
o[PROPERTY_NAME] = 1;
o[computePropertyName()] = 2;

Enter fullscreen mode Exit fullscreen mode

It is much simpler to set up an object like this with an ES6 feature known as computed properties that lets you take the square brackets from the preceding code and move them directly into the object literal:

const PROPERTY_NAME = "p1";
function computePropertyName() { return "p" + 2; }

let p = {
    [PROPERTY_NAME]: 1,
    [computePropertyName()]: 2
};

p.p1 + p.p2 // => 3

Enter fullscreen mode Exit fullscreen mode

Symbols as Property Names
The computed property syntax enables one other very important object literal feature. In ES6 and later, property names can be strings or symbols. If you assign a symbol to a variable or constant, then you can use that symbol as a property name using the computed property syntax:

const extension = Symbol("my extension symbol");
let o = {
    [extension]: { /* extension data stored in this object */ }
};
o[extension].x = 0; // This won't conflict with other properties of o

Enter fullscreen mode Exit fullscreen mode

Spread Operator
you can copy the properties of an existing object into a new object using the “spread operator” ... inside an object literal:

let position = { x: 0, y: 0 };
let dimensions = { width: 100, height: 75 };
let rect = { ...position, ...dimensions };
rect.x + rect.y + rect.width + rect.height // => 175

Enter fullscreen mode Exit fullscreen mode

If the object that is spread and the object it is being spread into both have a property with the same name, then the value of that property will be the one that comes last:

let o = { x: 1 };
let p = { x: 0, ...o };
p.x   // => 1: the value from object o overrides the initial value
let q = { ...o, x: 2 };
q.x   // => 2: the value 2 overrides the previous value from o.

Enter fullscreen mode Exit fullscreen mode

Shorthand Methods
When a function is defined as a property of an object, we call that function, you would define a method in an object literal using a function definition expression just as you would define any other property of an object:

let square = {
    area: function() { return this.side * this.side; },
    side: 10
};
square.area() // => 100

Enter fullscreen mode Exit fullscreen mode

the object literal syntax has been extended to allow a shortcut where the function keyword and the colon are omitted, resulting in code like this:

let square = {
    area() { return this.side * this.side; },
    side: 10
};
square.area() // => 100

Enter fullscreen mode Exit fullscreen mode

Top comments (0)