DEV Community

thatgirlvictoria
thatgirlvictoria

Posted on

JavaScript: Unary Operators

This is what I learned about unary operators while working on a 8kyu Codewars challenge in further detail.

What are Unary Operators in JavaScript?

To better understand what unary operators are I took apart the word Uni which equals One while operators are a character that represents an action.

Unary operators work on one value. Below is a table to better explain:

table of unary operators

What does this table mean exactly?

  • Non-numeric values: all unary operators will first convert them into a number.

  • Unary plus (+) when placed before a numeric value, it does nothing.

  • Unary minus (-) when placed before a numeric value, it will negate it.

  • Prefix increment operator (++ before value) adds one to a value. Value is changed before the statement is evaluated.

  • Postfix decrement operator (-- before value) minus one to a value. Value is changed before the statement is evaluated.

  • Postfix increment operator (++ before value) adds one to a value. Value is changed after the statement is evaluated.

  • Prefix decrement operator (-- before value) minus one to a value. Value is changed after the statement is evaluated.

Codewars Challenge: Opposite Number

How did I use unary operators to solve a problem?

The goal: If you are given an integer or a floating-point number, find its opposite.

Examples:
   1: -1
   14: -14
   -34: 34
Enter fullscreen mode Exit fullscreen mode

I love writing code that is easy to read, the cleanest way I thought to answer the problem was to use unary minus operator.

function opposite(number) {
  return(-number);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)