JAVASCRIPT DATA TYPES
A data type generally specifies that which type of data can be saved and operated within a program. It is a major concept in programming. In JavaScript, same variable can be used to hold various data types. JavaScript consists of two different data types to deal with various types of values:
- Primitive data type: It includes number, string, boolean, undefined null and symbol.
- Non-primitive data type: It has only one member i.e. the object.
Let's have a look at some variables with different datatypes:
var myVar = 100;
var a = true;
var b = null;
var c = undefined;
var d = "James";
Live Demo!
JAVASCRIPT NUMBERS
A JS variable can store any number assigned to it by the user. Any type of number can be stored in it. Let’s check an example:
const num1 = 4;
const num2 = 4.644;
const num3 = 4e5; // 4e5 Represents 4 * 10^5
A number type also includes + infinity, - infinity and NaN.
Example:
const x = 16/0;
document.write(x); // returns infinity
const y = -6/0;
document.write(y); // returns -infinity
//strings can't be divided by numbers
const z = "abc"/5;
document.write(z); // returns NaN
Live Demo!
JAVASCRIPT STRINGS
A string is a series of characters. Unlike numbers it is always written within quotes. Single and double quotes are generally similar, backticks are applied when you need to add expressions or variables in a string. Let's check an example on how we can deal with string variables in JS:
const x = "John";
const y = "Doe";
const result = `Welcome! ${x} ${y}`;
Live Demo!
JAVASCRIPT BOOLEAN
Only two values can be stored in this type of variable, i.e. True or False. To avoid confusing it with strings, it is written without quotes.
const first = false;
const second = true;
Live Demo!
JAVASCRIPT ARRAYS
Arrays are used to store more than one value in a single variable. The syntax is like an array elements are written within square brackets and different values are separated by commas.
var colors = ["Pink" , "Brown", "Golden", "Purple"];
var cities = ["Tokyo", "Bruxelles", "Los Angeles", "Chicago"];
document.write(colors[0]); // Output: Pink
document.write(cities[3]); // Output : Chicago
Live Demo!
JAVASCRIPT OBJECT
JS objects are written within curly brackets.
Example:
var person = {
firstName:"John",
lastName:"Doe",
age:60,
city:"Bruxelles",
country: "Belgium"
};
Live Demo!
THE TYPEOF OPERATOR
The typeof
operator can be used to determine what type of data a variable contains.
const name = "Ghost";
document.write(typeof(name)); // returns "string"
const number = 61;
document.write(typeof(number)); //returns "number"
const flag = true;
document.write(typeof(flag)); //returns "Boolean"
const a = null;
document.write(typeof(a)); // returns "object"
Live Demo!