ES6 – Unary Operators

ES6 – Unary Operators

Unary operation in JavaScript is an operation with only one operand. Unary are consider to be more useful and efficient than JavaScript functions, these unary operators come either after or before the operator. Below is a list of all unary operators in JavaScript.

  • + Addition
  • - Subtraction
  • / Division
  • * Multiplication
  • ~ Invert each bits
  • ! Logical NOT operator
  • delete Deletes object’s property
  • typeof Returns type of operand
  • void Evaluation without returning value

JavaScript plus & minus unary

The JavaScript plus + and minus - operators will attempt to convert the operators to a number if the operand is not a number. Below are some of their behaviors when used as unary operator with different datatypes.


    

// Unary plus operator
console.log(3+2)
// 6

console.log(3+”2″)
// “32”

console.log(3+”-2″)
// “3-2”

console.log(3+true)
// 4

console.log(3+false)
// 3

console.log(3+null)
// 3

console.log(NaN+NaN)
// NaN

console.log(undefined+undefined)
// NaN

console.log({}+{})
// [object Object][object Object]

 

// Unary minus operator

console.log(3-2)
// 1

console.log(3-“2”)
// 1

console.log(3-“-2”)
// 5

console.log(3-true)
// 2

console.log(3-false)
// 3

console.log(3-null)
// 3

console.log(NaN-NaN)
// NaN

console.log(undefined-undefined)
// NaN

console.log({}-{})
// [object Object][object Object]