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
2
  • 3
    console.log('Checking... ' + (auth.isAuthenticated() ? `User ${auth.user.email} is authenticated` : 'User is not authenticated!') ); should work. Commented Apr 18, 2018 at 9:47
  • What's the difference? Why adding braces would solve the issue? Commented Apr 18, 2018 at 9:49

1 Answer 1

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!')
);

Sign up to request clarification or add additional context in comments.

2 Comments

@Zenno It works! But why do I need () ?
We got tons of duplicates about that :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.