Object is a type of data in JavaScript that contains key-value pairs. These pairs are written within curly braces and separated by commas. For example:
const anObject = { key1: 'value1', key2: 'value2', string: 'Yay', // more string number: 1, // number boolean: true, // boolean anotherObject: {}, // another object aFunction: function () {}, // functions anArray: [] // array}
Get the value of a property
Objects can store various types of values, including primitives and other objects. You can access object properties using dot notation. For example:
const macbook = { storage: '512gb'}
const storage = macbook.storage // Dot notationconst storageAlt = macbook['storage'] // Bracket notation
Use dot notation for valid identifiers and bracket notation for invalid identifiers or when accessing properties through variables.
const objWithInvalidIdentifiers = { 'First Name': "Reza"}
const firstName = objWithInvalidIdentifiers['First Name'] // Bracket notation
Notes: Valid Identifiers
- It must be one word
- It must consist only of letters, numbers or underscores (0-9, a-z, A-Z,
_
) - It cannot begin with a number
- It cannot be any of these reserved keywords
Anything that doesn’t follow these rules is an invalid identifier.
Set and Delete value of a property
You can also set or delete properties using both notations.
macbook.storage = '256gb' // Set propertydelete macbook.storage // Delete property
Function are special objects
Function in JavaScript are special objects and can have properties. When functions are stored in objects, they are called methods.
const greeter = { sayHello: function (name) { console.log('Hello ' + name + '!') }}
greeter.sayHello('Reza') // Hello Reza!
Summary
- Object store key-value pairs.
- Properties can be accessed using dot or bracket notation.
- Use dot notation for valid identifiers and bracket notation for invalid identifiers or variable-based access.
- Functions can be stored in objects as methods.