I have the following code:
const showMessage = msg => console.log(msg);
let person = {
firstName: `Mick`,
lastName: `McCarthy`,
firstTimeUser: true
}
(person.firstTimeUser === true) ? showMessage(`Welcome, ${person.firstName}!`): showMessage(`Glad you're back, ${person.firstName}!`)
This results in the error:
home.js:7 Uncaught ReferenceError: Cannot access 'person' before initialization
at home.js:7
However, in the following case (where the parentheses in the ternary expression have been removed):
const showMessage = msg => console.log(msg);
let person = {
firstName: `Mick`,
lastName: `McCarthy`,
firstTimeUser: true
}
person.firstTimeUser === true ? showMessage(`Welcome, ${person.firstName}!`) : showMessage(`Glad you're back, ${person.firstName}!`)
There is no error and the welcome message displays correctly.
Why should this be the case? I was under the impression that parentheses were optional in the ternary expression. I imagine that it is something to do with order of evaluation, but since the ternary expression is on a different line to let person = {..., I am unclear as to why this is happening.
In fact, in the example shown by the JavaScript course I am taking, the instructor shows the following example working perfectly with or without parenthesis:
let price = 20
(price < 10) ? showMessage('yes') : showMessage('no')
However when I try it on my own machine, the same problem occurs. Could they be using an older version of JavaScript in which the behaviour is different? If so, what has changed?
Many thanks!