Bracket Notation in JavaScript

Hey!
While solving this challenge, the solution that was accepted was as follows:

function checkObj(obj, checkProp) {
if(obj.hasOwnProperty(checkProp))
{
return obj[checkProp];
}
else{
return "Not Found";
}
}

I learned in the previous challenges that in bracket notation you have to use quotes if there is space between words in the property name. However, I found that you have to use quotes even if there is no space.

But, in this particular challenge, in the syntaxes below the solution was only accepted when I removed the quotes from checkProp from both of them:

obj.hasOwnProperty(checkProp)

return obj[checkProp];

Can anyone please explain it to me? When and when not to use quotes in bracket notations?

Normally, use dot notation.

Now, bracket notation could be used always, but there are two cases where you must use it - if the property name is stored in a variable or if the property name is not a valid JS identifier (e.g., it has a space in it).

const obj = { foo: 'bar' };

const checkProp = 'foo';

console.log(obj.checkProp);
// undefined

console.log(obj[checkProp]);
// bar

console.log(obj.foo);
// bar

console.log(obj['foo']);
// bar

console.log(obj[foo]);
// Uncaught ReferenceError: foo is not defined

An example with non-valid JS identifier:

const femaleSingersFavoriteIceCream = {
  Madonna: 'vanilla',
  'Lady Gaga': 'chocolate',
};

console.log(femaleSingersFavoriteIceCream.Madonna);
// vanilla

console.log(femaleSingersFavoriteIceCream.['Lady Gaga']);
// chocolate

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.