DEV Community

Cover image for A Detailed Introduction To JavaScript Objects
Jason Smith
Jason Smith

Posted on

A Detailed Introduction To JavaScript Objects

In JavaScript, objects play a fundamental role in representing and storing data. Objects are versatile and crucial in many aspects of the language, making it essential to grasp their concepts thoroughly before delving into more complex aspects of JavaScript. To understand objects, let's explore their creation, properties, methods, and unique features.

Creating Objects

Objects in JavaScript can be created in two primary ways: using the "object constructor" syntax or the "object literal" syntax.

Object Constructor Syntax

You can create an empty object using the object constructor syntax as follows:

let user = new Object(); // Creates an empty object
Enter fullscreen mode Exit fullscreen mode

Object Literal Syntax

The more common and concise method is to use the object literal syntax:

let user = {}; // Creates an empty object using the object literal syntax
Enter fullscreen mode Exit fullscreen mode

Both methods create an empty object, and you can add properties to it as needed.

Properties and Values

In JavaScript objects, properties are essentially keys that are associated with values. You can think of an object as a cabinet with labeled files, where each property is a label (key) and the associated value is the content of the file. For instance:

let user = {
  name: "John", // Property "name" with the value "John"
  age: 30       // Property "age" with the value 30
};
Enter fullscreen mode Exit fullscreen mode

Here, the user object contains two properties: "name" with the value "John" and "age" with the value 30. You can access these property values using the dot notation, such as user.name or user.age.

Adding and Removing Properties

You can easily add or remove properties from an object. To add a property, simply assign a value to it:

user.isAdmin = true; // Adds a new property "isAdmin" with the value true
Enter fullscreen mode Exit fullscreen mode

To remove a property, you can use the delete operator:

delete user.age; // Removes the "age" property from the object
Enter fullscreen mode Exit fullscreen mode

Handling Multiword Properties

While single-word properties are commonly used, you can also have multiword properties by placing the property name in quotes:

let user = {
  "likes birds": true // Property with a multiword name
};
Enter fullscreen mode Exit fullscreen mode

Remember to quote multiword property names to avoid syntax errors.

Trailing Commas

You can add a trailing comma to the last property in an object. This can make it easier to add, remove, or reorder properties in the object:

let user = {
  name: "John",
  age: 30, // Trailing comma is allowed
};
Enter fullscreen mode Exit fullscreen mode

Square Bracket Notation

In some cases, using the dot notation may not be suitable, especially when dealing with property names that are not valid variable identifiers or need to be computed. In such cases, you can use square brackets to access properties:

user["likes birds"] = true; // Adds a property with a multiword name
Enter fullscreen mode Exit fullscreen mode

You can also use square brackets to access properties dynamically, allowing for more flexibility:

let key = "likes birds";
user[key] = true; // Accessing a property using a variable
Enter fullscreen mode Exit fullscreen mode

This is particularly useful when you need to obtain property names from user input or dynamic sources.

Computed Properties

JavaScript supports computed properties, which allow you to create object properties with dynamic names. This can be done within an object literal:

let fruit = "apple";
let bag = {
  [fruit]: 5, // Property name is determined by the value of the 'fruit' variable
};
Enter fullscreen mode Exit fullscreen mode

This allows you to create properties with names based on variable values or expressions.

Property Value Shorthand

To simplify object creation, you can use property value shorthand. This shorthand allows you to use the same variable name as both the property name and its value:

function makeUser(name, age) {
  return {
    name, // Shorthand for name: name
    age,  // Shorthand for age: age
    // ...other properties
  };
}
Enter fullscreen mode Exit fullscreen mode

This shorthand makes your code more concise and readable.

Property Names Limitations

Unlike variables, there are no limitations on property names in JavaScript objects. They can have names that match reserved words or include special characters:

let obj = {
  for: 1,
  let: 2,
  return: 3
};
Enter fullscreen mode Exit fullscreen mode

You can use any string as a property name, and JavaScript will automatically convert other types (except symbols) to strings when used as property keys.

Property Existence and the "in" Operator

In JavaScript, you can test whether a property exists in an object using the "in" operator. This operator checks if a property with a specific name is present in the object:

let user = {
  name: "John",
  age: 30
};

console.log("age" in user);   // true, 'age' property exists
console.log("blabla" in user); // false, 'blabla' property does not exist
Enter fullscreen mode Exit fullscreen mode

This is especially useful when you want to check for the existence of a property without running into errors caused by accessing non-existing properties.

The "for...in" Loop

The "for...in" loop allows you to iterate through an object's properties, making it a powerful tool for working with objects:

let user = {
  name: "John",
  age: 30,
  isAdmin: true
};

for (let key in user) {
  console.log(key);        // Outputs property names: name, age, isAdmin
  console.log(user[key]);  // Outputs property values: John, 30, true
}
Enter fullscreen mode Exit fullscreen mode

It's important to note that properties in an object are not ordered by default. Integer properties are sorted, and others appear in the order they were created.

Ordering of Properties

The ordering of properties in an object depends on whether the properties are integers or non-integers. Integer properties are sorted in ascending order, while non-integer properties appear in the order they were added.

let codes = {
  "49": "Germany",
  "41": "Switzerland",
  "44": "Great Britain",
  "1": "USA"
};

for (let code in codes) {
  console.log(code); // Outputs: 1, 41, 44, 49
}
Enter fullscreen mode Exit fullscreen mode

To control the order of properties, you can use non-integer property names, which will maintain the order of insertion. You can prefix properties with a non-integer character, like a plus sign ('+'), to achieve this effect.

let codes = {
  "+49": "Germany",
  "+41": "Switzerland",
  "+44": "Great Britain",
  "+1": "USA"
};

for (let code in codes) {
  console.log(+code); // Outputs: 49, 41, 44, 1
}
Enter fullscreen mode Exit fullscreen mode

Understanding how properties are ordered is essential when working with objects, especially when you need to ensure a specific order or grouping.

In conclusion, JavaScript objects are fundamental in representing structured data. They provide a flexible way to store and access information through key-value pairs. Understanding how to create, access, and manipulate objects, as well as how properties are ordered, is essential for effective JavaScript.

If you enjoyed this article, do give me a follow here ❣️

Top comments (3)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

You can use any string as a property name, and JavaScript will automatically convert other types to strings when used as property keys

This is not entirely correct. Symbols can be used as object keys, and they will not be converted to Strings.

Collapse
 
thejason profile image
Jason Smith

You're right, symbols are not converted into string. Thanks for your feedback.

Collapse
 
sammaji profile image
Samyabrata Maji

Great article 🔥