Unary and String Operators in Javascript


In javascript Unary and String Operators are commonly used but are rarely known for what they are. So in this article we only put a highlight of what these are, we are keeping it short and to the point.

Unary Operators:

+, -

Unary operators are actually these two, they take only one operand and are basically to change the sign of the values. for example in the following program,


var a = 5;
console.log(a);

a = -a;
console.log(a);

Output:
5
-5

In the program we see that the -(unary minus) operator can be used to convert a number into negative number, In real the 5 or +5 is same so no real work to use it but you can use it to convert a string number into a real number for example in following example program


var b = "6";
console.log(typeof b);

b = +b;
console.log(typeof b);

Output:
string
number

As we see from the program the b is a string first and when we apply +(unary plus) operator it converts the string into number.

Note: In this example we have used typeof keyword, or you can say operator if you prefer. Anyway, the typeof is used to check the value type stored in a field.

String Operator

The plus(+) is used as a string operator, this is used as a string concatenation operator to join two strings. As we show in following program.


var a = "Hello";
var b = "World";
var c = a+" "+b;

console.log(a);
console.log(b);
console.log(c);

output:
Hello
World
Hello World

as we see in this program that the +(plus) acts as the concatenation operator to combine two or more string. It can also be used to combine the string and a number, but in that case JavaScript will first covert the number into a string and then combine.