TLDR: You cannot use variables with dot notation.
I mostly care about the theory of why we are not able to lookup an object’s value based on a dynamically generated key (unless I am doing it wrong). If I statically type game.team1
it looks up the value perfectly fine, however if the key is dynamically generated game.key
it returns undefined. I know we can look it up using square bracket accessor game[key]
, but why can’t we do it using dot accessor? What gives? Shouldn’t game.key in the first iteration of the loop evaluate to game.team1 and then look the key up in the object?
const game = { team1: 'Bayern Munich', team2: 'Borrussia Dortmund', players: [ [ 'Neuer', 'Pavard', 'Martinez', 'Alaba', 'Davies', 'Kimmich', 'Goretzka', 'Coman', 'Muller', 'Gnarby', 'Lewandowski', ], [ 'Burki', 'Schulz', 'Hummels', 'Akanji', 'Hakimi', 'Weigl', 'Witsel', 'Hazard', 'Brandt', 'Sancho', 'Gotze', ], ], score: '4:0', scored: ['Lewandowski', 'Gnarby', 'Lewandowski', 'Hummels'], date: 'Nov 9th, 2037', odds: { team1: 1.33, x: 3.25, team2: 6.5, }, }; for (const [idx, scorer] of Object.entries(game.scored)) { console.log(`Goal #${Number(idx) + 1}: ${scorer}`); } for (const [key, odd] of Object.entries(game.odds)) { console.log(game.team1); // works -> Bayern Munich, console.log( `${ key === 'x' ? `Odd of draw: ${odd}` : `Odd of victory ${game.key}: ${odd}` }` ); // doesn't work -> Undefined }
Advertisement
Answer
When using the dot notation (object.property
) properties can only be alphanumeric (and _ and $), can’t start with a number and cannot contain variables. That’s why your game.key
example doesn’t work.
In Bracket notation (object[property]
) property identifiers have to be a String and it is okay to use spaces, Strings that start with numbers and variables that reference a string. As in your example key
is a variable that references a string, it works.
See: Property accessors and JavaScript Quickie— Dot Notation vs. Bracket Notation