Table of Contents
To add a key-value pair to a JavaScript object, you can use the dot notation or square bracket notation. Both methods achieve the same result, but they are used in different scenarios. Here are two possible approaches:
Using the Dot Notation
To add a key-value pair to a JavaScript object using the dot notation, follow these steps:
1. Access the object using the object name followed by a dot and the key name.
2. Assign a value to the key using the assignment operator (=).
Here's an example:
// Step 1 var person = {}; // Step 2 person.name = "John"; person.age = 30;
In this example, we create an empty object called person
in Step 1. In Step 2, we add the key-value pairs name: "John"
and age: 30
using the dot notation.
Related Article: How to Find All Mat Icons in Angular
Using the Square Bracket Notation
To add a key-value pair to a JavaScript object using the square bracket notation, follow these steps:
1. Access the object using the object name followed by square brackets containing the key name as a string.
2. Assign a value to the key using the assignment operator (=).
Here's an example:
// Step 1 var person = {}; // Step 2 person['name'] = "John"; person['age'] = 30;
In this example, we create an empty object called person
in Step 1. In Step 2, we add the key-value pairs name: "John"
and age: 30
using the square bracket notation.
Best Practices
Related Article: How to Check If a Variable Is a String in Javascript
When adding key-value pairs to a JavaScript object, it is important to follow best practices to ensure code readability and maintainability. Here are some best practices to consider:
1. Use meaningful key names: Choose descriptive key names that accurately represent the data they hold. This improves code readability and makes it easier for others to understand your code.
2. Encapsulate related data: If you have multiple key-value pairs that are related, consider grouping them together in an object or using nested objects. This helps organize your code and makes it easier to access related data.
3. Avoid using reserved words as keys: JavaScript has reserved words that cannot be used as keys in objects. Examples of reserved words include function
, return
, delete
, and typeof
. If you need to use a reserved word as a key, you can wrap it in quotes like object['function'] = ...
.
4. Use object literal syntax: When creating a new object, consider using object literal syntax ({}
) instead of the new Object()
syntax. Object literal syntax is more concise and easier to read.
5. Use computed property names: If you need to dynamically compute the key name, you can use computed property names introduced in ECMAScript 2015 (ES6). Computed property names allow you to use an expression inside square brackets to compute the key name. Here's an example:
var key = 'name'; var person = { [key]: 'John' };
In this example, the key name is computed using the value of the key
variable.