JavaScript: Data Types and Type Conversion

JavaScript variables are dynamically typed. That means variables do not have any fixed type, we don’t have to define/set type explicitly.

The type of the variable can change during execution. For example, a variable can contain a string and then later it can contain a number, and later some other data.

Primitive Data Types

Primitive data types represent a single value in memory.

Typetypeof ResponseObject RepresentDescriptionExamples
UndefinedundefinedThis is the default value in JS.
Used when a variable is not defined
and/or value is not assigned
NullobjectRepresents null value.
BooleanbooleanBooleanBoolean values- true or falsetrue
false
NumbernumberNumberRepresents any number,
both integers and floating numbers.
1
5
100
3.1416
9.99
BigIntbigintBigIntRepresents large numbers.
Provide high precision over Number type
9007199254741091n
SymbolsymbolSymbolRepresent unique and immutable valueSymbol('bigboxcode')
StringstringStringUsed for string representation"hello box"
'BigBoxCode tutorials'

Non-Primitive Data Types

Non-Primitive data types represent a group/collection of data.

Typetypeof ResponseDescriptionExamples
ObjectobjectRepresents a group of key/value combinations{a: 100, b: "bigboxcode"}
ArrayarrayContainers a group of items[1, 2, 3, 4, 5]
FunctionfunctionRepresents a functionfunction bigBoxFunc(){}

typeof Operator

the typeof operator is an important element when we deal with types in JavaScript. typeof operator returns a string, that represents the type of the provided operand.

Check the examples below-

console.log("Type of undefined: " + typeof undefined);
console.log("Type of a variable that is not defined yet: " + typeof myUndefinedVar);
console.log("Type of null: " + typeof null);
console.log("Type of true: " + typeof true);
console.log("Type of 100: " + typeof 100);
console.log("Type of 100n: " + typeof 100n);
console.log("Type of 'Sample text here': " + typeof 'Sample text here');
console.log("Type of Symbol('bigboxcode'): " + typeof Symbol('bigboxcode'));

console.log("Type of {a: 100, b: \"bigboxcode\"}: " + typeof {a: 100, b: "bigboxcode"});
console.log("Type of [1, 2, 3, 4, 5]: " + typeof [1, 2, 3, 4, 5]);
console.log("Type of function bigBoxFunc(){}: " + typeof function bigBoxFunc(){});

Output:

Type of undefined: undefined
Type of a variable that is not defined yet: undefined
Type of null: object
Type of true: boolean
Type of 100: number
Type of 100n: bigint
Type of 'Sample text here': string
Type of Symbol('bigboxcode'): symbol

Type of {a: 100, b: "bigboxcode"}: object
Type of [1, 2, 3, 4, 5]: object
Type of function bigBoxFunc(){}: function

WARNING

In the output above, the typeof null is object. This is weird and actually a very old bug in JavaScript.

This bug is decided to not be fixed, as this would break existing code and impact a lot of applications. As lots of applications already use typeof null and compare that to “object“.

Dynamic Typing

JavaScript variables are dynamically typed. We do not specify the type of a variable at any point in the code.

The same variable can have different types of data at different places. We just have to assign a new value to the variable, and the type of the variable changes automatically.

Check the code below-

// Assign a boolean
let bigBoxVar = true;

console.log("Type of bigBoxVar: " + typeof(bigBoxVar));

// Assign a number
bigBoxVar = 100;

console.log("Type of bigBoxVar: " + typeof(bigBoxVar));

// Assign a BigInt
bigBoxVar = 100n;

console.log("Type of bigBoxVar: " + typeof(bigBoxVar));

// Assign a string
bigBoxVar = 'Sample text here';

console.log("Type of bigBoxVar: " + typeof(bigBoxVar));

Output:

Type of bigBoxVar: boolean
Type of bigBoxVar: number
Type of bigBoxVar: bigint
bigBoxVar: string

Here we are assigning different types of data to the same variable in each step, and the type of the variable changes dynamically.

Data Types

Let’s discuss each type one by one-

Undefined

undefined is the default value of a variable. When a variable is declared, but not defined and no value is assigned to it, at that the value is undefined.

Check the examples below-

If we just declare a variable, and then check its value and type, both will be undefined

// Just declare the variable
let bigBoxVar;

// Check the value of the variable here
console.log("Value of bigBoxCode: " + bigBoxVar);

