JavaScript Data Types - CSU677 - Shoolini U

JavaScript Data Types

1. What Are Data Types and Why Do We Need Them?

In programming, a data type is a classification that specifies which kind of value a variable can hold. Data types define the operations that can be performed on the data and the way the computer interprets the values. In essence, data types act as a guide for the program to handle and manipulate information correctly.

1.1 Importance of Data Types

Data types are critical for several reasons:

1.2 Examples of Data Types

Here are some common data types used in programming:

1.3 Static vs. Dynamic Typing

Programming languages can be classified based on how they handle data types:

Let's explore the detailed data types in JavaScript to see how they function and why they are essential in this language.

2. Data Types in JavaScript

JavaScript is a dynamically typed language, meaning variables can hold any type of data and types are determined at runtime. JavaScript provides both primitive and object data types.

2.1 Primitive Data Types

Primitive data types are the most basic types of data in JavaScript. They are immutable and represent a single value. JavaScript has 7 primitive data types:

2.1.1 Number

JavaScript has a single type for numbers, which includes both integers and floating-point numbers.


// Example of a number
let integer = 42;
let floatingPoint = 3.14;

The Number type also includes special values: Infinity, -Infinity, and NaN (Not-a-Number).

2.1.2 BigInt

BigInt allows you to work with integers larger than Number.MAX_SAFE_INTEGER.


// Example of BigInt
let bigNumber = 1234567890123456789012345678901234567890n;
2.1.3 String

Strings in JavaScript are sequences of characters. They are enclosed in single, double, or backticks.


// Example of strings
let singleQuote = 'Hello';
let doubleQuote = "World";
let templateLiteral = `Hello, ${name}!`;
2.1.4 Boolean

Boolean represents a logical entity with two values: true and false.


// Example of boolean
let isTrue = true;
let isFalse = false;
2.1.5 Undefined

A variable that has been declared but not yet assigned a value is undefined.


// Example of undefined
let x;
console.log(x); // undefined
2.1.6 Null

Null represents the intentional absence of any object value.


// Example of null
let y = null;
console.log(y); // null
2.1.7 Symbol

Symbol is a unique and immutable primitive value used to create anonymous object properties.


// Example of symbol
let symbol1 = Symbol('description');
let symbol2 = Symbol('description');
console.log(symbol1 === symbol2); // false

2.2 Object Data Types

Objects are more complex data structures in JavaScript. They allow us to store collections of data and more complex entities.

2.2.1 Object

Objects are collections of key-value pairs. Values can be any data type, including functions and other objects.


// Example of object
let person = {
  name: 'John',
  age: 30,
  greet: function() {
    console.log('Hello');
  }
};
2.2.2 Array

Arrays are used to store ordered collections of data.


// Example of array
let numbers = [1, 2, 3, 4, 5];
2.2.3 Function

Functions in JavaScript are objects that can be invoked. They can be assigned to variables and passed as arguments to other functions.


// Example of function
function greet(name) {
  return `Hello, ${name}`;
}
2.2.4 Date

The Date object represents a single moment in time. It can be created with the new Date() constructor.


// Example of date
let now = new Date();
console.log(now);
2.2.5 RegExp

Regular expressions are patterns used to match character combinations in strings. They are created using the RegExp constructor or literal syntax.


// Example of RegExp
let pattern = /abc/;
let result = pattern.test('abc123');
console.log(result); // true

2.3 Type Checking

JavaScript offers several ways to check the type of a variable:


// Example of type checking
console.log(typeof 42); // "number"
console.log(person instanceof Object); // true

3. Data Types and its Concepts

To enhance understanding of data types, it's important to consider a few additional concepts that connect to how data types are used and managed in JavaScript and other programming languages. These concepts will deepen your understanding of the practical application and behavior of data types in programming.

3.1 Type Conversion

Type Conversion refers to converting a value from one data type to another. This can be done implicitly (automatic) or explicitly (manual). In JavaScript, implicit type conversion is common and is known as type coercion.


// Implicit Conversion (Coercion)
let x = 5 + '5'; // '55' (number is converted to string)

// Explicit Conversion
let y = String(5); // '5'
let z = Number('5'); // 5

3.2 Mutable vs. Immutable Data Types

Understanding whether a data type is mutable or immutable is key to managing how data changes in your programs:


// Mutable Example: Arrays
let arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]

// Immutable Example: Strings
let str = 'Hello';
str[0] = 'Y'; // Does nothing, strings are immutable

3.3 Strict Mode and Type Checking

Strict Mode in JavaScript enables a stricter set of rules for writing secure JavaScript code, and it helps prevent certain types of bugs related to variable declarations and type errors.


'use strict';

x = 10; // Error: variable must be declared

3.4 Data Structures and Complex Data Types

As you work with JavaScript, you'll often need to group multiple pieces of data. This is where complex data types like Objects and Arrays come into play. They allow you to store collections of related data:


// Example of a Map
let map = new Map();
map.set('key1', 'value1');
map.set(2, 'value2');
console.log(map.get('key1')); // 'value1'

3.5 Error Handling and Type Errors

Another essential aspect of working with data types is understanding how to handle errors, especially TypeErrors, which occur when an operation is performed on the wrong type.


try {
    null.length; // Error: Cannot read property 'length' of null
} catch (e) {
    console.log(e instanceof TypeError); // true
}

Handling such errors with try...catch blocks ensures your program continues to run even when encountering type-related issues.

3.6 Transition to TypeScript

As your programs grow in complexity, handling dynamic types can lead to bugs. This is where TypeScript comes in. TypeScript is a superset of JavaScript that adds static type definitions, allowing you to define variable types and catch type errors during development.


// TypeScript example with static typing
let message: string = 'Hello, TypeScript';
message = 42; // Error: Type 'number' is not assignable to type 'string'

By using static types, TypeScript helps prevent type-related errors that are common in dynamically typed languages like JavaScript.