JavaScript and Operators

JavaScript and Operators

Here’s a quiz for you (the answer is at the bottom of the post).

What is the expected output of these three lines of code, and why is it like that?

//Question 1
console.log('6' + 2);

//Question 2
console.log('6' - 2);

//Question 3
console.log('6' * '2');

This isn’t as straight forward as you might think, and will not produce the “expected” output.

Some operators in JavaScript do Type conversion when used.
1- The Number 2 is added as a String to the String 6, so the output is 62
2- The String 6 is converted to Number 6 and the Number 2 is subtracted from the Number 6. Output is 4
3- The String 6 and the String 2 are both converted to Numbers and are multiplied as Numbers. Output is therefor 12

JavaScript is a wonderful language to learn and use 😉

Leave a Reply

Your email address will not be published. Required fields are marked *