Binary + and String Concatenation
- If the binary
+
is applied to strings, it merges (concatenates) them.
- If one of the operands is a string, the other one is converted to a string too.
- However, note that operations run from left to right.
console.log('1' + 2); // "12"
console.log(2 + 2 + '1'); // "41" and not "221"
- String concatenation and conversion is a special feature of the binary plus +.
- Other arithmetic operators work only with numbers and always convert their operands to numbers.
console.log(2 - '1'); // 1
console.log('6' / '2'); // 3
Numeric Conversion, Unary +
- The unary plus is applied to a single value, doesn’t do anything to numbers.
- If the operand is not a number, the unary plus converts it into a number.
- It does the same thing as
Number()
function.
- If we are getting values from HTML form fields, they are usually strings.
- This operation can help you to convert string values to number.
console.log(Number("5")); // 5
let x = "1";
console.log(+x); // 1
console.log(+true); // 1
console.log(+""); // 0
console.log(+undefined) // NaN
console.log(+null) // 0
let apples = "2";
let oranges = "3";
console.log(+apples + +oranges); // 5
Assignment =
let a, b, c;
a = b = c = 2 + 2;
// a = 4, b = 4, c = 4
- Remember that the call
x = value
writes the value into x and then returns it.
let a = 1;
let b = 2;
let c = 3 - (a = b + 1);
console.log(a); // 3
console.log(c); // 0
Exponentiation **
- The exponentiation operator
**
is a recent addition to the language.
- For a natural number
b
, the result of a ** b
is a
multiplied by itself b
times.
- The operator works for non-integer numbers of a and b as well.
console.log(2 ** 2); // 4 (2 * 2)
console.log(2 ** 3); // 8 (2 * 2 * 2)
console.log( 4 ** (1/2) ); // 2 (power of 1/2 is the same as a square root)
console.log( 8 ** (1/3) ); // 2 (power of 1/3 is the same as a cubic root)
Increment/Decrement