Everything Be True - dot vs bracket notation

Everything Be True - dot vs bracket notation
0.0 0

#1

I’ve solved Everything Be True after switching from dot notation to bracket notation, but I don’t understand why. Specifically, this line was failing:

if(!collection[i].pre){ return false; }

But when I changed it to bracket notation, my code passed:

if(!collection[i][pre]) { return false; }

I’ve looked up the differences between bracket and dot notation and both should work in this scenario. I’m missing something why the dot notation isn’t working - what could it be?

Your code so far

function truthCheck(collection, pre) {
  // Is everyone being true?
  for(i = 0; i < collection.length; i++) {
    if(!collection[i].hasOwnProperty(pre)) { return false; }
    if(!collection[i].pre) { return false; }
  }
  return true;
}

truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");

Your browser information:

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

Link to the challenge:


#2

Because you have to use bracket notation with variables.

When you write collection[i].pre, JavaScript is looking for an actual property named “pre” in the collection object. It would be the same as writing collection[i][“pre”].