// Check the type
console.log("Type of bigBoxCode: " + typeof bigBoxCode);

Output:

Value of bigBoxCode: undefined
Type of bigBoxCode: undefined

If we check the type of a variable that is non-existing, which is not declared yet, then the type is undefined

// Check the vlaue of a variable
// that is not declared yet
console.log("Type of someVariableThatIsNotDeclaredYet: " + typeof someVariableThatIsNotDeclaredYet);

Output:

Type of someVariableThatIsNotDeclaredYet: undefined

Null

null is used to indicate that, a variable has some blank value. null in JavaScript is a single value, which is null. Check the code below-

var bigBoxNull = null;

console.log("Value of bigBoxNull: " + bigBoxNull);

console.log("Type of bigBoxNull: " + typeof bigBoxNull);

console.log("Type of null: " + typeof null);

Output:

Value of bigBoxNull: null
Type of bigBoxNull: object
Type of null: object

As we have already seen in the section for typeof, the type of null returned in JavaScript is “object”.

Compare with null:

Let’s compare null with other values-

Comparison ExpressionResultNotes
null == undefinedtrue
null === undefinedfalse
null == 0false
+null === 0trueWhen “+” sign is added in front of null, then JavaScript tries to convert it to an integer, which translates to Zero(0)-
console.log(+null); // outputs 0
-null === 0trueWhen “” sign is added in front of null, then JavaScript tries to convert it to an integer, which translates to negative Zero(-0)-
console.log(-null); // outputs -0
null == falsefalse

NOTE

  • If we compare null == undefined, it returns true.

Boolean

boolean type has only 2 values true and false.

let bigBoxPositive = true;
let bigBoxNegative = false;

console.log("Value of bigBoxPositive is: " + bigBoxPositive);
console.log("Type of bigBoxPositive is: " + typeof bigBoxPositive);

console.log("Value of bigBoxNegative is: " + bigBoxNegative);
console.log("Type of bigBoxNegative is: " + typeof bigBoxNegative);

Output:

Value of bigBoxPositive is: true
Type of bigBoxPositive is: boolean

Value of bigBoxNegative is: false
Type of bigBoxNegative is: boolean

Convert to boolean:

We can convert other type values to boolean using Boolean(). Let’s see what we get when we pass different data types to Boolean() function-

Data TypeValueValue after converting to a boolean
Boolean(providedValue)
Note
undefinedundefinedfalse
nullnullfalse
booleantruetrue
booleanfalsefalse
number0false
number-1true
number100true
number100.88true
bigint100ntrue
stringfalseempty string
string‘Sample text here’true
symbolSymbol(”)true
symbolSymbol(‘bigboxcode’)true
object{a: 100, b: “bigboxcode”}true
object{}trueempty object
array[1, 2, 3, 4, 5]true
array[0]true
array[]trueempty array
functionfunction bigBoxFunc(){}true

NOTE

  • In the code above, most of the elements returned true when converted to true.
    Only the following returned false-
    • undefined
    • null
    • 0
    • ” (empty string)

Number

Number type is used to represent both integer and floating numbers.

let bigBoxInt = 100;
let bigBoxNegativeInt = -11;
let bigBoxFloat = 99.99;

console.log("Type of " + bigBoxInt + " is: " + typeof bigBoxInt);
console.log("Type of " + bigBoxNegativeInt + " is: " + typeof bigBoxNegativeInt);
console.log("Type of " + bigBoxFloat + " is: " + typeof bigBoxFloat);

Output:

Type of 100 is: number
Type of -11 is: number
Type of 99.99 is: number

Let’s check the maximum and minimum values that can be stored in a JavaScript number-

console.log("Max number value: " + Number.MAX_VALUE);
console.log("Min number value: " + Number.MIN_VALUE);

console.log("Max safe integer: " + Number.MAX_SAFE_INTEGER);
console.log("Min safe integer: " + Number.MIN_SAFE_INTEGER);

Output:

Max number value: 1.7976931348623157e+308
Min number value: 5e-324

Max safe integer: 9007199254740991
Min safe integer: -9007199254740991

Convert to number:

We can convert other type values to numbers using Number(). Here is a list of what we get, when we convert values to numbers-

