JavaScript – Data Types

Well, we all know that JavaScript is a functional language (which is an entirely a different discussion about being functional language) has some data types, namely:

Let’s talk about each of this data type in detail:

Number:

JavaScript has no integers, numbers are represented by data type Number. They are 64-bit floating point numbers. Well it is a strange name for floating point numbers and they are represented by standard IEEE-754 which are similar to double data type.

Now as we know that they are floating point numbers we have to be bit careful about arithmetic operations over the operands of this type, especially if we are performing calculations representing money. The reason is, floating point operations always return approximations, not exact values. For example:

function multiplyTest() {
var x = 0.1 * 0.2;
console.log(x);
}
multiplyTest();
//which might return an approximate answer like 0.020000000000000004
//this is a bad idea if we are dealing with $ or INR values
view raw multiplyTest.js hosted with ❤ by GitHub
Multiplying number in JavaScript

Now, we will see how to deal with this situation. Solution here is very simple. We know that when we are dealing with money, we deal with numbers like 34.56$ or 8.99$ or 100.35 INR. These are the numbers with precision up to 2 digits after floating point. So scale them up by multiplying with 100. Perform arithmetic operations and then again scale them back by diving with 100. Let’s apply this solution to function above and see what it returns:

function multiplyTest() {
var x = ((0.1 * 100) * (0.2 * 100)) / 10000;
console.log(x);
//We are dividing here with 10000 because we multiplye 2 different numbers with 100
//here console log statement will return exact answer 0.02
}
multiplyTest();
Solution

Another important value to keep in mind is NaN while dealing with arithmetic operations. It is an output of any erroneous arithmetic calculation. If any arithmetic function is given NaN as an input, it is sure that end result will be NaN too.

There are few strange things about NaN. NaN is not equal to NaN. NaN is not greater than or less than NaN. NaN is not a numerical value but if we check type of NaN in JavaScript using typeof, the type returned is a Number. (Strange!!!!)

//You can directly type this in chrome console for instant output
NaN == NaN // false
NaN >= NaN // false
NaN <= NaN // false
typeof(NaN) // number (though it say, it is `not a number`)
view raw js-nan.js hosted with ❤ by GitHub
NaN behavior in JavaScript

It provides a function (or we can say constructor), Number(value) which helps converting a string into a Number. It works same a + prefix operator (we will see in the program).

function sum() {
var a = new Number('3');
//Converts String value '3' to numeric value 3
var b = +'4';
//Converts String value '4' to numeric value 4
var c = a + b;
//If there is any issue in conversion it must return NaN as output
console.log(c);
// Output is numeric value 7
}
sum();
view raw sum.js hosted with ❤ by GitHub
Type coercion with Number and + operator

The final thing we will discuss about Number is a function called parseInt (strange again, now it says int). Well, this function helps parsing a string into Number. It takes two arguments: parseInt(String to parse, raddix)

function parseIntTest() {
var a = parseInt("5");
console.log(`a: ${a}`)
//variable a will have numeric value 5
// this is a bug in some of the older browsers where
// parseInt with '08' will return 0
// if you are supporting older browsers, make sure you
// mention second argument, the base for number system as 10
var b = parseInt("08");
console.log(`b: ${b}`)
//variable b will have numeric value 0
var c = parseInt("08", 10);
console.log(`c: ${c}`)
//variable c will have numeric value 8
}
parseIntTest();
view raw parse-int.js hosted with ❤ by GitHub
parseInt(any, radix)

parseInt will  stop parsing the input String when it will encounter the first no-numeric character. It is also important to pass the radix argument which we can see in the program above. It the input String is ’08’ in that case we can see the output is numeric value 7 because parseInt thinks (in the absence of radix argument) that input String is an octal number input. In the third statement when we have passed raddix argument we can see that now the output is 8. The radix argument is nothing but the base into which we want to convert the String.

It is important to know as a developer that the default value of radix is not 10. It always depends on the first input. parstInt converts first arguments to string. If it can be parse the output will be an Integer other wise it will return NaN.

String

String are nothing but sequence of 16-bit characters. One important thing to keep in mind is, in JavaScript String UCS-2 encoding not UTF-16. The major difference between UCS-2 and UTF-16 is, in UCS-2 there is no support for surrogate pairs (For detailed explanation of surrogate pairs check this out. For String variables in JavaScript, similar strings are equal. == returns true for similar strings. Also we can represent String literals  using either ” or “”. Both are same.

string.length in JavaScript returns the count of number of 16-bit characters in a string. Function String(value) helps to convert numeric value into String.

  1. Input string begins with 0x or 0x, the radix value will be assumed as 16
  2. Input string begins with 0, the radix value assumed is 8 or 10. Which will be used? It depends how browser has implement ECMA5 standards. How to cope with it? Always be specific and provide radix value.
  3. For any other input string, radix assumed is 10.

Boolean

There are two Boolean values, true and false. Function Boolean(value) takes value as an input and based on the value being truthy or falsy, it returns true or false. This urges us to delve in another concept which is: ‘What is truthy or falsy value?

Well, in JavaScript falsy values are:

  • false
  • NaN
  • null
  • undefined
  • ” or “” (empty String)
  • 0 (numeric value zero

Rest all values are truthy value. Even “0” (zero in quotes) or “false” are turthy values as all the non-empty String are truthy.

//if you try following line of code in chrome console
var a = new Boolean(undefined);
console.log(a);
//false
a = new Boolean(null);
console.log(a);
//false;
a = new Boolean(0);
console.log(a);
//false
a = new Boolean('0');
console.log(a);
//false
a = new Boolean(false);
console.log(a);
//false;
a = new Boolean('false');
console.log(a);
//true
a = new Boolean(NaN);
console.log(a);
//false
view raw js-boolean.js hosted with ❤ by GitHub
Boolean in JavaScript

null

In JavaScript null is not a value but absence of value. Yet it is import to note that typeof null is object. That’s the way it has been implemented from the beginning and now it cannot be changed without breaking applications written in the past. JavaScript engine, whenever not sure, assigns undefined while null is assigned by the programmers.

undefined

Well, it  is a special value (I wish a less confusing name would have been choosen) assigned to any variable when when left uninitialized. It means a variable defined but not assigned any value will have value undefined in it. undefined == undefined returns true and type of undefined returns undefined when typeof function is used. undefined is also a value returned when we try to extract a member from an object when it doesn’t have a member present.

var emp = {
name: 'John Snow',
email: 'john.snow@abc.com'
}
console.log(emp.name);
//John Snow
console.log(emp.address);
// undefined (here we are trying to extract a member which object doesn't have)
var test;
console.log(test);
//undefined (a variable defined but not initialized)
view raw js-undefined.js hosted with ❤ by GitHub
undefine in JavaScript

Rest everything in Java is an Object. But that will be an entirely a different discussion. We will take it separately in a different article.

One thought on “JavaScript – Data Types

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 )

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

%d bloggers like this: