Data Types in Javascript

JavaScript is not strict when it comes to data types and use of variables if we are writing codes without using ‘use strict’. None of the code example in this post has been written with ‘use strict’ option.

As a result, we can use a variable (without declaring it) and the JavaScript engine won’t have any issue with that. But it’s not the best practice, so it is not recommended, however, the point worth noting here is, it does not throw any error. This property makes JavaScript a loosely typed language.

Example 1:
x = 10;
console.log(x);        // prints 10

This code will run without any error. Behind the scenes, what JavaScript does is, it treats the same block of code as follows:

Example 2:
var x;
x = 10;
console.log(x);        // prints 10

var is a JavaScript keyword which is used to declare a variable. In the ES6 version of JavaScript, we have let and const keywords for declaring variables, but for now, let’s stick to the basics.

This property of JavaScript of creating/declaring the variable implicitly, whenever it finds a new identifier, is called variable hoisting.

Example 3:
1. var local = 'Local';
2. (function foo() {
3.   if (local === undefined) {
4.      var local = 'now it is Local';
5.        console.log(local);
6.    } else {
7.        console.log('Is', local, 'actually global?');
8.    }
9. })();

Prints: now it is Local

Open in jsfiddle

In the above code:

  • Line 1: we declared a global variable.
  • Line 2: we created a function foo, which is an immediately invoked function, i.e. it will be executed as soon as its declaration is over.
  • Line 3: it will be true. As soon as the execution enters the function foo’s scope, it will see the variable local’s declaration due to variable hoisting (see example 1 and 2)

Variable hoisting is restricted to the current scope.

Let’s come to the point and discuss data types. A JavaScript variable name can start with any character or an underscore ( _ ) or a dollar sign ( $ ). Any keyword of JavaScript or any identifier cannot start with any other special character except these two.

There are five primitive data types in JavaScript:

  • string
  • number
  • boolean
  • null
  • undefined

String and string are not the same, similarly Number and number, and boolean and Boolean are not the same. There are no data types based on types of numbers, i.e. floating point numbers and integers. Both of them are number in JavaScript.

While string, number, and boolean work as expected, null and undefined don’t. Click here to read more on undefined versus null.

Consider following examples, arithmetic operations on primitive data types.

1. 1 + 2 + '3'          // gives 33
2. '1' + 2              // gives 12
3. 1 + 2 - '3'          // gives 0
4. '1' - 2              // gives -1
5. 2 * '3'              // gives 6

In an expression, if there is a plus (+) symbol, everything is converted to string from the point where the first string is encountered (see 1 & 2). But when used with other operations like subtraction, multiplication, and so on, these strings are converted into numbers. These conditional conversions are referred to as automatic type conversion or type coercion. Since the plus (+) symbol is also used for string concatenation, coercion of number into a string is observed.

The JavaScript function parseInt (string, base) coverts a string into a number.

var x = '123';
typeof x;                  // prints "string"
var y = parseInt (x, 10);
typeof y;                  // prints "number"

In addition, parseInt discards everything after it encounters something which cannot be converted to a number.

var x = '123x456';
var y = parseInt (x, 10);
console.log (y);            // prints 123

Falsy Values

!undefined                  // true
!null                       // true
!''                         // true
!0                          // true
!false                      // true
!NaN                        // true

When negated, these six values gives results in truth value. These six values are referred to as falsy values in JavaScript.

As JavaScript is loosely typed language, we do not need to create variables with a data type (that’s why the keyword var). So the question is, how does typeof operator find out whether a value is a string or a number? Out of 64 bits (8 bytes), first 10 bits are reserved and they indicate based on certain conditions (will discuss later), if the value is a string or a number.

Let’s look at some more [confusing, perhaps] expressions and their outputs.

1.  typeof Infinity;                       // "number"
2.  typeof inifinity;                      // undefined [see the small i]

// AO represents arithmetic operation
3.  Infinity (AO) Infinity = Infinity
4.  Infinity (AO) NaN = NaN
5.  Infinity (AO) <any number> = Infinity
6.  NaN (AO) NaN = NaN
7.  NaN (AO) <any number> = NaN
8.  undefined (AO) NaN = NaN
9.  null +/- <any number> = <null becaomes 0>
10. null *// <any number> = <null becomes 0>
11. <any number> / null = Infinity
12. typeof NaN;                            // "number"
13. NaN + 'a' = 'NaNa'
14. 'a' + NaN = 'aNaN'
15. 1 == '1'                               // true [type coercion]
16. 1 === '1'                              // false
17. typeof undefined === undefined         // false
18. typeof undefined ? 1 : 0;              // 1
19. undefined ? 1 : 0;                     // 0

Using double equals while comparing two value involves type coercion and it might give an undesired result (see 15). That is why it is recommended to use triple equals while comparing two values.