Common JavaScript Data Types with Examples

In JavaScript data types are divided into two basic categories, one is primitive data type and other one is compound data type.

 

Primitive data types:

Primitive data type are mainly three types:

  • Boolean

Example: – true or false (1 or 0).

  • Numbers

Example: – 424, 42.25

  • Strings

Example: – “this is string text”

There are also two primitive data type, which are null and undefined.

Null — if we declare a variable and define the value as “null”, or we want value absolutely nothing in this variable, but we don’t want the variable to be as an undefined.

Undefined — when declare a variable but don’t assign any value in this variable then the value is undefined. When we attempt to call / use this variable it will return “undefined”.

 

Compound data type:

Compound data are made up with two or more primitive data types. Such as 2 + 2 or 2 + “abs” (hear 2 and abs is two primitive data type that together is compound data type). Array and object are also in compound data types.

 

Here some example of JavaScript data types with possible combination:

var price1 = 44;  //number
var price2 = 44.00; //number (decimal)

Both are count as number data type

Var first_name1 = “Osman”; //string
output: “Osman”;

var first_name2 = 2 + “Osman”; //string
output: “2Osman”;  // JavaScript will treat as “2” + “Osman”;

var first_name3 = 2 + 4 + “Osman”; //string
output: “4Osman”;  // JavaScript treats 2 and 4 as numbers, until it reaches “Osman”.

var first_name4 = “Osman” + 2 + 4 ; //string
output: “Osman24”;  // because the first operand is a string, so JavaScript are treated all operands as strings.

 

We can use same variable as different data type dynamically, Like:

var sam;                  //undifined
var sam = 44;         //number
var sam = 44.22;   //number
var sam = “strin”;  //String

 

Declares / creates an array, variable are containing three value into a single variable.
var arr = [“abc”, “def”, “ghi”] //declare array with value
var arr = new array(“abc”, “def”, “ghi”) //another declare array with value
arr[0] = “abc”;
arr[1] = “def”;
arr[2] = “ghi”;

Above example are compound JavaScript data types.

1 thought on “Common JavaScript Data Types with Examples”

  1. Number data types in JavaScript are floating-point numbers, but they may or may not have a fractional component. If they don t have a decimal point or fractional component, they re treated as integers base-10 whole numbers in a range of 2

Comments are closed.