Data TypeValueValue after converting to number
Number(providedValue)
Note
undefinedundefinedNaN
nullnull0
booleantrue1
booleanfalse0
number00
number-1-1
number100100
number100.88100.88
bigint100n100
string0empty string
string‘Sample text here’NaN
symbolSymbol(”)Uncaught TypeError: Cannot convert a Symbol value to a number
symbolSymbol(‘bigboxcode’)Uncaught TypeError: Cannot convert a Symbol value to a number
object{a: 100, b: “bigboxcode”}NaN
object{}NaNempty object
array[1, 2, 3, 4, 5]NaN
array[0]0
array[]0empty array
functionfunction bigBoxFunc(){}NaN

NOTE

  • NaN means “Not a Number” which indicates, that this is not a number, as could not be converted to a number.
  • If we compare NaN with the same value, we get false-
    console.log(NaN == NaN); // output: false

Parse any value to Integer:

We can take any value in JavaScript and parse it to retrieve an integer, by using parseInt() function-

Data TypeValueParse value to Integer using
parseInt(providedValue)
Note
string’99’99
string‘9abc’9
string‘9abc8’9
string‘98.7654’98
string‘abc’NaN
string‘abc986’NaN
stringNaN
string‘ 9876’9876
string90.87690
nullnullNaN
undefinedundefinedNaN
number0.00000000770.000000007 is represented as 7e-9 :
console.log(0.000000007); // output: 7e-9
console.log(parseInt(7e-9)); // output: 7

NOTE

  • parseInt(0.000000007) gives an unexpected output of 7. Check the explanation above in the note. Be careful while using the parseInt() function about these edge case.

BigInt

As we have already seen the maximum value of a safe integer is 2^53 – 1 (=9_007_199_254_740_991). To handle numbers bigger than that we can use BitInt.

A BigInt looks like a number value, but there is a “n” suffix after the number, to indicate a BigInt.

let myInt = 100;
let bigBoxBigInt = 9999n;

console.log("Value of bigBoxBigInt : ", bigBoxBigInt);
console.log("Type of bigBoxBigInt is: " + typeof bigBoxBigInt);

console.log("Value of " + myInt + " after converted to BigInt:", BigInt(myInt));
console.log("Type of BigInt(" + myInt + ") is:", typeof BigInt(myInt));

Output:

Value of bigBoxBigInt :  9999n
Type of bigBoxBigInt is: bigint

Value of 100 after converted to BigInt: 100n
Type of BigInt(100) is: bigint

Let’s check the problem when a number exceeds the max number value-

let bigBoxInt = Number.MAX_SAFE_INTEGER;

console.log("Value of bigBoxInt = " + bigBoxInt);

bigBoxInt++;
console.log("Value of bigBoxInt = " + bigBoxInt);

bigBoxInt++;
console.log("Value of bigBoxInt = " + bigBoxInt);

bigBoxInt++;
console.log("Value of bigBoxInt = " + bigBoxInt);


bigBoxInt += 2;
console.log("Value of bigBoxInt (after +2) = " + bigBoxInt);

bigBoxInt += 1;
console.log("Value of bigBoxInt = " + bigBoxInt);

Output:

Value of bigBoxInt = 9007199254740991
VM3738 Script snippet #22:6 Value of bigBoxInt = 9007199254740992
VM3738 Script snippet #22:9 Value of bigBoxInt = 9007199254740992
VM3738 Script snippet #22:12 Value of bigBoxInt = 9007199254740992
VM3738 Script snippet #22:16 Value of bigBoxInt (after +2) = 9007199254740994
VM3738 Script snippet #22:20 Value of bigBoxInt = 9007199254740996

We can see, that the number becomes unpredictable after exceeding the range.

Let’s see how BigInt solves the issue-

let bigBoxInt = BigInt(Number.MAX_SAFE_INTEGER);

console.log("Value of bigBoxInt = " + bigBoxInt);

bigBoxInt++;
console.log("Value of bigBoxInt = " + bigBoxInt);

bigBoxInt++;
console.log("Value of bigBoxInt = " + bigBoxInt);

bigBoxInt++;
console.log("Value of bigBoxInt = " + bigBoxInt);


bigBoxInt += 2n;
console.log("Value of bigBoxInt (after +2) = " + bigBoxInt);

bigBoxInt += 1n;
console.log("Value of bigBoxInt = " + bigBoxInt);

