- How to create objects in JavaScript
- 1. Creating objects using object literal syntax
- 2. Creating objects using the ‘new’ keyword
- 3. Using Object.create() to create new objects
- 4. Using Object.assign() to create new objects
- 5. Using ES6 classes to create objects
- JavaScript Objects
- JavaScript Primitives
- Examples
- Immutable
- Objects are Variables
- Example
- Example
- Example
- Object Properties
- Object Methods
- Creating a JavaScript Object
- Using an Object Literal
- Example
- Example
- Example
- Using the JavaScript Keyword new
- Example
- JavaScript Objects are Mutable
- Example
How to create objects in JavaScript
We all deal with objects in one way or another while writing code in a programming language. In JavaScript, objects provide a way for us to store, manipulate, and send data over the network.
There are many ways in which objects in JavaScript differ from objects in other mainstream programming languages, like Java. I will try to cover that in a another topic. Here, let us only focus on the various ways in which JavaScript allows us to create objects.
In JavaScript, think of objects as a collection of ‘key:value’ pairs. This brings to us the first and most popular way we create objects in JavaScript.
1. Creating objects using object literal syntax
This is really simple. All you have to do is throw your key value pairs separated by ‘:’ inside a set of curly braces(< >) and your object is ready to be served (or consumed), like below:
This is the simplest and most popular way to create objects in JavaScript.
2. Creating objects using the ‘new’ keyword
This method of object creation resembles the way objects are created in class-based languages, like Java. By the way, starting with ES6, classes are native to JavaScript as well and we will look at creating objects by defining classes towards the end of this article. So, to create an object using the ‘new’ keyword, you need to have a constructor function.
Here are 2 ways you can use the ‘new’ keyword pattern —
a) Using the ‘new’ keyword with’ in-built Object constructor function
To create an object, use the new keyword with Object() constructor, like this:
Now, to add properties to this object, we have to do something like this:
person.firstName = 'testFirstName'; person.lastName = 'testLastName';
You might have figured that this method is a bit longer to type. Also, this practice is not recommended as there is a scope resolution that happens behind the scenes to find if the constructor function is built-in or user-defined.
b) Using ‘new’ with user defined constructor function
The other problem with the approach of using the ‘Object’ constructor function result from the fact that every time we create an object, we have to manually add the properties to the created object.
What if we had to create hundreds of person objects? You can imagine the pain now. So, to get rid of manually adding properties to the objects, we create custom (or user-defined) functions. We first create a constructor function and then use the ‘new’ keyword to get objects:
function Person(fname, lname)
Now, anytime you want a ‘Person’ object, just do this:
const personOne = new Person('testFirstNameOne', 'testLastNameOne'); const personTwo = new Person('testFirstNameTwo', 'testLastNameTwo');
3. Using Object.create() to create new objects
This pattern comes in very handy when we are asked to create objects from other existing objects and not directly using the ‘new’ keyword syntax. Let’s see how to use this pattern. As stated on MDN:
The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.
To understand the Object.create method, just remember that it takes two parameters. The first parameter is a mandatory object that serves as the prototype of the new object to be created. The second parameter is an optional object which contains the properties to be added to the new object.
We will not deep dive into prototypes and inheritance chains now to keep our focus on the topic. But as a quick point, you can think of prototypes as objects from which other objects can borrow properties/methods they need.
Imagine you have an organization represented by orgObject
And you want to create employees for this organization. Clearly, you want all the employee objects.
const employee = Object.create(orgObject, < name: < value: 'EmployeeOne' >>); console.log(employee); // < company: "ABC Corp" >console.log(employee.name); // "EmployeeOne"
4. Using Object.assign() to create new objects
What if we want to create an object that needs to have properties from more than one object? Object.assign() comes to our help.
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
Object.assign method can take any number of objects as parameters. The first parameter is the object that it will create and return. The rest of the objects passed to it will be used to copy the properties into the new object. Let’s understand it by extending the previous example we saw.
Assume you have two objects as below:
const orgObject = < company: 'ABC Corp' >const carObject =
Now, you want an employee object of ‘ABC Corp’ who drives a ‘Ford’ car. You can do that with the help of Object.assign as below:
const employee = Object.assign(<>, orgObject, carObject);
Now, you get an employee object that has company and carName as its property.
5. Using ES6 classes to create objects
You will notice that this method is similar to using ‘new’ with user defined constructor function. The constructor functions are now replaced by classes as they are supported through ES6 specifications. Let’s see the code now.
class Person < constructor(fname, lname) < this.firstName = fname; this.lastName = lname; >> const person = new Person('testFirstName', 'testLastName'); console.log(person.firstName); // testFirstName console.log(person.lastName); // testLastName
These are all the ways I know to create objects in JavaScript. I hope you enjoyed this post and now understand how to create objects.
Thanks for your time for reading this article. If you liked this post and it was helpful to you, please click the clap ? button to show your support. Keep learning more!
JavaScript Objects
In JavaScript, objects are king. If you understand objects, you understand JavaScript.
In JavaScript, almost «everything» is an object.
- Booleans can be objects (if defined with the new keyword)
- Numbers can be objects (if defined with the new keyword)
- Strings can be objects (if defined with the new keyword)
- Dates are always objects
- Maths are always objects
- Regular expressions are always objects
- Arrays are always objects
- Functions are always objects
- Objects are always objects
All JavaScript values, except primitives, are objects.
JavaScript Primitives
A primitive value is a value that has no properties or methods.
3.14 is a primitive value
A primitive data type is data that has a primitive value.
JavaScript defines 7 types of primitive data types:
Examples
- string
- number
- boolean
- null
- undefined
- symbol
- bigint
Immutable
Primitive values are immutable (they are hardcoded and cannot be changed).
if x = 3.14, you can change the value of x, but you cannot change the value of 3.14.
Value | Type | Comment |
---|---|---|
«Hello» | string | «Hello» is always «Hello» |
3.14 | number | 3.14 is always 3.14 |
true | boolean | true is always true |
false | boolean | false is always false |
null | null (object) | null is always null |
undefined | undefined | undefined is always undefined |
Objects are Variables
JavaScript variables can contain single values:
Example
JavaScript variables can also contain many values.
Objects are variables too. But objects can contain many values.
Object values are written as name : value pairs (name and value separated by a colon).
Example
A JavaScript object is a collection of named values
It is a common practice to declare objects with the const keyword.
Example
Object Properties
The named values, in JavaScript objects, are called properties.
Property | Value |
---|---|
firstName | John |
lastName | Doe |
age | 50 |
eyeColor | blue |
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
Object Methods
Methods are actions that can be performed on objects.
Object properties can be both primitive values, other objects, and functions.
An object method is an object property containing a function definition.
Property | Value |
---|---|
firstName | John |
lastName | Doe |
age | 50 |
eyeColor | blue |
fullName | function() |
JavaScript objects are containers for named values, called properties and methods.
You will learn more about methods in the next chapters.
Creating a JavaScript Object
With JavaScript, you can define and create your own objects.
There are different ways to create new objects:
- Create a single object, using an object literal.
- Create a single object, with the keyword new .
- Define an object constructor, and then create objects of the constructed type.
- Create an object using Object.create() .
Using an Object Literal
This is the easiest way to create a JavaScript Object.
Using an object literal, you both define and create an object in one statement.
An object literal is a list of name:value pairs (like age:50) inside curly braces <>.
The following example creates a new JavaScript object with four properties:
Example
Spaces and line breaks are not important. An object definition can span multiple lines:
Example
This example creates an empty JavaScript object, and then adds 4 properties:
Example
const person = <>;
person.firstName = «John»;
person.lastName = «Doe»;
person.age = 50;
person.eyeColor = «blue»;
Using the JavaScript Keyword new
The following example create a new JavaScript object using new Object() , and then adds 4 properties:
Example
const person = new Object();
person.firstName = «John»;
person.lastName = «Doe»;
person.age = 50;
person.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.
JavaScript Objects are Mutable
Objects are mutable: They are addressed by reference, not by value.
If person is an object, the following statement will not create a copy of person:
The object x is not a copy of person. It is person. Both x and person are the same object.
Any changes to x will also change person, because x and person are the same object.
Example
const person = <
firstName:»John»,
lastName:»Doe»,
age:50, eyeColor:»blue»
>
const x = person;
x.age = 10; // Will change both x.age and person.age