Course Content
JavaScript Data Structures
JavaScript Data Structures
Object Creation
Let's focus on creating objects, using object literals, and understanding the rules for naming keys.
Object Literals
When creating objects in JavaScript, one of the most common and straightforward methods is to use object literals enclosed in curly braces {}
. Here's an example:
In this example, we've created an object named book
with several properties defined using key-value pairs. Let's break down the key components of this object creation:
Key-Value Pairs
- Key (Property Name): Each property within an object is described by a key. These keys are also referred to as property names and are always represented as strings. In the
book
object, keys liketitle
,author
,genres
,relevant
, andrating
serve as property names; - Value: The values associated with the keys can be of any data type: primitives, arrays, objects, booleans, functions, and more. For example, the
title
property holds a string value, while thegenres
property contains an array; - Commas: Properties within an object are separated by commas. The commas are crucial in distinguishing one key-value pair from the next.
Key Naming Rules
When naming keys (property names) for your objects, there are some simple rules to keep in mind:
Quoted Keys
If a key is enclosed in quotes (single or double), it can be an arbitrary string. You can use spaces, special characters, and valid string content as the key. Example:
Unquoted Keys
Certain restrictions apply if there are no quotes around the key. The key should be a name without spaces and should begin with a letter or one of the characters: _
, $
, or any Unicode character.
These rules ensure consistency and validity when defining keys in your objects.
Thanks for your feedback!