Numbers, Strings and Coercion
Terminology
- Coercion
- Implicitly converting a value from one type to another.
- Arithmetic operator
- Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.
- Addition Operator (
+
) - The addition operator produces the sum of numeric operands OR string concatenation.
- String Concatenation
- Joining two or more strings together.
Untyped languages and coercion
It's important to know that Javascript is an untyped language, meaning that a variable will often be converted from one data type (such as a number) to another (a string). This often "helps" programmers type less code but will sometimes cause problems when you don't expect it.
- See: JavaScript type coercion explained for more information
Key Takeaways
- The addition
+
does two jobs:- It adds numbers together;
- It concatenates (joins) two strings together.
- The
+
operator will concatenate values if one or more is a string.- For example:
1 + 1
is2
, but1 + "1"
is"11"
.
- For example:
- When a number is needed but the type cannot be converted to a number, you'll see the dreaded
NaN
property. - When you need to concatenate a string with a variable, it's recommended you use the new (ES6) template literal syntax.