Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain +var and -var unary operator in javascript

Tags:

I'm trying to understand unary operators in javascript, I found this guide here http://wiki.answers.com/Q/What_are_unary_operators_in_javascript most of it makes sense but what I don't understand is how the following examples would be used in an actual code example:

+a; -a; 

To my understanding the +a; is meant to make the variable the positive value of a and the -a; is meant to make the variable the negative value of a. I've tried a number of examples like:

a = -10; a = +a; document.writeln(a); 

And the output is still -10;

I've also tried:

a = false; a = +a; document.writeln(a); 

And the output is 0;

What is a practical code example of these unary operators?

like image 557
fakeguybrushthreepwood Avatar asked Aug 25 '12 09:08

fakeguybrushthreepwood


People also ask

What is unary operator in JavaScript?

A unary operation is an operation with only one operand. This operand comes either before or after the operator. Unary operators are more efficient than standard JavaScript function calls. Additionally, unary operators can not be overridden, therefore their functionality is guaranteed.

What are unary operators explain?

In computer programming, a unary operator is an operator that takes only one value for its operation. An example in the C programming language is the increment operator (++), which increments a given value by 1. For instance, to increment the variable x by 1, you could express this as: x++

Which is the unary operator?

The unary operators are as follows: Indirection operator ( * ) Address-of operator ( & ) Unary plus operator ( + )

What is an unary operator example?

In mathematics, an unary operation is an operation with only one operand, i.e. a single input. This is in contrast to binary operations, which use two operands. An example is any function f : A → A, where A is a set.


1 Answers

The + operator doesn't change the sign of the value, and the - operator does change the sign. The outcome of both operators depend on the sign of the original value, neither operator makes the value positive or negative regardless of the original sign.

var a = 4; a = -a; // -4 a = +a; // -4 

The abs function does what you think that the + opreator does; it makes the value positive regardless of the original sign.

var a =-4; a = Math.abs(a); // 4 

Doing +a is practically the same as doing a * 1; it converts the value in a to a number if needed, but after that it doesn't change the value.

var a = "5"; a = +a; // 5 

The + operator is used sometimes to convert string to numbers, but you have the parseInt and parseFloat functions for doing the conversion in a more specific way.

var a = "5"; a = parseInt(a, 10); //5 
like image 69
Guffa Avatar answered Oct 21 '22 08:10

Guffa