Unary operators help you change or check a single value quickly. They make your code shorter and easier to read.
0
0
Unary operators in Javascript
Introduction
When you want to add or subtract 1 from a number, like counting steps.
When you want to convert a string to a number before doing math.
When you want to check the type of a value to understand what it is.
When you want to flip a true/false value to its opposite.
When you want to delete a property from an object.
Syntax
Javascript
++variable
--variable
+value
-value
!value
delete object.propertyUnary operators work with only one value.
Some unary operators change the value, others just check or convert it.
Examples
Increment operator adds 1 to the variable.
Javascript
let count = 5; count++; // count becomes 6
Unary plus converts a string to a number.
Javascript
let str = "123"; let num = +str; // num is 123 as a number
Logical NOT flips true to false and vice versa.
Javascript
let flag = true; let notFlag = !flag; // notFlag is false
Delete removes a property from an object.
Javascript
let obj = {a: 1}; delete obj.a; // obj is now {}
Sample Program
This program shows different unary operators: increment, decrement, unary plus, logical NOT, and delete.
Javascript
let x = 10; console.log(x); // 10 x++; console.log(x); // 11 x--; console.log(x); // 10 let str = "42"; console.log(+str); // 42 (number) let isTrue = false; console.log(!isTrue); // true let person = {name: "Anna", age: 25}; delete person.age; console.log(person); // { name: 'Anna' }
OutputSuccess
Important Notes
Increment (++) and decrement (--) operators change the variable's value by 1.
Unary plus (+) tries to convert a value to a number.
Logical NOT (!) flips true to false and false to true.
Delete removes a property from an object but does not affect variables.
Summary
Unary operators work with one value to change or check it.
They help write shorter and clearer code for simple tasks.
Common unary operators include ++, --, +, -, !, and delete.