How to get values in a JavaScript Object?

We can get values from a JavaScript Object in two ways using either the Dot (.) or Bracket ([]) Notation.

Let us take a look at this with some sample examples:

The example below shows how to get a value from an object using dot notation:

const sampleObject = {
    'title': 'Mr',
    'name': 'John Doe'
    'age': 20,
    'occupation': 'Software Engineer'
};

// now let us get the name from this object
console.log(sampleObject.name) //returns John Doe

Here’s another example below which shows how to get a value from an object using the bracket notation:

const sampleObject = {
    'title': 'Mr',
    'name': 'John Doe'
    'age': 20,
    'occupation': 'Software Engineer'
};

// now let us get the name from this object
console.log(sampleObject['name']) //returns John Doe

The example below illustrates a simple scenario where it would be better to use the bracket notation rather than the dot notation:

const sampleNamesObject = {
    1: 'John',
    2: 'Jack'
    3: 'Jane'
};

/**
* The object above in a key-value pair of serial numbers and names.
* In this scenario the best and ideal option to use to access the  
* value in this object is with the bracket notation.
* 
* If we use the dot notation, an error is returned because we cannot call
* the dot notation on a number.
*/

// This is the result of what happens when we try to access the value using dot notation
console.log(sampleNamesObject.1) // returns this error (SyntaxError: Unexpected token, expected ",")

// Using the bracket notation returns the result successfully.
console.log(sampleNamesObject[1]) // returns John

NOTE:

You can also check out arrays to represent the above as a list.

See you in the next one 😊 👍