DEV Community

Cover image for JS Test #3: Adding strings to numbers and booleans
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Updated on • Originally published at learn.coderslang.com

JS Test #3: Adding strings to numbers and booleans

code-snippet

Will we see any output? If yes, then what would it be?

.

.

.

.

.

.

.

.

.

.

.

.

.

To answer this question correctly, you need to understand the typecast rules in JS.

The arithmetic operations + and - have the same priority, so the value of x will be calculated from left to right without any exceptions.

First, we concatenate the string '2' with the number 3. The result is the string '23'.

Second, we try to subtract the boolean value true from the string '23'. To make this operation possible, both boolean and a string have to be cast to a number. Non-surprisingly '23' becomes 23 and true is turned to 1. Eventually, we do the subtraction and get the result, number 22.

The last step is to add the string '1' to the number 22. Applying the same concatenation that we did on the first step gives us the result - a string '221'.


ANSWER: there are no issues with the expression in line 1. The value of x is a string ’221’, which will be successfully logged to the screen.

Learn Full Stack JavaScript

Top comments (0)