Dot vs Bracket Notation

Hello could somebody explain why the return inside the if statement has to be

if (myObj.hasOwnProperty(checkProp) == true) {
  return myObj[checkProp];
  }
instead of 

if (myObj.hasOwnProperty(checkProp) == true) {
  return myObj.checkProp;
  }

why cant we also use the dot notation the same way ??


// Setup
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};

function checkObj(checkProp) {
// Your Code Here
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};

if (myObj.hasOwnProperty(checkProp) == true) {
return myObj.checkProp;
}

else 
{return "Not Found"}

}

// Test your code by modifying these values
console.log(checkObj("gift"));

console.log(myObj.gift);

Your browser information:

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

Challenge: Testing Objects for Properties

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/testing-objects-for-properties

dot notation will search literally for that property
so if you have obj.prop it will try to access a property named prop, equivalent of using obj["prop"]

if you want instead the property with the name held by the variable prop you need to use bracket notation obj[prop], in this way it will first get the value from inside the variable and then access the property

1 Like

Hey @spiropoulos94 welcome on FreeCodeCamp :slight_smile:

Yep, I totally agree with @ilenia, I wanted just to add that in the future you will see that the bracket notation will be also useful when you try to access properties with names composed with more than a word or in general with special characters.

obj.123;      // ❌ SyntaxError
obj.123name;  // ❌ SyntaxError
obj.name123;  // ✅ 'does not start with digit'
obj.$name;    // ✅  '$ sign'
obj.name-123;  // ❌ SyntaxError
obj.'name-123';// ❌ SyntaxError
obj.NAME; // ✅ 'upper case'
obj.name; // ✅ 'lower case'

Here you find a good article providing good examples:

Happy Coding :man_technologist:

1 Like

2 posts were split to a new topic: Implementing hasOwnProperty