Bracket Notation in JavaScript

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

function checkObj(obj, checkProp) {
return obj[checkProp];
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:


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';

// undefined

// bar

// bar

// bar

// Uncaught ReferenceError: foo is not defined

An example with non-valid JS identifier:

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

// vanilla

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

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