Loading...

Type Conversion & Arithmetic Operators in JavaScript

Type Conversion & Arithmetic Operators in JavaScript

In the previous articles, we have seen many data types including numbers, strings, booleans, and the object data type. We have also learned a few JavaScript fundamentals

Today you will learn how the console.log() statement actually prints a bunch of text along with numbers like age and salary directly. You will also learn how to do it by yourself.

You will also look at the basic mathematical operations that you can do in JavaScript.

And remember, you can download all the code and experiment with it on codedamn playgrounds. It is a full-fledged IDE that you can use online without installing anything on your system.

Let’s begin!


How to print variables in console using console.log()?

Check out the code below and see statement 1:

Printing Strings with console.log()
Printing Strings with console.log()

We have firstName as Jason and we are printing it out on the console with some other text (String data type). “Jason” is also a String datatype.

The output you see is: “Hi! I am Jason”.

You can easily figure out that JavaScript just combined two String datatype objects into a single object!

Now, check out statement 2:

Printing numbers with console.log()
Printing numbers with console.log()

You took a few strings and then added a number to the string. The final output was a string! Where did the number go!?

This is exactly why you need to understand type conversions! 

JavaScript is a clever language. When you put a number and a string together, it automatically converts the Number to a String datatype so that it can perform that “addition” on the strings. It is also called String Concatenation.

Well, then, what will be the output of the following code?

Printing String & Number with console.log()
Printing String & Number with console.log()

If your answer is:

I am 221 years old.

You will be 100% right! Remember, “+” concatenates the strings. So if you add a Number and a String Datatype together, the Number will be converted to a String type and the final result will be a String

Since JavaScript does it all under the hood, it is called Implicit Type Conversion.

If you are curious try replacing “+” addition with:

  • : Subtraction
  • *: Multiplication
  • / : Division
Subtracting String from Number
Subtracting String from Number

You will realize that the calculations were actually performed! But why? The addition wasn’t done. We were not able to increment the age when we tried adding 1 to it. Why were we able to subtract, multiply or divide?

The reason is simple, JavaScript is clever. This time it saw that it could convert the string into a number and actually complete the calculation. So it did. And you get Number data type as an output.

Attempt the following and note the output for each by adding a console.log() after each statement. You can find the code here.

Mathematical operations on a mix of data types
Mathematical operations on a mix of data types

The general rule of thumb is that if it makes sense, JavaScript will compute it.

Find a summary table below for a quick reference:

Data Type 1OperatorData Type 2Output
StringaddString, Number, Boolean undefined, nullString
Stringsubtract, multiply, divideNumberNumber
Stringsubtract, multiply, divideNull, StringNaN
Stringsubtract, multiply, divideundefinedundefined
Number as String, Numberadd, subtractBooleanNumber
Numberadd, subtractnullNumber
Numbermultiply, dividenullInfinity, 0
undefinedANYANYundefined
Implicit Conversion

Just like implicit conversion, if you want you can convert from one type to another explicitly, i.e., you tell JavaScript what conversion to make!

Explicit Conversion

The syntax is:

Syntax for Explicit Conversion
Syntax for Explicit Conversion

I’d recommend you to try out various value parameters directly on playground and play with the code.

Practice explicit conversion
Practice explicit conversion

This is the end of Type Conversion. Next up is basic mathematics!


Arithmetic Operators in JavaScript

Let me try to keep this section quick! You have done simple addition, multiplication, division, and subtraction in school. You can do the same in JavaScript between two Number data types.

Basic mathematical operations
Basic mathematical operations

Well, that was easy! I have a question for you:

Since 20.5 doesn’t divide 100 fully, what is the remainder? Can you calculate it in JavaScript? 

Of course, you can. And you don’t need to write any calculations logic. You can simply use the modulo (%) operator as shown below:

Modulo in JavaScript
Modulo in JavaScript

What if you want to calculate the 2 raised to the power 3? Just use the exponent operator → base**power = 2**3

Exponent in JavaScript
Exponent in JavaScript

There is another thing JavaScript provides to increase or decrease the value of a Number data type by 1. 

OperatorOperation
++Increment the value by 1
– –Decrement the value by 1
Increment and decrement in JS

These operators are the same as doing:

variable = variable + 1

variable = variable - 1

Then why do we have these separately? Well for starters, they are a quick way to increase or decrease the value by 1 (you will use it a lot in loops).

Another thing is, that their placement matters! What do you think is the output of the following code?

Pre-increment & post-increment
Pre-increment & post-increment

If you just go by the explanation above, you would say that line 2 prints 2, and line 3 prints 3! You’d be partially correct. Line 3 does print 3, but line 2 prints 1!

Pre-increment & post-increment
Pre-increment & post-increment

But why does this happen at all? See, when you place “++” after the variable, JavaScript will first print the value of x and then increment it.

But when you place it before the variable, JS will increment the value first and then print it (reverse of the above).

This is what it looks like internally:

Pre and post increment logic flow
Pre and post-increment logic flow

You can similarly use “--” to decrement the value by 1!

Below you will find a summary of the arithmetic operators for a quick reference!

OperatorOperationExample
+Additionx + y
-Subtractionx – y
*Multiplicationx * y
/Divisionx / y
%Modulo/Remainderx % y
**Exponentx ** y
++Increment by 1x++ or ++x
--Decrement by 1x– or –x
Arithmetic operators in JS

That’s all folks! In the next article, we will learn about if-else statements in JavaScript which will help you write the logic on which your applications will eventually run! See you!

Till then, practice, practice, and practice on codedamn playgrounds.

Sharing is caring

Did you like what Rishabh Mittal wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far