0

I have the following code:

  console.log('Checking... ' +
    auth.isAuthenticated() ?
      `User ${auth.user.email} is authenticated` :
      'User is not authenticated!'
  );

If isAuthenticated returns false, then auth.user is undefined. Therefore, trying to print auth.user.email when isAuthenticated==false, will result in an error.

But in my case, I only want to print auth.user.email when auth.isAuthenticated==true but I still get this error:

TypeError: Cannot read property 'email' of undefined
Poogy
  • 2,597
  • 7
  • 20
  • 35
  • 3
    `console.log('Checking... ' + (auth.isAuthenticated() ? \`User ${auth.user.email} is authenticated\` : 'User is not authenticated!') );` should work. – Zenoo Apr 18 '18 at 09:47
  • What's the difference? Why adding braces would solve the issue? – Poogy Apr 18 '18 at 09:49

1 Answers1

1

You need to wrap your ternary operator with () for it to be considered as a single value in your String concatenation :

let auth = {
  isAuthenticated: () => true,
  user: {
    email: 'test'
  }
};

console.log('Checking... ' +
  (auth.isAuthenticated() ?
    `User ${auth.user.email} is authenticated` :
    'User is not authenticated!')
);
Zenoo
  • 12,670
  • 4
  • 45
  • 69