Introduction to JavaScript Objects

In the world of programming, JavaScript objects are like customizable containers where you can store different types of data in an organized manner. You can think of these objects as collections of 'properties'. Each property is a pairing of a unique key (like a label) and a value (the data you want to store under that label). This is similar to how a car can be characterized by its color, model, and manufacturer.

JavaScript objects are also known as dictionaries, and both terms are widely used. The analog with dictionaries comes from the fact that dictionaries also have words (keys) and their definitions (values).

Creating and Manipulating JavaScript Objects

There are a couple of ways to generate objects in JavaScript, but the most common one is via literal notation {}. Here is an example:

let car = {
  color: "red",
  model: "sedan",
  manufacturer: "Toyota",
};
console.log(car); // Outputs: {color: "red", model: "sedan", manufacturer: "Toyota"}

As you can see, for each key-value pair, we put a <key>: <value>, line in the object.

Accessing Data in Objects

You can access data in objects using dot notation (object.property) or bracket notation (object["property"]). Here's an example:

console.log(car.color); // Outputs: "red"
console.log(car["model"]); // Outputs: "sedan"

Dot notation directly accesses properties, while bracket notation is useful for variables or keys containing special characters or spaces.

Modifying and Adding Data to a JavaScript Object

You can modify object values or add new properties by simply assigning a new value to the key:

car.color = "blue"; // changing the existing property value
console.log(car.color); // Outputs: "blue"

car.propellant = "electric"; // adding a new property
console.log(car.propellant); // Outputs: "electric"
Checking the Existence of a Key in an Object

In JavaScript, you can verify whether a key exists within an object by using the in operator as shown below:

let car = {
  color: "red",
  model: "sedan",
  manufacturer: "Toyota"
};

console.log('color' in car); // Outputs: true
console.log('mileage' in car); // Outputs: false

In this example, we inspect if the keys 'color' and 'mileage' are in the car object. The expected outputs are true and false, respectively, since the car object contains the 'color' key but not the 'mileage' key.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal