Table of Contents
What are JavaScript Objects?
In JavaScript, almost everything is an Object. Therefore, understanding JavaScript Objects means understanding JavaScript.
An Object is a collection of key-value pairs ( properties ), where the keys are usually strings ( or symbols ) and values can be any type of JavaScript value, including other objects.
Objects can have methods. A Method in an object is actually a function that is a property of the object. Methods can be called on the object, and they can access and manipulate the object’s properties.
const car = {
make: "Honda",
model: "Civic",
year: 2022,
color: "blue",
isElectric: false,
honk: function() {
console.log("Beep beep!");
}
};
// Accessing object properties
console.log(car.make); // Output: "Honda"
console.log(car.year); // Output: 2022
// Calling the method
car.honk(); // Output: "Beep beep!"
JavaScript objects are dynamic, which means that properties and methods can be added, deleted, or modified at any time.
Objects are reference types. This means that when you assign an object to a variable, you are assigning a reference to the object( address of the object ) and not a copy of the object. For example, in the above code the “car”, the constant variable, now has a reference to the object.
In addition to user-defined objects, JavaScript has built-in objects( Standard built-in Objects ) such as Array, Date, and Math, which are used extensively in JavaScript programming.
How to create Objects
There are many ways to create JavaScript objects. We are going to see the some of most common ways.
1. Object literal syntax
The simplest way is to use object-literal syntax.
All you need to do is to embed the key-value pairs( properties ) inside curly braces( { } ) and assign it a variable so that you can use this object in your code later.
const person = {
name: "John",
age: 30,
isEmployed: true
};
You can access these properties with dot notation.
console.log(person.name); // Output: "John"
console.log(person.age); // Output: 30
console.log(person.isEmployed); // Output: true
2. Constructor functions with the new keyword
Another way to create JavaScript objects is by using constructor functions with the new keyword. A Constructor is a special function that is used to create and initialize objects with properties and methods. For example:
function Person(name, age, isEmployed) {
this.name = name;
this.age = age;
this.isEmployed = isEmployed;
}
const person = new Person("John", 30, true);
console.log(person.name); // Output: "John"
In general, this is the way to create built-in JavasCript objects in your code. For example
const d = new Date();
In this case, you do not need to worry about creating a constructor. All you need to do is call the built-in constrictor to create the Date object.
3. Object.create() method
This is probably the least used way ( compared to the other two methods mentioned above ) to create objects in JavaScript.
const personProto = {
greet: function() {
console.log(`Hello, my name is ${this.name}!`);
}
};
const person = Object.create(personProto);
person.name = "John";
person.age = 30;
person.isEmployed = true;
person.greet(); // Output: "Hello, my name is John!"
Working with Object properties
Accessing Object properties
There are two ways to access object properties.
1. using dot notation
You can access ( read ) values of properties with dot notation. You need to use the name of the object followed by a dot( .) and then a key to get the value associated with the key.
Syntax: objectName.key
console.log(person.name); // Output: "John"
console.log(person.age); // Output: 30
console.log(person.isEmployed); // Output: true
2. using bracket notation
Another way is to use bracket Notation.
Syntax: objectName["key"]
console.log(person[“name”]); // Output: "John"
console.log(person[“age”]); // Output: 30
console.log(person.[“isEmployed”]); // Output: true
Should I use dot notation or bracket notation?
Many JavaSript developers tend to use dot notation rather than bracket notation, because of dot notation’s readability, accuracy(lack of typing errors), and ease of use. In addition, using dot notation can be significant in an application that requires high performance, There are situations in which you must use bracket notation
Invalid property names (if it is used in dot notation)
Some property names may be invalid if accessed with dot notation, for example, if an object has a property name containing a space, it cannot be accessed with dot notation. Thus, you must use bracket notation.
console.log( person["first name"]);
Unknown property name
Bracket notation is necessary or more appropriate;
- When the property name is not known until runtime.
const obj = {
firstName: 'John',
lastName: 'Doe'
};
// Prompt the user to enter a property name
const propertyName = prompt('Enter a property name:');
// Use bracket notation to access the property with the name entered by the user
console.log(obj[propertyName]);
- When the property name is a variable
const obj = {
firstName: 'John',
lastName: 'Doe'
};
// Assign the property name to a variable
const propertyName = 'lastName';
// Use bracket notation to access the property with the variable as the key
console.log(obj[propertyName]);
Adding new properties or updating existing properties
You can use either dot or bracket notation with the following syntax to add a new property to an object or update( change) an existing property value.
objectName.key = value or objectName[‘key’] = value
person.job = “developer” //adding new property
person[‘job’]= “developer”
person.name = ‘jane’ //updating existing property
person[‘name’] = ‘jane’
Here, the ‘job’ is the key of the property, and the ‘developer’ is the value.
After adding the new property the person’s object would be like this.
{
‘name’ : ‘jane’,
‘age’ : ‘30’,
‘isEmployed’: true,
‘job’:’developer’
}
Deleting properties of an object
You can use the delete operator to remove properties from an object.
let person = {
name: "John",
age: 30,
isEmployed: true,
job:’developer’
};
delete person.age;//or wih bracket notaion delete person["age"];
console.log(person); // Output: {firstName: "John", lastName: "Doe"}#
JavaScript Standard built-in object
In JavaScript programming, standard built-in objects (or just built-in objects) are widely used.
These standard objects are categories based on their purpose and functionality.
- Value properties
- Function Properties
- Fundamental objects
- Numbers and Dates ( ex: Date object )
- Text processing ( ex: String Object )
- Indexed collections( ex: Map Object, Array Object )
- Keyed collections
- Structured data
- Control abstraction objects
- Reflection
- Internationalization
Some built-in objects are less likely to use than others. Even at the beginning of your journey as a developer, for example, you might have used an Object belonging to the Number and Dates category.
While it is not necessary to master the usage of every category, I will recommend you be familiar first with commonly used objects such as String, Date, Math, Array, and so on.
Resources
You can use the following resources as references in learning about JavaScript objects.