My Development Notes

Programming Made Easier


Key-Value Pairs in JavaScript Objects

JavaScript objects have keys (or properties), and values. Let’s take a look at this JS object example with some keys and values, keys are on the left, values on the right :

const housingSociety = {
  house1: 'Mr Joe',
  house2: 'Ms Allena',
  house3: 'Mr Steve'
};

housingSociety;

// outputs {house1: 'Mr Joe', house2: 'Ms Allena', house3: 'Mr Steve'}

Now let’s add some additional key value pairs to the object. Here’s one way to do that:

const housingSociety = {
  house1: 'Mr Joe',
  house2: 'Ms Allena',
  house3: 'Mr Steve'
};

housingSociety.house4 = 'Mrs Angela'; // new key value


housingSociety;

// outputs {house1: 'Mr Joe', house2: 'Ms Allena', house3: 'Mr Steve', house4: 'Mrs Angela'}

So, if you add the above code on the next line and log it to the console again, it adds the fourth key-value pair i.e., house4: ‘Mrs Angela’ to the object. You can also achieve this result in another way using the bracket notation as like so:

housingSociety['house4'] = 'Mrs Angela';

Yet another way to add the above key-value pair is this:

const houses = 'house4';
housingSociety[houses] = 'Mrs Angela';

Posted

in

by

Leave a Reply