Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Adding a Number to a Boolean
In the above code we add 3 to
true and then 3 to
false. Our answers are
true boolean into the value of
1, and a
false boolean into the value of
0. Let's set up an equality equation to test this theory:
We get true back for both equations. Now that we know the values that
false coerce to, try answering this quiz question correctly:
Adding A String to a Number
What happens when we add a string to an actual number? Run the code below and lets see if the answer is what you expect:
48? You see, when the plus operator is placed between to operands, and one is a string, it will convert the other number or boolean to a string and concatenate them. By this logic:
'4' + 8 becomes
'4' + '8' and we get an answer of
Let's try another example:
+ opperators, the left-most operator is evaluated first. Here's a visualization of what that would look like:
"1" + 1 + 1 "11" + 1 "111"
But what happens if our string value is the last value in our equation? Would anything change? Run the following code and lets see. Notice that the difference between this example and the example above is the location of our string variable.
1 + 1 which equals
2. Only then do we move on and add in the string value of
'1'. Now String concatenation occurs and the result is
Here’s the chain of events:
1 + 1 + "1" 2 + "1" "21"
Based on what we've learned so far, what do you think would happen here?
Using the negative operator
What if we attempt to negate a string with the negative operator and then add it to a number? For example,
-"50" + 50. What would the answer be? Let's look at an example:
As expected, our String + Number result is
"5050" due to string concatenation. Howver, the negation in the second equation changes things. The minus sign before
"50" is a unary minus operator that will actually coerce the string into a number and make it negative. Thus, our equation becomes
-50 + 50 which equals
Seeing as the minus operator coerced our string value into a number, what happens if we use the minus operator on a different value of string? Let's look at this example:
"giddyup" string into a number value. But will it be able to? Run the code below:
Now it's time to combine everything we've learned in this article and answer one final question. Are you up for it?
You made it!
Good work! I hope you enjoyed my article. This article was originally published at codeburst.io