2

I think below code can be simpleer somehow. Can this code be optimized?

let name = app.short_name;
  if (name === undefined) {
    name = app.name;
    if (name === undefined) {
      name = 'Untitled';
    }
  }
1
  • 5
    yes, name could be n :p let name = app.short_name || app.name || 'Untitled'; Commented Jun 14, 2017 at 6:48

3 Answers 3

9

Use Logical OR (||) operator

let name = app.short_name || app.name || 'Untitled';
Sign up to request clarification or add additional context in comments.

Comments

8

You could use a default chain with logical OR || in a short-circuit evaluation.

let name = app.short_name || app.name || 'Untitled';

But I suggest to use a variable name different of name, because it is usually a property of window

Comments

4

Javascript will assign what it considers true. If you concat with || (OR) then each value is checked for true until a true value is found and is assigned.

There are a number of values that become false for example:

  • undefined
  • 0
  • null
  • '' (empty String)
  • NaN

This is why you could write

let name = app.short_name || app.name || 'Untitled';

because if app.short_name has a value it will be true rather than false and it is assigned. But if it is undefined it will be considered false and app.name will be checked if it is true. If it is undefined it will be again considered false and so finally 'Untitled' is considered and deemed true and assigned to name. Might want to look at this link.

1 Comment

appreciate you for the additional infomation. helped me to learn :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.