Basic JavaScript: Data Types
Data Types are important concepts in any language. They define the type of data a variable can hold
Data Types are important concepts in any language. They define the type of data a variable can hold.
In JavaScript, we have various data types like:
-
Number
-
String
-
Boolean
-
Arrays
-
Object
-
null
-
undefined
The function can be used to see the data type of the variable.
Number
This data type can hold integers from -Infinity to +Infinity including floating-point numbers.
1var a = 2; 2console.log(typeof a); // "number" 3var b = 3.56; 4console.log(typeof b); // "number"
String
A String is a sequence of characters. String are denoted using " "
or ' '
1var name = "Developer"; 2console.log(typeof name); // string 3 4var letter = "A"; 5console.log(typeof letter); // string
Boolean
A boolean is a true
or false
value.
1var isRaining = true; 2console.log(typeof raining); // boolean 3 4var isLoggedIn = false; 5console.log(typeof isLoggedIn); // boolean
Arrays
Arrays are a collection of similar data types. They are denoted using square brackets [ ]
1var numbers = [1, 2, 3, 4, 5]; // array of numbers 2var colors = ["red", "green", "blue"]; // array of strings
But, in JavaScript, an array can hold various data types too.
1var numbersAndColors = [1, "blue", 2, "red", 3];
You can access the value of the array by its index. Every array has an index that starts with 0.
1console.log(colors[0]); //red 2console.log(colors[1]); //green 3 4console.log(numbers[0]); // 1 5console.log(numbers[1]); // 2
Object
In JavaScript, an object is a collection of key: value pairs. They are denoted using the {}
brackets
1var obj = { 2 name: "Shubham", 3 age: 20, 4 role: "Frontend Developer", 5 isStudent: true, 6 hobbies:['coding","reading","eating"] 7};
Each object’s key: value pair must be separated by a comma.
The data of an object can be accessed by the following syntax.
Syntax:
-
ObjectName.keyName
= if the key is a String. -
ObjectName[keyName]
= if the key is a Number
1var obj = { 2 name: "Shubham", 3 age: 20, 4 role: "Frontend Developer", 5 100: "Hundred", 6}; 7 8console.log(obj.name); // "Shubham" 9console.log(obj.age); // 20 10console.log(obj[100]); // "Hundred"
null
A null data type means that value doesn’t exist in memory.
undefined
An undefined type means that value exists but is not yet defined.
1var a;console.log(a); // undefined
These are the basics data types present in JavaScript.
Next, we will learn about JavaScript Operators.