There are many ways in JavaScript to do the same thing. I will tell you about some nuances that will help you write more beautiful code.

One-liner functions

When you got acquainted with functions, we told you that you need to place the body of the function in curly braces {...}.

But if your function consists of one command, for example, adds two numbers and returns the result, then you can remove the curly braces and reduce the creation of the function to a single line.

const sum = (x, y) => {
  return x + y;
}

Turns into

const sum = (x, y) => x + y;

After the arrow => you can immediately write the return value instead of the curly braces. The return keyword is not used in this case.

Let’s try another example. Here we took a name and returned a greeting to the user:

const getPersonalizedGreeting = (name) => `Hello, $ {name}!`;

Or we immediately displayed it on the screen:

const printGreeting = (name) => console.log (`Hello, $ {name}!`);

Returning objects in one line

However, one-liner functions have one peculiarity. To return an object, you need to wrap it in parentheses.

It is not right:

const getObjectIncorrect = (name) => {name: 'Jack', email: '[email protected]'};

Parentheses are required!

const getObjectCorrect = (name) => ({name: 'Jack', email: '[email protected]'});

Ternary operator

When you need to check a condition, you don’t have to use if/else. The check can be shortened to one line using the ternary operator.

In general, it looks like condition ? expression1 : expression2. Here’s the breakdown:

  • condition is the same condition that you specified in parentheses after if
  • expression1 - expression (command) that will be executed if condition is truthy
  • expression2 - expression (command) that will be executed if condition is falsy
  • the condition is separated from expressions by a question mark ?
  • expressions are separated from each other by a colon :

By combining the ternary operator and one-liner functions, we can cut down on fairly large chunks of code.

Imagine that we need to implement the isOfAge(user) function, which will check the age field of the user object and return true if it is greater than or equal to 21, otherwise - false.

In simple words - we check if the user is of age.

const isOfAge = (user) => {
  if (user.age >= 21) {
    return true;
  } else {
    return false;
  }
}

The same function can be written much shorter:

const isOfAge = (user) => user.age >= 21 ? true : false;

Although there is another way to shorten the isOfAge function, which you’ll explore in one of your practical tasks.

FAQ

— Can I nest one ternary operator in another? — You can, but it’s not a good idea. Such code is difficult to read and understand.