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 Syntax: The Complete Cheat Sheet

JavaScript syntax is what you will use when writing and reading javascript code, it is the foundation of using this…

JavaScript Optional Chaining “?”: How it Works with Examples

JavaScript optional chaining lets you access object values without runtime errors. It checks if a property exists before access and…

JavaScript Math log: How it Works with Examples

JavaScript Math.log() was added to help people find the natural log of a number. It solves real problems in science…

JavaScript Class and Object Constructors with Examples

Object constructors and class constructors in JavaScript create objects in a structured way. Both provide methods to build reusable code.…

JavaScript for Loop: How to Iterate Arrays by Examples

JavaScript runs code in different ways, but the for loop stays one of the most common tools. You use it…

JavaScript Math asin: How it Works with Examples

Math.asin() finds the arc sine of a number in JavaScript. It helps you work with angles from values. You get…

JavaScript Math.random() Returns Numbers 0–1

Math.random() gives a number between 0 and 1 in JavaScript. It helps create random values for colors or other data.…

Math pow in JavaScript : How to Raise Numbers to Power

The Math.pow() function in JavaScript solves one common task. It raises a number to a power. This helps avoid loops…

JavaScript Math abs(): How It Works with Examples

Some numbers come from user input and other come from math operations. Sometimes, these numbers need to stay positive. The…

JavaScript Introduction: What is JavaScript?

The current essay is devoted to the basic principles and introduction of JavaScript. This language no longer needs to be…

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.