I’m confused. So bracket notation doesn’t always require using `“` or `‘`? How do I know when to use quotation marks and when I don’t?


#1

Question

I’m confused. So bracket notation doesn’t always require using or ? How do I know when to use quotation marks and when I don’t?

Answer

This is easy to mix up! You need to use quotation marks when you are accessing the object with the name of the key. You don’t need quotation marks when you are using a variable that contains a key name. Here is an example:

		let dog = {
						name: ‘Max’,
								breed: ‘Chihuahua’
				};

	// Let’s say we want to know the name of the dog.:
						console.log(dog[‘name’]) // output: ‘Max’

	// What if we have a variable for the key name?
				let key = ‘name’;
		

console.log(dog[key]) // output: ‘Max’
		

You can see in the above that the value of the variable key has quotation marks, so when we use the variable key in dog[key], ’name’ takes the place of key and becomes dog[‘name’].