DEV Community

Cover image for JavaScript Objects πŸ€” πŸ’»
Irena Popova πŸ‘©πŸ»β€πŸ’»
Irena Popova πŸ‘©πŸ»β€πŸ’»

Posted on • Edited on

JavaScript Objects πŸ€” πŸ’»

Objects in JavaScript are collections of key/value pairs. The values can consist of properties and methods, and may contain all other JavaScript data types, such as strings, numbers, and Booleans.

So roughly:

  • all objects in JavaScript are maps (dictionaries) from strings to values.
  • A (key, value) entry in an object is called a property.
  • The key of a property can be a text string.
  • Symbols can appear to have a description that looks like a text string, but they are fundamentally different from strings.
  • In JavaScript, the keys of an object (also known as properties) are primarily strings
  • The value of a property can be any JavaScript value, including a function.
  • Methods are properties whose values are functions. Key Types in JavaScript Objects- String Keys, Symbol Keys, Automatic Conversion. While the primary type for object keys in JavaScript is indeed strings, you can also use Symbols as keys. Any other type used as a key will be converted to a string. This behavior is important to understand when working with objects in JavaScript, especially when dealing with property enumeration and access.

All objects in JavaScript descend from the parent Object constructor. They have many useful built-in methods we can use and access to make working with individual objects straightforward.
There are three kinds of properties:

  • Properties (or named data properties) Normal properties in an objectβ€”that is, mappings from string keys to values. Named data properties include methods. This is by far the most common kind of property.
  • Accessors (Getters/Setters) (or named accessor properties) Special methods whose invocations look like reading or writing properties. Normal properties are storage locations for property values; accessors allow you to compute the values of properties. They are virtual properties.
  • Internal properties
    Exist only in the ECMAScript language specification. They are not directly accessible from JavaScript, but there might be indirect ways of accessing them. The specification writes the keys of internal properties in brackets. For example, [[Prototype]] holds the prototype of an object and is readable via Object.getPrototypeOf().

  • Object Literals
    JavaScript’s object literals allow you to directly create plain objects (direct instances of Object).

In the following code snippet an object literal is used to assign an object to the variable Irene. The object has the two properties: name and describe. describe is a method:

let irene = {
    name: 'Irene',

    describe: function () {
        return 'Person named '+this.name;  // (1)
    },  // (2)
};

Enter fullscreen mode Exit fullscreen mode
  • Use this in methods to refer to the current object (also called the receiver of a method invocation).
  • in ECMAScript 5 allows a trailing comma (after the last property) in an object literal.
  • A trailing comma is useful, because it helps to rearrange properties without having to worry which property is last.

You may get the impression that objects are only maps from strings to values. But they are more than that: they are real general-purpose objects, we can use inheritance between them.
For example with the Prototype relationship between objects
The prototype relationship between two objects is about inheritance: every object can have another object as its prototype. Then the former object inherits all of its prototype’s properties.

But for now let's stay focus on the basics.

Create an object

In JavaScript object is a collection of properties where each property has a value associate with the key.
Use curly brackets {…}to create an object.

Pay attention to the following:

let empty = {};
Enter fullscreen mode Exit fullscreen mode

To create an object with properties, using the key : value pair.

let mobile = {
    name: 'apple',
    model: 's7',
    price: ' β€Žβ‚¬800'
};
Enter fullscreen mode Exit fullscreen mode

The mobile object has three properties name, model, and price with the corresponding values 'apple', 's7' and ' β€Žβ‚¬ 800'.

Accessing objects properties

There are two ways to access the property of an object, see the following: the dot notation and array-like notation.

The dot notation (.)

The following syntax shows how to use the dot notation to access a property of an object:

objectName.propertyName
Enter fullscreen mode Exit fullscreen mode

In order to access the name property of the mobile object, you use the following expression:

mobile.name
Enter fullscreen mode Exit fullscreen mode

The following snippet creates a mobile object and console name and model of mobile objects:

let mobile = {
    name: 'apple',
    model: 's7',
    price: 'β€Žβ‚¬800'
};

