Updating an objects quotes and unquoted

Tell us what’s happening:,

Hi
Why does the code not run when I use dot notation my: myDog.“name”
when it is a string as a property and with brackets it wont work without quotes?

  **Your code so far**

// Setup
var myDog = {
"name": "Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"]
};

// Only change code below this line

myDog.name = "Happy Coder"
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36 Edg/88.0.705.68.

Challenge: Updating Object Properties

Link to the challenge:

Dot notation just does not work with quotes. It’s not how the syntax works. Only bracket notation works with quotes.

Bracket notation takes a string (or a number in some cases, but typically a string) or a variable holding a string (or number in some cases…).

Dot notation requires the exact name of the property without quotes.

Why does the code not run when I use dot notation my: myDog.“name” when it is a string as a property and with brackets it wont work without quotes?

Because with dot notation, you have to give the exact property that is a valid JS identifier, which can contain letters, numbers, $, or _, as long as it doesn’t start with a number. So, since the property is name, that has to be after the dot. The property is not "name" with the quotes. So,

myDog.name

or

myDog["name"]

or

const prop = "name"
myDog[prop]

In the first one, it is not a string, but a JS identifier which gets interpreted by the compiler.

In theory you could have something like:

const myDog = { "\"name\"": "Rover" }
myDog["\"name\""]

But since that property is not a valid JS identifier, it could only work with bracket notation.

1 Like