How do numbers differ in Javascript and Java?

Numbers are a basic data type.

You can’t have a programming language without them.

Yet how these numbers are treated can vary slightly between different languages.

Brendan Eich , when he created Javascript was hugely influenced by Java. In face he was asked to create a Java language for the browser by Netscape and ended up creating Javascript.

Though Java and Javascript have a lot of similarities , they differ quite widely.

Here is a look at the features which Javascript has and Java does not:

All numbers in Javascript are floating point numbers:

So 5 = 5.0 in Javascript.

But in Java they are represented by two different primitive data types int and float respectively.

Not a number can be represented by a value in Javascript:

In Java if you try to parse a string (which has a non numerical value) as a number it would throw an exception.

But Javascript would return NaN (Not a number):

Number('hello') returns NaN

Javascript can represent infinity:

If you divide a number by zero Java will throw exception.

But javascript will return infinity:


<script>
alert( 5/0);

</script>

The above code alerts the value Infinity:

Infinity can be used to compare with other values:


<script>


alert( 3 < Infinity);

</script>

The above code returns true:

You can also use -Infinity to represent infinity in the negative direction:


<script>


alert( -3 < -Infinity);

</script>

The above code returns false since -Infinity represents the minimum number:

So the range of numbers in Javascript is -Infinity to Infinity!

You can convert a string to a number by using the plus’+’ operator in Javascript:

Converting a string to number is easy in Javascript.

You just need to append the plus operator before the string variable.

In Java you need to use methods like parseInt().

The below code returns the value ’32’ initially as it considers 3 and 2 as strings.


<script>

let x = '3';
alert( x+2);

</script>

Appending ‘+’ before x changes it to a number.

The below code returns 5:


<script>

let x = '3';

alert( +x+2);

</script>

That’s it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s