JavaScript Data Types

Data types are the classifications of data that JavaScript can handle, such as numbers, strings, booleans, etc. Data types determine how the data can be stored, manipulated, and evaluated in a program. JavaScript has two main categories of data types: primitive and non-primitive.

Primitive Data Types

Primitive data types are the basic types of data that are immutable, meaning that their values cannot be changed. JavaScript has six primitive data types:

Number:

This type represents numeric values, such as integers, decimals, and fractions. Numbers can be written with or without decimals, and can also use exponential notation. For example:

Javascript
                        
// Numbers with decimals
let x = 3.14;
let y = -2.5;

// Numbers without decimals
let a = 42;
let b = 0;

// Numbers with exponential notation
let c = 1.23e5; // 123000
let d = 4.56e-3; // 0.00456

String:

This type represents textual data, such as words, sentences, and symbols. Strings are written with quotes, either single or double. You can use quotes inside a string, as long as they don't match the quotes surrounding the string. For example:

Javascript
                        
// Strings with double quotes
let name = "Alice";
let greeting = "Hello, world!";

// Strings with single quotes
let color = 'red';
let animal = 'cat';

// Strings with quotes inside
let question = "What's your name?";
let answer = 'He said "yes"';

Boolean:

This type represents logical values, either true or false. Booleans are often used for conditional statements, such as if-else or switch-case. For example:

Javascript
                        
// Booleans
let isRaining = true;
let isSunny = false;

// Conditional statements
if (isRaining) {
  console.log("Bring an umbrella");
} else {
  console.log("Wear sunglasses");
}

Null:

This type represents the intentional absence of any value. Null is often used to indicate that a variable has no value assigned, or that an object has no valid reference. For example:

Javascript
                        
// Null
let empty = null;
console.log(empty); // null

Undefined:

This type represents the unintentional absence of any value. Undefined is the default value of a variable that has not been assigned, or a function that has no return value, or a property that does not exist in an object. For example:

Javascript
                        
// Undefined
let unknown;
console.log(unknown); // undefined

function doNothing() {
  // no return statement
}
console.log(doNothing()); // undefined

let person = {name: "Bob"};
console.log(person.age); // undefined

Symbol:

This type represents unique and immutable identifiers that can be used as keys for object properties. Symbols are created by calling the Symbol() function, which takes an optional description as an argument. For example:

Javascript
                        
// Symbol
let sym1 = Symbol(); // no description
let sym2 = Symbol("foo"); // description is "foo"
let sym3 = Symbol("foo"); // description is also "foo"

console.log(sym2 === sym3); // false, symbols are unique
console.log(sym2.toString()); // "Symbol(foo)", the description is shown

You can check the type of a primitive value by using the typeof operator, which returns a string indicating the type. For example:

Javascript
                        
// typeof operator
console.log(typeof 3.14); // "number"
console.log(typeof "Hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof null); // "object" (this is a bug in JavaScript)
console.log(typeof undefined); // "undefined"
console.log(typeof Symbol("foo")); // "symbol"

Non-Primitive Data Types

Non-primitive data types are the complex types of data that are mutable, meaning that their values can be changed. JavaScript has one non-primitive data type: object.

Object:

This type represents a collection of properties and methods that are organized by key-value pairs. An object can contain any type of data, including other objects, arrays, functions, etc. Objects are created by using curly braces, with a list of properties and methods separated by commas. For example:

Javascript
                        
// Object
let person = {
  name: "Alice", // property with a string value
  age: 25, // property with a number value
  hobbies: ["reading", "writing", "coding"], // property with an array value
  greet: function() { // method with a function value
    console.log("Hello, I'm " + this.name);
  }
};

// Accessing properties and methods
console.log(person.name); // "Alice"
console.log(person.hobbies[1]); // "writing"
person.greet(); // "Hello, I'm Alice"

Objects are very versatile and powerful data structures that can be used to model real-world entities, such as people, animals, cars, etc. Objects can also be used to implement other abstract data types, such as arrays, sets, maps, etc.

You can check the type of an object by using the typeof operator, which returns "object" for any object. However, this is not very useful if you want to distinguish between different kinds of objects, such as arrays, functions, dates, etc. For that, you can use the instanceof operator, which returns true if an object is an instance of a specific constructor function. For example:

Javascript
                        
// typeof operator
console.log(typeof person); // "object"
console.log(typeof [1, 2, 3]); // "object"
console.log(typeof function() {}); // "object"

// instanceof operator
console.log(person instanceof Object); // true
console.log([1, 2, 3] instanceof Array); // true
console.log(function() {} instanceof Function); // true

Type Conversion

Type conversion is the process of changing the type of a value from one type to another. JavaScript performs type conversion automatically when an operation involves values of different types, such as adding a number and a string. This is called implicit type conversion, and it can sometimes lead to unexpected results or errors. For example:

Javascript
                        
// Implicit type conversion
console.log(1 + "2"); // "12", number is converted to string
console.log("1" + 2); // "12", number is converted to string
console.log(1 - "2"); // -1, string is converted to number
console.log("1" - 2); // -1, string is converted to number
console.log(1 * "2"); // 2, string is converted to number
console.log("1" * 2); // 2, string is converted to number
console.log(1 / "2"); // 0.5, string is converted to number
console.log("1" / 2); // 0.5, string is converted to number
console.log(1 + true); // 2, boolean is converted to number
console.log(1 + false); // 1, boolean is converted to number
console.log(1 + null); // 1, null is converted to number
console.log(1 + undefined); // NaN, undefined is converted to number

To avoid implicit type conversion, you can use the strict equality operator (===), which compares the values and the types of the operands, and returns true only if they are both equal. For example:

Javascript
                        
// Strict equality operator
console.log(1 === "1"); // false, different types
console.log(1 === 1); // true, same type and value
console.log(true === 1); // false, different types
console.log(true === true); // true, same type and value
console.log(null === undefined); // false, different types
console.log(null === null); // true, same type and value

You can also perform type conversion manually by using built-in functions or methods that convert values from one type to another. This is called explicit type conversion, and it gives you more control over how the values are converted. For example:

Javascript
                        
// Explicit type conversion
console.log(Number("3.14")); // 3.14, string is converted to number
console.log(Number("abc")); // NaN, invalid string
console.log(String(42)); // "42", number is converted to string
console.log(String(true)); // "true", boolean is converted to string
console.log(Boolean(1)); // true, number is converted to boolean
console.log(Boolean(0)); // false, number is converted to boolean
console.log(Boolean("")); // false, empty string is converted to boolean
console.log(Boolean("abc")); // true, non-empty string is converted to boolean

Summary

In this article, you learned about the different types of data that JavaScript can handle, such as numbers, strings, booleans, null, undefined, symbols, and objects. You also learned how to check and convert data types in JavaScript, and the difference between implicit and explicit type conversion. Data types are essential for understanding how data can be stored, manipulated, and evaluated in your JavaScript programs.