Addition involves adding numbers, while concatenation involves combining strings.
In JavaScript, both operations use the same + operator.
As a result, adding a number as a numeric value will produce a different outcome than adding a number as a string.
let x = 10; x = 10 + 5; // Now x is 15 let y = 10; y += “5”; // Now y is “105” |
When adding two variables, predicting the result can be challenging.
let x = 10; let y = 5; let z = x + y; // Now z is 15 let x = 10; let y = “5”; let z = x + y; // Now z is “105” |
In JavaScript, all numbers are stored as 64-bit floating point values (Floats).
Like all programming languages, JavaScript faces challenges when dealing with precise floating point values.
let x = 0.1; let y = 0.2; let z = x + y // the result in z will not be 0.3 |
To address the issue above, it can be helpful to multiply and then divide.
let z = (x * 10 + y * 10) / 10; // z will be 0.3 |
JavaScript allows you to split a statement across two lines.
let x = “Hello World!”; |
However, splitting a statement in the middle of a string will not work.
let x = “Hello World!”; |
You need to use a backslash if you want to break a statement within a string.
let x = “Hello \ World!”; |