String or not a string?

So I’m a bit confused and wondered if anyone had anything to say on the subject…

In the example in this lesson we are shown the code below. In this example the property name is not held in quotation marks, (which makes me think it is a keyword? What even is a keyword? Is it limited to special JavaScript words that do things?). When we assign this property we do not use quotation marks

Code example
const myObj = {
  prop1: "val1",
  prop2: "val2"
};

const prop1val = myObj.prop1;
const prop2val = myObj.prop2;

In the lesson activity however we can see that our property is held within quotation marks. Does this make it a string rather than a keyword? Also why does the test pass when I assign this property without the quotation marks? Is that a bug, or is there some information I’m missing?

My Code

const testObj = {
"hat": "ballcap",
"shirt": "jersey",
"shoes": "cleats"
};
const hatValue = testObj.hat;
const shirtValue = testObj.shirt;
Accessing Object Properties with Dot Notation Link

https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-dot-notation

AFAIK, object’s key (property) is always a string, like this:

const testObj = {
"hat": "ballcap",
"shirt": "jersey",
"shoes

If it’s not a string, than JS will convert it into a string.
The display like this:

const myObj = {
  prop1: "val1",
  prop2: "val2"
};

is not an evidence that the key’s typeof is not a string. So be really careful when we see something like this:

const myObj = {
1: "val1",
2: "val2"

because it is basically:

const myObj = {
"1": "val1",
"2": "val2"

So if we need the key to be a typeof Number, we need to convert it first before processing it.

This kind of behavior is the unique trait of JS, for “being helpful” (not strictly enforcing the rule), similar to what it did with: 1 + “1” = 2 (“being helpful” converting the string 1 into a number before processing it).

This forgiving behavior is also part of why it’s popular as a (beginner friendly) language for beginner to learn.
CMIIW.

Thanks for that information @shugyoza Does that mean then I can access the key like this…

const testObj = {
"hat": "ballcap",
"shirt": "jersey",
"shoes": "cleats"
};
const hatValue = testObj."hat";
const shirtValue = testObj."shirt";

Will have to try that out. Thanks again for your info

No. it’s prescribed that way. if you want to access with bracket, it’s testObj[“hat”], if you want to use dot notation, it’s testObj.hat. The bracket is more versatile as we can use it to access obj[“key with space”], and also use it in a for loop like:

for (let key in testObj) {
   console.log(testObj[key]);

This is the only case where we don’t use quote in the bracket because key is a variable we defined, and the testObj itself does not have a property named “key”, only “hat”, “shirt”, and “shoes”

2 Likes