Unary Plus and Minus
+ is the unary plus. When the unary plus is applied to a nonnumeric value, it performs the same conversion as the Number() casting function.
<!DOCTYPE html>
<html>
<head>
<title>Operator Example</title>
<script type="text/javascript">
var s1 = "2";
var s2 = "A";
var s3 = "2.1";
var s4 = "0xAA";
var b = true;
var b2 = false;
var f = 1.1;
var o = {
valueOf: function() {
return 10;
}
};
document.writeln(s1);
document.writeln(s2);
document.writeln(s3);
document.writeln(s4);
document.writeln(b);
document.writeln(b2);
document.writeln(f);
document.writeln(o);
s1 = +s1;
s2 = +s2;
s3 = +s3;
s4 = +s4;
b = +b;
b2 = +b2;
f = +f;
o = +o;
document.writeln(s1);
document.writeln(s2);
document.writeln(s3);
document.writeln(s4);
document.writeln(b);
document.writeln(b2);
document.writeln(f);
document.writeln(o);
</script>
</head>
<body>
</body>
</html>
The unary minus operator negates a numeric value.
<!DOCTYPE html>
<html>
<head>
<title>Operator Example</title>
<script type="text/javascript">
var num = 2;
num = -num; //becomes -2
document.writeln(num);
</script>
</head>
<body>
</body>
</html>
When used on nonnumeric values, unary minus applies the same rules as unary plus:
<!DOCTYPE html>
<html>
<head>
<title>Operator Example</title>
<script type="text/javascript">
var s1 = "2";
var s2 = "A";
var s3 = "2.1";
var s4 = "0xAA";
var b = true;
var b2 = false;
var f = 1.1;
var o = {
valueOf: function() {
return 10;
}
};
document.writeln(s1);
document.writeln(s2);
document.writeln(s3);
document.writeln(s4);
document.writeln(b);
document.writeln(b2);
document.writeln(f);
document.writeln(o);
s1 = -s1;
s2 = -s2;
s3 = -s3;
s4 = -s4;
b = -b;
b2 = -b2;
f = -f;
o = -o;
document.writeln(s1);
document.writeln(s2);
document.writeln(s3);
document.writeln(s4);
document.writeln(b);
document.writeln(b2);
document.writeln(f);
document.writeln(o);
</script>
</head>
<body>
</body>
</html>
Home
JavaScript Book
Language Basics
JavaScript Book
Language Basics
Operators:
- JavaScript Operators
- Increment/Decrement Operators
- Increment/Decrement Operators for String, Boolean, Floating-point and Object
- Unary Plus and Minus
- Bitwise Not operator
- Bitwise AND
- Bitwise OR
- Bitwise XOR
- Left Shift
- Signed Right Shift
- Unsigned Right Shift
- Logical NOT
- Logical AND
- Logical OR
- Multiply
- Divide
- Modulus
- Add
- Subtract
- Relational Operators
- Equal and Not Equal
- Identically Equal and Not Identically Equal
- Conditional Operator
- Assignment Operators
- Comma Operator