Playing Around With Strings
Explore string operations in JavaScript including concatenation and immutability. Understand automatic type casting and master converting strings to integers and floats using parseInt and parseFloat methods for practical coding tasks.
We'll cover the following...
Concatenating strings
A string is basically a series of characters. Let’s perform some operations on strings.
The + concatenates strings. Concatenation means that you join the contents of two strings one after the other.
Strings are immutable, which means that their value cannot be changed. When concatenating two strings, the result is saved in a third-string.
Automatic type casting
If any of the operands of plus is a string, the result becomes a string. JavaScript automatically converts the operands of an operator to the same type. This is called automatic type casting.
Rules may become confusing, so don’t abuse automatic typecasting.
Parsing strings as integers
You may have to explicitly cast a string to an integer to be able to add it to another integer:
All the above conversions work. The first relies on giving a sign to a numeric string which converts it to a number. Then 1+2 becomes 3. The second typecast is more explicit: you use Number to wrap a string and convert it to a number.
I recommend using the third option: Number.parseInt with a radix. parseInt converts a string into a number. The second argument of parseInt is optional: it describes the base in which we represent the number.
Arbitrary strings are often NaN. “2” in base 2 is 10. You can see how easy it is to convert a binary or a hexadecimal (base 16) string into a decimal number. Base 16 digits are 0123456789abcdef. The last 6 digits may also be upper case.
Number.parseInt recognizes the starting characters of a string as integer numbers and throws away the rest:
Parsing Strings as floating numbers
The dot is not a character present in integer numbers, so everything after 1234 is thrown away by Number.parseInt.
You can also use Number.parseFloat to parse floating point. It parses the floating-point number until the terminating space:
What will be the output of
console.log(Number.parseInt( "f", 16 ));
10
NaN
15