Output:

Value of bigBoxInt = 9007199254740991
Value of bigBoxInt = 9007199254740992
Value of bigBoxInt = 9007199254740993
Value of bigBoxInt = 9007199254740994
Value of bigBoxInt (after +2) = 9007199254740996
Value of bigBoxInt = 9007199254740997

NOTE

  • If we try to perform any operation where we mix BigInt with a number, like below-
    100n + 20
    then we get the following error-
    Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions

Convert to number:

We can convert other type values to bigint using BigInt(). Here is a list of what we get, when we convert values to numbers-

Data TypeValueValue after converting to bigint
BigInt(providedValue)
Note
undefinedundefinedUncaught TypeError: Cannot convert undefined to a BigInt
nullnullUncaught TypeError: Cannot convert null to a BigInt
booleantrue1
booleanfalse0
number00
number-1-1
number100100
number100.88Uncaught RangeError: The number 100.88 cannot be converted to a BigInt because it is not an integer
bigint100n100
string0
string‘Sample text here’Uncaught SyntaxError: Cannot convert Sample text here to a BigInt
symbolSymbol(”)Uncaught TypeError: Cannot convert Symbol() to a BigInt
symbolSymbol(‘bigboxcode’)Uncaught TypeError: Cannot convert Symbol() to a BigInt
object{a: 100, b: “bigboxcode”}Uncaught SyntaxError: Cannot convert [object Object] to a BigInt
object{}Uncaught SyntaxError: Cannot convert [object Object] to a BigInt
array[1, 2, 3, 4, 5]Script snippet #22:24 Uncaught SyntaxError: Cannot convert 1,2,3,4,5 to a BigInt
array[0]0
array[]0
functionfunction bigBoxFunc(){}Uncaught SyntaxError: Cannot convert function bigBoxFunc(){} to a BigInt

Symbol

We can create a symbol by using the Symbol() function. A string can be passed to the function. Symbols are unique, as the Symbol() function generates a new Symbol each time. Check the code below

console.log("Value of Symbol() is: ", Symbol());
console.log("Value of Symbol('') is: ", Symbol(''));
console.log("Value of Symbol('My Big Box of Code') is: ", Symbol('My Big Box of Code'));

Output:

Value of Symbol() is:  Symbol()
Value of Symbol('') is:  Symbol()
Value of Symbol('My Big Box of Code') is:  Symbol(My Big Box of Code)

Compare with symbol:

Each time the Symbol function is called, it returns a unique Symbol value-

Comparison ExpressionResultNotes
Symbol() == Symbol()false
Symbol(“bigboxcode”) == Symbol(“bigboxcode”)false

String

Strings are a sequence of characters. If there is no character, then it is called an empty string. We can use single(‘) or double(“) quotation to wrap a string-

let bigBoxEmptyString = '';
let bigBoxStrWithSingleQuote = 'This is my string with single quote';
let bigBoxStrWithDoubleQuote = "This is my string with double quote";

console.log("Value of bigBoxEmptyString is: " + bigBoxEmptyString);
console.log("Value of bigBoxStrWithSingleQuote is: " + bigBoxStrWithSingleQuote);
console.log("Value of bigBoxStrWithDoubleQuote is: " + bigBoxStrWithDoubleQuote);

Output:

Value of bigBoxEmptyString is: 
Value of bigBoxStrWithSingleQuote is: This is my string with single quote
Value of bigBoxStrWithDoubleQuote is: This is my string with double quote

Convert to string:

We can convert other type values to string using String(). Here is a list of what we get, when we convert values to numbers-

Data TypeValueValue after converting to string
String(providedValue)
Notes
undefinedundefined‘undefined’
nullnull‘null’
booleantrue‘true’
booleanfalse‘false’
number0‘0’
number-1‘-1’
number100‘100’
number100.88‘100.88’
bigint100n‘100’
string
string‘Sample text here’‘Sample text here’
symbolSymbol(”)‘Symbol()’
symbolSymbol(‘bigboxcode’)‘Symbol(bigboxcode)’
object{a: 100, b: “bigboxcode”}‘[object Object]’
object{}‘[object Object]’
array[1, 2, 3, 4, 5]‘1,2,3,4,5’
array[0]‘0’
array[]
functionfunction bigBoxFunc(){}‘function bigBoxFunc(){}’

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.