Data types in JavaScript

Data types in JavaScript

Guide on JavaScript data types with examples

What is a data type?

data type, in programming, is a classification that specifies which type of value a variable has and what type of mathematical, relational or logical operations can be applied to it without causing an error.

What are the data types available in JavaScript?

  1. Primitive data type

  2. Non-primitive (reference) data type

  • JavaScript Primitive data types:

Primitive data types are immutable meaning not able to be changed and these are the primitive types in JavaScript:

  1. Number
  2. String
  3. Boolean
  4. Undefined
  5. Null
  • Number

Number data type can written with or without a decimal point. It can be used to represent floating-point numbers, integers etc. Many operations can be done with numbers e.g. multiplication *, division /, addition +, subtraction -, and so on.

Example:

var num1 = 10;
var num2 = 15.5;
  • String

String in JavaScript represents some textual data. Values of type string are enclosed in quotation marks. It must be enclosed in single or double quotation marks.

Example:

let greeting = 'Hi';
let wish = "Good Morning"
  • Boolean Boolean datatype variable holds only one value, which can be true or false.

Example:

let a = true;
let b = false;
console.log(typeof(b)); // boolean
  • Undefined

Undefined value is assigned to newly created variable that isn’t assigned with any value.

Example:

var state; //variable declared but not defined.
console.log(state);
  • Null

Null represents a reference to a non-existent entity or some invalid address in memory.

Example:

let obj = null;
console.log(typeof(obj)); // object
  • JavaScript non-primitive types:

    Non-primitive data types can hold collections of values and more complex entities.
  1. Object
  2. Array
  3. Date
  • Object

objects in JavaScript can be seen as a collection of properties. Objects are often represented with curly braces{}. The properties are stored in key value pairs. Property values can be of any type, including objects.

Example:

var details= {
name: "Vignesh", 
age: 25, 
career: 'Developer', 
hobby: "blogging"};
  • Array

An array is used to store multiple values in a single variable. Each elements in array has a numeric position, known as its index. Using index, we can access all elements present in an array.

Example:

let colors = ["Red", "Yellow", "Green", "Orange"];
console.log(colors[0]) // Red
  • Date Date objects are created with the new Date() constructor.

Example:

const d = new Date(2018, 10, 24, 10, 33, 30);
console.log(d) // 2018-11-24T05:03:30.000Z