Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

Data Types in JavaScript

In this article, we look at the JavaScript Data Types. JavaScript is a loosely typed dynamic language. It is loosely typed because you will never specify a data type of a variable. It is a dynamic language because you can assign any value to any variable whenever you wish to. But it does not mean that JavaScript does not have data types. It is just that do not need to specify the data type, But the JavaScript interpreter interprets the data type of the variable and generates the executable code accordingly.

What is a Data Type ? Why it is required ?

The Type or the Data Type is an attribute of data that tells the compiler or interpreter how to interpret its value. Whether it is a number, string, Boolean, etc.The type of data defines the operations that we can do on that data .

Take a look at the following example. The code declares two numbers and adds them using the + operator. The JavaScript interpreter correctly identifies the data type as a number and runs the arithmetic addition on them.

                            
let num1=10
let num2=10
 
console.log(num1+num2)   //20               Numbers are added
                            
                            
                        

The following code is very similar to the code above. Here instead of adding two numbers, we add two strings using the + operator. Here interpreter correctly identifies that the data type as a string and hence joins them.

                            
let str1="Hello"
let str2="world"
console.log(str1+ str2)  //HelloWorld       Strings are joined
                            
                            
                        

How does the interpreter know when to perform the addition and when to join them?. By examining the data type. If both the variables are numbers then the interpreter adds them. If any one of them is a string, then it joins them.

The following examples add a string to a number. Since one of the operands is a string, the interpreter generates the code to join them.

                            
console.log(str1+num1)      //Hello10
console.log(num1+str1)      //10Hello
                            
                            
                        

Hence it is very important for the compiler or interpreter to identify the data type of the variable. Otherwise, it may end up joining numbers and adding strings etc.

JavaScript is loosely typed

JavaScript is loosely typed. You don’t have to specify the data type of a JavaScript variable when we declare it. JavaScript interpreter automatically infers the type of a variable when you assign some value to it.

This gives JavaScript a lot of flexibility while coding. But it also makes it difficult to identify bugs and remove them. This is where Languages like TypeScript are useful. You can refer to ourTypeScript Tutorial .

JavaScript creates fourScopes. They are Global Scope, Function Scope, Block Scope & Module Scope.

JavaScript is dynamically typed

JavaScript is a dynamically typed language. You can assign any value to a variable at any time. In the following example, we assign a string and then a number to the variable num.

                            
 let num                  // No value is given to num. It is of type undefined
 
 
 num="10"                 // now num is string
 console.log(num+num)     // 1010  strings are joined
  
  
 num=10                  // now num is number
 console.log(num+num)    //20  numbers are added
                            
                            
                        

JavaScript Data Types

Although we do not specify the Data Type of a variable, the JavaScript interpreter keeps track of the type of data. JavaScript supports 8 data types. 7 of them are primitive data types and the 8th one is Object Data Type.

Primitive Types

JavaScript supports 7 primitive types (or basic types) number, string, boolean, bigint, symbol, undefined, and null. All other data types are objects in JavaScript.

A primitive data type is a data type that is provided as the basic building block of a language. All other types are composed using primitive data types. For Example, the Object in JavaScript is not a primitive type because we compose an object using the primitive types and other objects

Primitive Types do not have any methods. All primitives are immutable.

String

We use the string data type to store textual data. The string value is enclosed in double-quotes (“) or single quotes (‘).

                            
let message="Hello World"  // Use a double quote 
let color='red'            // or a single quote 
let val="100"              //number stored as string. Anything inside the "" or '' is a string
 
 
                            
                            
                        

You can use a single quote inside a double quote or vice versa

                            
let message 
 
message="Hello 'World'"
console.log(message)  //Hello 'World'
 
message='Hello "World"'
                            
                            
                        

Or you can use the escape character \ to include a double quote (or single quote)

                            
message="Hello \"World\" ";
console.log(message) 
 
                            
                            
                        

Multiline string

The strings can span multiple lines in such cases the strings are surrounded by the backtick/backquote (`) character. Such Strings are called Template Strings or Template Literals.

                            
let sentence 
 
sentence = `Hello, welcome to the world of JavaScript Data Types,     
This is the example of muluti line string in JavaScript
use the backtick/backquote charater to enclose it`
 
 
console.log(sentence)
 
                            
                            
                        

Number

The number data type in JavaScript are 64-bit floating-point values and are used to represent integers and fractions. JavaScript also supports hexadecimal & decimal literals. It also supports the binary and octal literals introduced in ECMAScript 2015

                            
let decimal = 10; 
let hex = 0xa00d;       //hexadecimal number starts with 0x
let binary = 0b1010;    //binary number starts with 0b 
let octal = 0o633;      //octal number starts with 0o 
 
 
console.log(decimal)        //10
console.log(hex)            //40973
console.log(binary)         //10
console.log(octal)          //411
 
                            
                            
                        

Apart from the all numbers, It also contains three special values i.e. Not A Number or NaN, positive infinity and negative infinity.

Number Data type has a Limitation of Max Safe Integer & Min Safe Integer. If you want to use any integer beyond these numbers, then you can consider using BigInt

Boolean

The boolean type is a simple true/false value

                              
let isDone = false
let isOk = true
 
console.log(isDone)     //false
console.log(isOk)       //true   
 
 
                            
                            
                        

Bigint

bigint is the new introduction in JavaScript. This will provide a way to represent whole numbers larger than 2^53 – 1. You can get a bigint by calling the BigInt() function or by writing out a BigInt literal by adding an n to the end of any integer numeric literal as shown below.

                              
let big1 = BigInt(100); // the BigInt function
let big2 = 100n;        // a BigInt literal.  end with n 
 
 console.log(big1)      //100n
 console.log(big2)      //100n
 
                            
                            
                        

BigInt appears similar to Number Data Type. But they do have few important differences. To find out checkout BintInt Vs Number.

Null

The null in JavaScript is a special value & also a data type. The value null represents the intentional absence of any object value. It is one of JavaScript’s primitive values and is treated as falsy for boolean operations. The value of null is represented in JavaScript using the literal null.

                              
let a = null     
console.log(a)    // null
 
                            
                            
                        

Undefined

Undefinedis a special JavaScript value and also a data type. It is one of JavaScript’s primitive values and is treated as falsy for boolean operations.

The JavaScript creates the variable as of type undefined and assigns it a value of undefined if we do not assign any value to it. Hence undefined usually means the unintentional absence of any value.

                              
let a;
console.log(a)           //undefined
console.log(typeof (a))  //undefined
 
                            
                            
                        

JavaScript also has a global variable with the name undefined which has the value Undefined.

A variable of type undefined has can take only one value undefined

Symbol

The symbol is the new primitive type introduced in ES6 and represents the javaScript symbol primitive type. it represents unique tokens that may be used as keys for object properties. it is created by the global Symbol() function. Each time the Symbol() function is called, a new unique symbol is returned.