JavaScript

Java Script Data types

Data types denote the type of data that can be stored in a program. They are important in a program because to perform operations on variables one should know what data types they are. For example, an addition cannot be performed on a string variable and a numeric variable. They can be concatenated. The typeof operator in JavaScript helps in finding the data type of the variable. By getting this information the program can decide what operations has to be performed on the variables. Thus, data types play a major role in any sort of coding including JavaScript coding.

Basic data types where one value at a time can be stored.
Numeric data types: These are numbers that can store either integer numbers like 12 or floating-point numbers like 12.3. The numbers can be positive or negative. In some cases, for example if a string is divided by number, then there will be an error as it is not a number. It is shown as NaN. Also, anything divided by zero is shown as Infinity.
String data types: They denote text data and can be either shown in single or double quotes. e.g. ‘How are you’ or “How are you.”
Boolean: It has the values true or false. Stores yes or no values.
Null: It means the value is unknown
Undefined: It means the value is not assigned
Symbol(): It creates a new unique value every time it is called
Bigint: The whole numbers larger than 253 – 1
Data types that have a collection of data
Object data type: It is a collection of properties. Each property is key-value pair.
Array data type: Stores multiple values in single variable.

Examples:
• Number: x=10 or x=10.2
• String: str=” This is a string”
• Boolean: 10 > 5
• Null: str=null
• Undefined: let x
• Symbol: let str=Symbol(“test”)
• Object: str= {EmpNo:1, EmpName:” Peter”}
• Array: str=[‘a’,’b’,’c’]

<!DOCTYPE html>

<html lang=”en” xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta charset=”utf-8″ />
<title>JS Datatypes</title>
</head>
<body>

<script>
//number
x = 10
document.write(x + “<br>”) //Answer:10

//string
str = “This is string”
document.write(str + “<br>”) //Answer: This is string

//boolean
p = 5, q = 10
document.write((p == q) + “<br>”) //Answer: false

//array
str = [‘a’, ‘b’, ‘c’]
document.write(str + “<br>”) //Answer:a,b,c
document.write(str[0] + “<br>”) //Answer:a

//object
str1 = {
Name: “Peter”,
country: “USA”
}
document.write(str1.Name + “<br>”) //Answer:Peter
document.write(str1[“Name”] + “<br>”) //Answer:Peter

//Symbol is used to identify object properties
//Both these symbols are not equal
let str2 = Symbol(“test”)
let str3 = Symbol(“test”)
document.write(str2 == str3) //Answer:false

//null means unknown value e.g. str4 = null

//Variable that is not initialized is undefined e.g. let x

</script>
</body>
</html>

Output:

10
This is string
false
a,b,c
a
Peter
Peter
false