console.log(mobile.name);
console.log(mobile.model);
Enter fullscreen mode Exit fullscreen mode

Array-like notation ( [])

The following syntax shows how to access the value of an object’s property via the array-like notation:

objectName['propertyName'];
Enter fullscreen mode Exit fullscreen mode

for example:

let mobile = {
    name: 'apple',
    model: 's7',
    price: '€800'
};

console.log(mobile['name']);
console.log(mobile['price']);
Enter fullscreen mode Exit fullscreen mode

Suppose, you have property with contains spaces, you need to place it inside quotes.

Pay attention the following:

let homeAddress = {
   'house nom': 39,
    street: 'GΓΆtelstr.',
    state: 'Berlin',
    country: 'Germany'
};
Enter fullscreen mode Exit fullscreen mode

To access the 'house nom', you must use the array-like notation:

homeAddress['house nom'];
Enter fullscreen mode Exit fullscreen mode

If you use the dot notation, you will get an error:

homeAddress.'house nom';
Enter fullscreen mode Exit fullscreen mode

Reading from a property that does not exist will result in an undefined. For example:

console.log(homeAddress.district);

// Output: undefined
Enter fullscreen mode Exit fullscreen mode

Change the property’s value
To change the value of a property, you use the assignment operator. For example:

let mobile = {
    name: 'apple',
    model: 's7',
    price: '€800'
};

mobile.name = 'Motorola';

console.log(mobile);

//Output: {name: "Motorola", model: "s7", price: "€800"}
Enter fullscreen mode Exit fullscreen mode

Add a new property to an object

The following expression adds the weight property to the mobile object and assigns 150g to it:


let mobile = {
    name: 'apple',
    model: 's7',
    price: '€800'
};

mobile.name = 'Motorola';

mobile.weight= '150g';

console.log(mobile); 

// {name: "Motorola", model: "s7", price: "€800",
 weight: "150g"}
Enter fullscreen mode Exit fullscreen mode

Delete a property of an object

Using delete operator, To delete a property from an object:


delete objectName.propertyName;
Enter fullscreen mode Exit fullscreen mode

The following example removes the price property from the mobile object:

delete mobile.price;
Enter fullscreen mode Exit fullscreen mode

How to check if a property exists:

Using the in operator, You can check if a property exists in an object:


propertyName in objectName

Enter fullscreen mode Exit fullscreen mode

The following example creates a mobile object and uses the inoperator to check if the model and weight properties exist in the object.


let mobile = {
    name: 'apple',
    model: 's7',
    price: '€800'
};

console.log('model' in mobile);
console.log('weight' in mobile);

// Output:
true
false

Enter fullscreen mode Exit fullscreen mode

Iterate over properties of an object using for...in loop

πŸ›‘ To iterate over all properties of an object without knowing property names, you use the for...inloop, have a look at the following syntax:


for(let key in object) { 
    // ...
};
Enter fullscreen mode Exit fullscreen mode

The following shows, to creates abookobject and iterates over its properties using the for...in loop:

let book = {
    title: 'JavaScript',
    tags: ['es6', 'javascript', 'node.js'],
    price: '€35'
};

for (const key in book) {
    console.log(book[key]);
}
Enter fullscreen mode Exit fullscreen mode

Functions

The following syntax shows how to tag function to the book object:

let book = {
    title: 'JavaScript',
    price: '€35'
};

book.tag = function () {
   return ['es6', 'javascript', 'node.js']
}

console.log(book.tag());

//Output: ["es6", "javascript", "node.js"]
Enter fullscreen mode Exit fullscreen mode

In this example, a function expression is added to create the function and assigned it to the property tag of the book object.

Then, the function is called via the tag property as tag().
πŸ›‘When a function is a property of an object, it is called a method.

In ES6, you can even make it more concise:


let book = {
    title: 'JavaScript',
    price: '€35',
    tag() {
        return ['es6', 'javascript', 'node.js']
    }
};

console.log(book.tag());

Enter fullscreen mode Exit fullscreen mode

The this object properties

Suppose you have an array and you want to concatenate two objects properties inside the function, you can use this object properties.

