bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/JavaScript/Objects, Classes, and Advanced Patterns
JavaScript•Objects, Classes, and Advanced Patterns

JavaScript Object Definitions

Concept visual

JavaScript Object Definitions

keys map to buckets01kiwi:12pear:43apple:7grape:9

Methods for Defining JavaScript Objects

Using an Object Literal

Using the new

Keyword

Using an Object Constructor

Using

Object.assign()

Using

Object.create()

Using

Object.fromEntries()

Using an Object Literal

An object literal is a list of property key:values inside curly braces

{ }.
{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Example

// Create an Object const person = {
firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue"
};

Using the new

Keyword

Example

// Create an Object const person = new Object({
firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue"
});

The examples above do exactly the same. But, there is no need to use new Object(). For readability, simplicity and execution speed, use the object literal method. Objects written as name value pairs are similar to:

Associative arrays in PHP

Dictionaries in Python

Hash tables in C

Hash maps in Java

Hashes in Ruby and Perl

JavaScript Object.create()

The

Object.create() method creates an object from an existing object.

Example

// Create an Object:

const person = {
firstName: "John", lastName: "Doe"
};
// Create new Object const man = Object.create(person);
man.firstName = "Peter";

JavaScript Object fromEntries()

ES2019 added the Object method fromEntries()

to JavaScript.

The fromEntries()

Formula

method creates an object from iterable key / value pairs.

Example

const fruits = [
["apples", 300],
["pears", 900],
["bananas", 500]
];
const myObj = Object.fromEntries(fruits);

Previous

JS Temporal Arithmetic

Next

JS Temporal Differences