What are data types in JavaScript
Data types in JavaScript are used to specify the type of value or data a variable can store or hold and determine the operations that can be performed on it.
How to know the data type of variable?
In Javascript, we can know the data type of a variable using the ‘typeof’ operator.
The ‘typeof’ operator in Javascript is used to check the data type of variable
var
name='Code';
var
age=13;
console.log(typeof(name)); // string
console.log(typeof(age)); // number
What are different Data Types in JavaScript?
Primitive Data Type
- In JavaScript. It can hold only a single value at a time.
- It includes String, Number, Boolean, Undefined, and Null.
- These data types are immutable i.e. they can’t be changed or altered.
var
a="Hello";
console.log(a[2]); // l
a[2]='L'
console.log([a]); // Hello
Types of primitive data types
String
A string is a data type that is used to store or hold sequence characters enclosed in either single or double quotes. It is used to store data in the form of text.
let
name='Vandana';
let
msg="Hello";
console.log(msg,name); // Hello Vandana
console.log(typeof(name)); // string
Number
It represents any one integer, floating-point or exponential value.
let
a = 123
let
b = 1.23
console.log(a); // 123
console.log(b); // 1.23
Boolean
It returns either true or false.
var
x=false;
console.log(typeof
x);
Undefined
A variable that is declared but not initialized with any value.
var
a;
console.log(typeof(a)); // undefined
Null
It represents a null value which means no value. A variable is initialized with null.
var
b=null;
console.log(b); // null
console.log(typeof
b); // object
Non-primitive/Reference Data Types
These are the data types derived from primitive data types. It is used to store or hold multiple values at a time.
It includes arrays, objects, and functions.
These data types are mutable, i.e. they can be altered or changed.
let
arr=[1,2,3];
console.log(arr); // [1,2,3]
arr.push(5);
console.log(arr); // [1,2,3,5]
console.log(typeof
arr); // object
Types of Non-primitive data types
Object
Elements are stored as a key-value pair.
let
obj={ name:'Vandana', age:21};
console.log(obj); // { name:'Vandana', age:21}
console.log(typeof
obj); // object
// access value of object
console,log(obj["name"]); // Vandana
console,log(obj.name); // Vandana
Array
It is used to store multiple elements.
let
arr=[1,2,true,'Sam'];
console.log(arr); // [1,2, true,'Sam']
// access value from array
console.log(arr[0]); // 1
Function
A function is a block of code enclosed in curly braces used to perform a specific task.
function
fun()
{}
console.log(typeof
fun); // function