Tuesday, 18 August 2015

InDetail: JavaScript Datatype - Number

Numbers In JavaScript

    Before going to the discussion, let’s see what is  a number.

123 is a number,
123.5 is a number,
0xff is also a  number (hexa decimal number),
5e2 is also a number (represented in exponential form).
“abc” is not a number (String literals are not numbers),
“123” is also not a number, but you can convert it to a number.

Numbers are used to store numeric data like weights, and quantities of things. By seeing the examples, you can understand that there are two types of numbers i.e a. Integers b. floating point numbers

How Numbers are represented in JavaScript?

Before knowing how numbers are represented in JavaScript, let’s see how they are represented in other languages. In Java, each of the above numbers have different data types, for example, 123 can be represented as byte, int, and long. For representing 123.4 Java has float and double types. Hex decimal numbers can be represented with int and long data types, and 5e2 with double datatype.

But in JavaScript, all the numbers are floating point numbers, even Integers also. Most JavaScript engines optimize and do distinguish between floating point numbers and integers.

How to Declare and Initialize Numbers In JavaScript:

You can write numbers in 3 ways.
a.    Using Number literals.
b.    Using function – Number().
c.    Using Number constructor – Number().

Using Number literals:

Here you just need to create a variable and assign number to it. Here a represents primitive type of number.
var a = 5; 
Using Number() function:

In this case you need to pass number value to function Number(). It also represents primitive type of number.
 var b = Number(5); 
Using Number constructor:
You can create a Number with Number constructor.

var c = new Number(5);

Here c is of type object, not number. You can see types of a,b,c below.
typeof a; // “number”.

typeof b; // “number”.

typeof c; // “object”.

typeof is an operator which returns datatype of variable

As variable c is an object, Let’s check for equality among primitive variables a,b and object type variable c.
a == c; // true

a === c; // false

b == c; // true

b === c; //false


a == b ; // true

a === b; // true

If you want to know how ==, === works see the post == vs ===.

Some more about function Number():
You can pass any data type to Number() function. For example Number(‘’), Number(‘123’);
var a = Number(‘’); // value of a is 0.
var b = new Number(‘’); // value of b is 0.
It converts the value passed into number, in that process it ignores any leading and trailing white spaces. For ex:
 var a = Number(‘    5    ‘); // value of a is 5.
 var a = new Number(‘    5    ‘); // value of a is 5.
When you pass different types to Number() function, the conversion happens like below.
var a = Number(undefined); // NaN
var b = Number(null); // 0
var c = Number(false); // 0
var d = Number(true); // 0
var e = Number(5); // 5 - same as input
var f = Number(‘3.12’); // 3.12 – parse the number in the string, like point b.
d.    If you pass an object to Number function, internally, it calls the function ‘ToPrimitive(value, Number) and convert the result. For ex:
var str = new String(“5”); // creates object.

var a = Number(str); // 5 

Invoking Methods on Literals:
Literals like 123, 123.0 are also numbers, so you can directly invoke methods on them. While accessing methods on literals using ‘.’ operator, you need to distinguish it from decimal dot. Below is how you can do it.
123..toString(); // with 2 dots.

123 .toString(); // with space before the dot.

123.0.toString(); // nothing extra required when accessing on floating numbers.

(123).toString();//surround the number with brackets and access with ‘.’

Special Number Values:
JavaScript has special number values, 
NaN, Infinity for two error values,
+0, -0 for Zero.

NaN :
It is an abbreviation for “not a number”. results, when you try to parse an alphabetical string for eg:
var a = Number(‘xyz’); // NaN

var b = Number(undefined); // NaN

When an operation failed:
Math.sqrt(-1); // NaN 
One of the operand is NaN
NaN + 3; // NaN 

How to check whether a value is NaN? 
Use isNaN() global function, it returns true if value is not a number else false.
isNaN(NaN); // true

isNaN(33); // false , 33 is a number
Infinity is an error value, that comes when a number can’t be represented because its magnitude is too large, or a division by zero has happened. It has two values, positive Infinity (Infinity) and negative (-Infinity) For ex:
Math.pow(2, 1024); // Infinity

3 / 0 ; // Infinity

3 / -0; // -Infinity

Infinity is larger than any number (except NaN).
–Infinity is smaller than any other number (except NaN).

Computations on Infinity
Infinity – Infinity ; // NaN

Infinity / Infinity; // NaN

Infinity + Infinity; // Infinity

Infinity * Infinity; // Infinity

Checking for Infinity:
strict and lenient equality works fine for Infinity. For eg:
var x = Infinity;

x == Infinity; // true

How to check whether a value is neither Infinite nor NaN?
Use isFinite() global function.
isFinite(5); // returns true is number is finite.

isFinite(Infinite); // false.

isFinite(NaN); // false.

Arithmetic Operators on Numbers: 
you can apply following arithmetic operators on numbers.
Addition (+) : Adds two numbers for eg:

 var c = 2 + 3; // 5

Subtraction (-) : Subtracts two numbers for eg:

 var c = 3 – 2; // 1

Multiplicaiton(*) : Multiplies two numbers for eg:

 var c = 3*2; // 6

Division (/) : Divides two numbers. For ex:

 var c = 3/2 ; // 1.5

Remainder( % ): Gives remainder of division between 2 numbers. For ex:

 var c = 3%2; // 1

 var d = -3%2; // -1

This operation is not modulo, it returns a value whose sign is same as the first operand. 

–number: Negates its argument. For ex:

 var c = -32; // -32

+number: non numbers are converted to a number. For ex:

 var c = +true; // c = 1

++, -- : increments and decrements variable value by 1 respectively. 

Bitwise Operators:
Bitwise Not Operator ( ~ ): computes the one’s complement of a number. 

var a = ~5; // -6

Bitwise Or Operator ( | ): performs (|) operation between bits of two numbers. For ex:

var a = 5 | 4; // 5

Bitwise And ( & ): performs (&) operation between bits of two numbers and gives result. For ex:

var a = 5 & 6; // 4 

Bitwise XOR ( ^ ):  performs exclusive or operations between bits of two numbers. For ex:

var a = 5 ^ 4; // 1

Bitwise Shift Operators:
JavaScript has 3 bit wise shift operators. Those are
Left shift (<<):
Left shifts the number by given no of bits. It requires 2 operands. Left operand is actual number, right operand is how many bits to shift. For ex:
var a = 10 << 2; // result is 40. 
Right shift (>>):
Right shifts the number by given no of bits. It also requires 2 operands just like left shit. This operator is also called as signed right shift, because it preserves sign bit. For ex:
var a = -2 >> 1; // result is -1
Unsigned Right shift (>>>):
Works similar to right shift operator, but it won’t preserve sign of the given number. For example,
var a = -2 >>> 1; // result is 2147483647.

whereas -2 >> 1 results to -1.


Post a Comment

Note: only a member of this blog may post a comment.