JavaScript Unary Operators: How they Work with Examples

javascript unary operators

Unary operators in JavaScript work with only one value. They can change, test, or change the type of that value, and they are used in many different cases in programs.

Understand the Unary Operators in JavaScript

A unary operator is an operator that works with one operand only. This operand can be a number, a variable, or an expression. The operator then produces a new value.

A binary operator uses two operands, while a unary operator uses only one. For example, x + y is binary because it has two values, but -x is unary because it has one.

Unary operators in JavaScript include the following:

  • Increment
  • Decrement
  • Unary plus
  • Unary minus
  • Logical NOT
  • The typeof
  • void
  • delete

Each one has a unique role. Here is a quick example:

let x = 5;
let y = -x;
console.log(y); // -5

Here, the unary minus changes x from 5 to -5. It works on one value and gives its negative without changing the original variable.

Types of Unary Operators in JavaScript

Unary plus (+) helps you to change the operand to a number if it is not already.

Here is an example:

let str = "10";
let num = +str;
console.log(num); // 10

The "10" is a string, but + changes it to a number, so num is numeric.

Unary minus (-) returns the negative version of the value. Here is an example:

let n = 8;
let result = -n;
console.log(result); // -8

The operator takes the number 8 and returns -8.

Increment (++) adds one to the operand. For example:

let count = 3;
++count;
console.log(count); // 4

The pre-increment adds one before the value is used.

Decrement (--) subtracts one from the operand. For example:

let items = 5;
--items;
console.log(items); // 4

The value is reduced by one before it is read.

Logical NOT (!) changes a truthy value to false and a falsy value to true. Here is an example:

let isOpen = true;
console.log(!isOpen); // false

The true becomes false because ! flips the value.

The typeof returns a string that tells the type of the value.

let value = "test";
console.log(typeof value); // "string"

The typeof operator checks the type without changing the value.

The void runs an expression, but returns undefined.

void console.log("Hello");

The expression runs, but its value is always undefined.

The delete removes a property from an object.

let obj = { name: "Ali" };
delete obj.name;
console.log(obj.name); // undefined

The property name is removed from the object.

The Differences Between the Pre-Increment and Post-Increment Difference

The Pre-increment (++x) adds one to the value first, then returns the new value. Post-increment (x++) returns the current value first, then increments it by one.

Here is a table that shows you the key differences between them:

FeaturePre-increment (++x)Post-increment (x++)
When value changesBefore it is returnedAfter it is returned
Returned valueNew valueOriginal value
Typical usageWhen you need the incremented value immediatelyWhen you need the old value before incrementing
Effect in expressionsUses updated value in the expressionUses original value in the expression

Examples

Use of Unary Plus with Boolean:

let isTrue = true;
let num = +isTrue;
console.log(num); // 1

The unary plus changes true to the number 1. Boolean false would become 0. This is often used when you want quick number conversion for logic checks or counts.

Pre-increment in a Loop Condition:

let i = 0;
while (++i < 5) {
  console.log(i);
}

The loop adds one before checking if i is less than 5. This means it starts printing from 1 and stops before 5, as the increment happens before the comparison.

Using Logical NOT Twice for Conversion:

let value = "hello";
let isTrue = !!value;
console.log(isTrue); // true

Two ! operators change a value to its boolean form. "hello" is truthy, so the result is true. This is a common way to ensure a strict boolean value.

Delete a Property in an Object:

let user = { name: "Sara", age: 22 };
delete user.age;
console.log(user); // { name: "Sara" }

The delete operator removes age from the object. This is useful when you need to clean up objects before sending them or saving them.

Wrapping Up

In this article you learned what unary operators are and how each one works with only one operand. You also learned the difference between pre-increment and post-increment. Here is a quick recap:

  • Unary operators work with one value only
  • They can change values, check values, or change types
  • Common operators are +, -, ++, --, !, typeof, void, and delete
  • Pre-increment changes the value before it is used, post-increment after

FAQs

What are JavaScript unary operators?

In JavaScript, unary operators work with a single operand. Common examples are:
  • Increment (++) increases a number by one.
  • Decrement (--) decreases a number by one.
  • Unary plus (+) converts a value to a number.
  • Unary negation (-) changes the sign of a number.
  • Logical NOT (!) flips a boolean value.
  • Bitwise NOT (~) inverts bits of a number.
  • typeof returns the type of a value.
  • delete removes a property from an object.
  • void runs an expression without returning a value.

How does the increment operator work in JavaScript?

Increment (++) adds one to a variable. Example:
let num = 5;  
num++; // post-increment  
console.log(num); // 6  

let x = 5;  
++x; // pre-increment  
console.log(x); // 6  
Pre-increment changes the value before use, post-increment changes after.

What is the difference between unary plus and unary minus in JavaScript?

Unary plus (+) converts its operand into a number. Unary minus (-) converts to number and negates the value. Example:
console.log(+"5");   // 5   
console.log(-"5");   // -5   
console.log(+true);  // 1   
console.log(-true);  // -1  

How does the typeof operator work in JavaScript?

The typeof operator returns a string describing the type of a value. Example:
console.log(typeof 123);       // "number"   
console.log(typeof "hello");   // "string"   
console.log(typeof true);      // "boolean"  
console.log(typeof undefined); // "undefined"   
console.log(typeof null);      // "object" (legacy quirk)   

Similar Reads

JavaScript math.exp: How to Calculate e^x

Math.exp is a built-in JavaScript function that returns the value of e raised to a given number. Here, e is…

Mocha JavaScript Test Framework: Guide and Examples

Mocha is a JavaScript test framework for Node.js. It runs tests in sequence and shows results. It works with any…

JavaScript toSpliced Function Explained with Examples

The toSpliced function creates a new array without changing the original array in JavaScript. It returns a copy with new…

JavaScript Garbage Collection: How it Works with Examples

JavaScript removes unused memory blocks with garbage collection. It frees memory space so programs run without leaks. What is JavaScript…

JavaScript valueOf Function: How it Works with Examples

You will learn what the JavaScript valueOf function does and how it works. It returns the primitive value of an…

JavaScript Math atan: Arc Tangent of a Number in Radians

Math.atan() function in JavaScript helps you to solve math problems in your code. It turns a number into an angle.…

Arrow Function in JavaScript: How it Works with Examples

Arrow function gives you short code and keeps this in the right scope in JavaScript. Understand the Arrow Function in…

JavaScript “use strict” Mode: What It Is and Why You Should Use It

Code mistakes used to slip by without a warning. That made bugs hard to trace and fix. JavaScript "use strict"…

String Operators in JavaScript: A Complete Guide to Concatenation

String Operators in JavaScript help you work with text. You can join, build, or change strings. Most of what you…

JavaScript Math floor: How It Works with Examples

JavaScript gives you several ways to round numbers, but not all of them round the same way. If you want…

Previous Article

HTML Document Structure Guide for Beginners

Next Article

PHP sizeof: How to Count Elements in Arrays with Examples

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.