Ads by ProfitSence
Close

What is a Key-Value Pair?

Last Updated on Wednesday 5th Oct 2022

In this Article We define, and work with objects.

  • You can also initialize an object with key-value pairs when you create it.
  • Deleting a Key-value pair

key value pair

			
					var books = { name: "Blue Highways" };

// or, equivalently

var books = new Object({ name: 'Blue Highways' })

			
	

In this case, name is the key and "Blue Highways" is the value.

Note that all keys in JavaScript objects are strings.

  • This means that even though you can create an object name: 'Eat, Pray, Love: One Woman's Search for Everything Across Italy, India and Indonesia'.
  • The key here, name gets turned into the string 'name'. Values can be of any type.
			
					var book = {
  name: "Blue Highways",
  name: "Unlikely Destinations: The Lonely Planet Story"
}

			
	

And then check on the value of book, you'd see

			
					{ name: "Unlikely Destinations: The Lonely Planet Story" }

			
	

Only the last key-value pair to use name as the key gets saved! Values don't have to be unique, though

			
					var book = {
  name: "Blue Highways",
  author: "William Least Heat-Moon",
  year: 1982
}

			
	

Deleting a Key-Value Pair

If We want to delete the year key-value pair

			
					
var book = {
  name: "Blue Highways",
  author: "William Least Heat-Moon",
  year: 1982
}

// the delete operator returns true if it has successfully
// deleted, false otherwise
delete book.year; // true

book;
// returns {  author: "William Least Heat-Moon", name: "Blue Highways" }