πŸ›‘ Inside the method, the this value references the object that contains the method so you can access an object property using the dot notation:

this.propertyName
Enter fullscreen mode Exit fullscreen mode

The following example uses the this value in the getName() method:


let ps = {
    firstName: 'Irena',
    lastName: 'Smith',
    getName: function () {
        return this.firstName + ' ' + this.lastName;
    }
};

console.log(ps.getFullName());

//Output: Irene Smith

Enter fullscreen mode Exit fullscreen mode

In JavaScript, the keys of an object (also known as properties) are primarily strings. However, there are some important nuances to consider:

Key Types in JavaScript Objects

String Keys: By default, when you define a property on an object using a string, that string becomes the key. For example:

const obj = {
  name: 'Irena',
  age: 30
};

Enter fullscreen mode Exit fullscreen mode

Here, "name" and "age" are string keys.

More on Symbol keys

Symbol Keys:

In addition to strings, JavaScript also allows the use of Symbols as keys. Symbols are unique and immutable values that can be used to create private object properties.

For example:

const sym = Symbol('uniqueKey');
const obj = {
  [sym]: 'This is a symbol key'
};
Enter fullscreen mode Exit fullscreen mode

In this case, sym is a Symbol key, which is not converted to a string and is not enumerable in the same way as string keys.

Automatic Conversion:

If you attempt to use a non-string value (like a number or an object) as a key, JavaScript will automatically convert it to a string. For example:

const obj = {};
obj[1] = 'one'; // The number 1 is converted to the string '1'
console.log(obj['1']); // Outputs: 'one'

Enter fullscreen mode Exit fullscreen mode

While the primary type for object keys in JavaScript is indeed strings, you can also use Symbols as keys. Any other type used as a key will be converted to a string. This behavior is important to understand when working with objects in JavaScript, especially when dealing with property enumeration and access.

Symbols are not text strings. In JavaScript, Symbols are a distinct primitive data type introduced in ECMAScript 2015 (ES6).
Here are the key differences between Symbols and strings:

Key Differences

Type:

-Symbols: They are a unique and immutable primitive type. Each Symbol is guaranteed to be unique, even if they have the same description.
-Strings: Strings are sequences of characters used to represent text.

Usage:

-Symbols: Typically used as unique property keys in objects to avoid name collisions. They are not converted to strings and do not appear in standard object property enumerations (like for...in loops).
-Strings: Commonly used for text representation and can be used as keys in objects. If a non-string value is used as a key, it is automatically converted to a string.

const sym1 = Symbol('description');
const sym2 = Symbol('description');
console.log(sym1 === sym2); // false, each Symbol is unique

const obj = {
  [sym1]: 'value1',
  [sym2]: 'value2'
};
console.log(obj[sym1]); // 'value1'
console.log(obj[sym2]); // 'value2'

Enter fullscreen mode Exit fullscreen mode

while both Symbols and strings can be used as keys in objects, they are fundamentally different types. Symbols provide a way to create unique identifiers that do not conflict with other property keys, while strings are the standard way to represent text.

Symbols can appear to have a description that looks like a text string, but they are fundamentally different from strings. Here’s a breakdown of why Symbols might seem similar to strings and how they differ:

Appearance vs. Type

Description:

When you create a Symbol, you can provide a description (a string) that helps identify it. For example:

const mySymbol = Symbol('mySymbolDescription');

Enter fullscreen mode Exit fullscreen mode

The description ('mySymbolDescription') is a string, but the Symbol itself is not a string; it is a unique identifier.

String Representation:

If you try to convert a Symbol to a string (for example, by using String(mySymbol)), it will return the description, but the Symbol itself remains a distinct type:

console.log(String(mySymbol)); // 'Symbol(mySymbolDescription)'
console.log(typeof mySymbol); // 'symbol'

Enter fullscreen mode Exit fullscreen mode

Uniqueness: Each Symbol is unique, even if they have the same description. This is a key feature that differentiates them from strings, which can have identical values:

const sym1 = Symbol('desc');
const sym2 = Symbol('desc');
console.log(sym1 === sym2); // false, they are different Symbols
Enter fullscreen mode Exit fullscreen mode

