hasOwnProperty - return question

Out of the 2 options, why does only the first one return the prop value? Why does dot notation not return but the square brackets does? There are no spaces in the properties.

if (obj.hasOwnProperty(checkProp)) {
return obj[checkProp];} esle…

if (obj.hasOwnProperty(checkProp)) {

return obj.checkProp;} else…

You should review this lesson - https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables

obj.checkProp ← Return the value stored at the key named “checkProp”

obj[checkProp] ← Evaluate the value of the variable checkProp, and return the value stored at that key

const name = {
  first: 'John',
  last: 'Doe',
};

const key = 'first';

// dot notation
name.first; // 'John'
name.last; // 'Doe'
name.key; // undefined (there's no key named "key")

// bracket notation
name[first]; // Reference Error (there's no variable named "first" in scope)
name[last]; // Reference Error (there's no variable named "last" in scope)
name[key]; // 'John' (key evaluates to "first")
1 Like

Note that you’re already familiar with this concept when writing for loops to iterate over strings or arrays with an iterator variable (usually i).

That is fantastic thank you, I hadn’t linked the 2 together and it makes much more sense now!