While Symbols can have descriptions that look like strings, they are a separate primitive type in JavaScript. Their primary purpose is to create unique property keys that do not collide with other keys, making them useful for scenarios where you want to avoid naming conflicts. This uniqueness and immutability are what set Symbols apart from strings, despite their similar appearance.

In order to make it more clear and practicle
Example:

Using Symbols as Object Keys

Scenario
Imagine you are building a user management system where you want to store user information. You want to ensure that certain properties are unique and not easily accessible or overwritten by other parts of your code.
Using String Keys
When using string keys, you might define an object like this:


const user = {
  name: 'Irena',
  email: 'irena@example.com',
  password: 'securePassword123'
};

// Accessing properties
console.log(user.name); // 'Irena'
console.log(user.email); // 'irena@example.com'

// Potential issue: Overwriting properties
user.password = 'newPassword456'; // This can be overwritten easily
console.log(user.password); // 'newPassword456'
Enter fullscreen mode Exit fullscreen mode

In this case, anyone with access to the user object can easily overwrite the password property.
Using Symbol Keys
Now, let’s use Symbols to create unique keys for sensitive information:


const passwordKey = Symbol('password');
const user = {
  name: 'Irena',
  email: 'irena@example.com',
  [passwordKey]: 'securePassword123' // Using Symbol as a key
};

// Accessing properties
console.log(user.name); // 'Irena'
console.log(user.email); // 'irena@example.com'
console.log(user[passwordKey]); // 'securePassword123'

// Attempting to access the password with a string key
console.log(user.password); // undefined, as 'password' is not a key
Enter fullscreen mode Exit fullscreen mode

Key Differences recap

Uniqueness:

The passwordKey Symbol is unique. Even if you create another Symbol with the same description, it will not conflict with passwordKey.

If you used a string key like 'password', it could easily be overwritten or accessed by other parts of the code.

Access Control:

The Symbol key (passwordKey) does not show up in standard property enumerations (like for...in loops), making it less likely to be accidentally accessed or modified.
String keys can be easily accessed and modified, which can lead to potential security issues.

Type Safety:

Symbols provide a way to create private properties that are not easily accessible, enhancing encapsulation.
String keys do not provide this level of protection, as they are openly accessible.

So using Symbols as keys in JavaScript objects allows for greater control over property access and helps prevent naming collisions. This is particularly useful in scenarios where you want to protect sensitive information or ensure that certain properties remain unique and unaltered.

RECAP

In this article you have learned the following:

  • An objectis a collection of properties where each property has a value associate with thekey. An object property key is a string and value can be any valid value.
  • Use the dot notation( .) or array-like notation ([]) to access an object property.
  • The delete operator removes a property from an object.
  • The inoperator check if a property exists in an object.
  • The for...in iterates over properties of an object.
  • When functions are properties of an object, they are called methods.
  • Use the this inside the method to access the object’s properties.

I have written this article as a student's guide for my workshop aboutJavaScript Objects organised for DCI new students.

Happy coding!

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

The key of a property is always a text string

This isn't correct, the key can also be a Symbol.

Collapse
 
irenejpopova profile image
Irena Popova πŸ‘©πŸ»β€πŸ’» • Edited

Hey, I'd be glad to provide more examples and explanations regarding property keys in JavaScript.
Property Keys are more than just Strings
Symbols can appear to have a description that looks like a text string, but they are fundamentally different from strings. A breakdown is in the article.
In JavaScript, property keys are used to access and modify properties of objects. While strings are the most common type of property keys, they are not the only option. Symbols can also be used as property keys, offering unique advantages:
Symbol Keys:
Uniqueness: Symbols are guaranteed to be unique, even if they have the same description. This prevents accidental naming collisions and ensures that properties are truly private within an object.
Privacy:
Symbols can be used to create private properties that are not accessible from outside the object's scope. This enhances encapsulation and protects sensitive data.
Both Symbols and strings can be used as keys in objects, they are fundamentally different types. Symbols provide a way to create unique identifiers that do not conflict with other property keys, while strings are the standard way to represent text.