Data types

Every variable has a data type. Data type indicates what kind of data the variable holds. In JavaScript, the type of data variable hold can be grouped into two categories:

  1. primitive types
  2. composite types

Primitive types in JavaScript

In JavaScript, primitive types (also called primitive values or primitive data types) are the most basic data types that are not objects and have no methods. There are 7 primitive types in JavaScript:

1. number

  • Represents both integer and floating-point numbers.
  • Examples: 423.14NaN (Not a Number), Infinity.
  • Special cases:
    • NaN (result of invalid math operations like 0/0).
    • Infinity (result of division by zero: 1/0).

Below is an example.

let x = 250;
    let y = 40.5;
    console.log("Value of x=" + x);
    console.log("Value of y=" + y);

Output

Value of x=250
Value of y=40.5

As the name implies, a number type refers to numerical values. Numbers can be divided into two groups:

  • floating-point — are fractional numbers such as 2.45, -3.58, and .97
  • Integers — are whole numbers such as 245, -480, and 3.

Unlike programming languages such as C++, and Java, the number type in JavaScript include both floating-point and integer values. Integers, in JavaScript, can span in the range of -253 to 253 and floating-point values can be as high as ±1.7976*10308 and as low as ±2.2250*10-308.

2. string

  • Represents textual data (sequence of characters).
  • Examples: "hello"'world'`template`.
  • Strings are immutable (cannot be changed once created).

Below is an example.

let str = 'Hello All';
let str1 = "Welcome to my new house";
console.log("Value of str=" + str);
console.log("Value of str1=" + str1);

Output

Value of str=Hello All
Value of str1=Welcome to my new house

A string type refers to one or more characters of text. In JavaScript, a string is enclosed inside single or double quotes. “Script buzz”, ‘HTML’, ‘JavaScript’, and “1999”, are all examples of strings. Why is “1999” a string? As we stated above, a variable of string type is surrounded by double or single quotes. Note, 1999, is an example of numerical type because of the absence of the quotes.

When working with strings, it is important to understand that strings must be either surrounded with single or double quotes. The following, for example, represents an invalid string:

“This is not a valid string.’

In the above example, we are not being consistent when creating the string: we start with double quotation marks but end with only single quote. If you need to use an apostrophe (or single quote) in the string, then, you may want to surround it with double quotation marks to make it a valid string. For example, this is not a valid

‘they’re here!’

string because we have unbalanced quotes. Our string contains a single quote while we start and end our string with a single quote. We can make that a valid string by using double quotes around the string:

“they’re here!”

On the other hand, if you have to use double quotes in a string, then, you may want to avoid using double quotes around the string. As another example, the following is an invalid string:

“”JavaScript” is easy.”

because again here we have unbalanced quotes. Instead, you may create that string as:

‘”JavaScript” is easy.’

3. boolean

  • Represents a logical value (true or false).

Below is an example

let x;
console.log(x); // Outputs: undefined

Output

George Boole developed the true/false system logic in the 19th century. Consequently, the word Boolean is derived from his name.

In JavaScript, Boolean logic allows your program to make decisions. A Boolean logic statement consists of a condition that evaluates to either true or false. You can think of the condition as a question that has one of two possible answers:

  1. yes or no,
  2. ON or OFF, or
  3. positive or negative
  4. true or false

When working with Boolean logic, keep in mind there is no “maybe” or third possibility. Thus a Boolean type a can be used anytime there is only one possible outcome out of two possible outcomes.

A Boolean type is useful in situations where you want the program to act according to the value it represents. For instance, let’s say our program has to determine whether a person is at least 18 years of age to apply for a driving license. In the program, we would ask the applicant’s date of birth and then we would calculate applicant’s age. Then we would ask the following questions programmatically: is this applicant’s age at least 18 years of age. The answer to this question would be either yes or no. In this case, we could use a Boolean type to store our response. If our response is yes to our question, then, the applicant does meet the minimum age requirement for the license. If, however, our response if no, then the applicant does not meet the minimum age requirement. The following summarizes our Boolean logic example:

4. null

  • Represents the intentional absence of any value.
  • Example: let x = null;.
  • Note: typeof null returns "object" (a historical bug in JavaScript).

The null type indicates an empty value. When a variable is assigned the value null, its type becomes null. A null type variable is a placeholder that represents nothing. The following shows an example of a variable of type null:

var iAge = null;

Since null is an empty object, its type is object. We can confirm this by using the typeof operator:

alert (“iAge is of type: ” + typeof(iAge));

That will output:

5. undefined

  • Represents a variable that has been declared but not assigned a value.
  • Example: let x; → x is undefined.
  • Also, functions without a return statement return undefined.

The undefined type refers to those variables or object properties that are either undefined or do not exist. When a variable, for example, is declared without assigning a value to it, it is of undefined type. So

var iAge;

declares a variable called iAge. Its type is undefined; it can be confirmed by simply outputting its type using the typeof operator:

alert (“iAge is of type: ” + typeof(iAge));

So our output will show that iAge is of type undefined:

So as long as no value is assigned to a variable, its type is undefined. Once a value is assigned, it will no longer be of type undefined but rather one of other types supported in JavaScript: numbers, strings, Boolean, or Null.

6. symbol (ES6+)

  • Represents a unique and immutable value, often used as object property keys.

Below is an example.

let sym = Symbol("Hello")
console.log(typeof(sym));
console.log(sym);

Output

symbol
Symbol(Hello)

7. bigint (ES11/ES2020+)

  • Represents integers larger than 2^53 - 1 (the limit for number type).
  • Created by appending n to an integer or using BigInt().

Below is an example.

let bigNum = 123422222222222222222222222222222222222n
console.log(bigNum)

Output

123422222222222222222222222222222222222n

Key Characteristics of Primitives:

  • Immutable: Their values cannot be changed (e.g., let s = "hello"; s[0] = "H" does not modify s).
  • No Methods: Though they behave like they have methods (e.g., "hello".toUpperCase()), JavaScript temporarily wraps them in objects (concept called “auto-boxing”).
  • Stored by Value: When assigned or passed, the actual value is copied (not a reference).

Checking Types with typeof:

typeof 42;           // "number"
typeof "hello";      // "string"
typeof true;         // "boolean"
typeof undefined;    // "undefined"
typeof null;         // "object" (historical bug)
typeof Symbol('id'); // "symbol"
typeof 10n;          // "bigint"

Summary Table:

Primitive TypeExample Valuestypeof Check
number423.14NaN"number"
string"hello"'world'"string"
booleantruefalse"boolean"
nullnull"object"
undefinedundefined"undefined"
symbolSymbol('desc')"symbol"
bigint123nBigInt(123)"bigint"

Primitives are the foundation of JavaScript, and understanding them is crucial for working with more complex data structures like objects and arrays. Let me know if you’d like further clarification!

Composite types in JavaScript

From primitive types mentioned above, we can derive composite types. A composite type can consist of numbers, strings, Booleans, undefined and null values. The three types of composite types available in JavaScript are objects, arrays, and functions.

Non-Primitive Data Types

Here are the non-primitive data types in JavaScript:

1. Objects

  • The most fundamental non-primitive type
  • Collections of key-value pairs

Example

let person = {
  name: "John",
  age: 30,
  isStudent: false
};

2. Arrays

  • Special type of object used for storing ordered collections

Example

let colors = ["red", "green", "blue"];

3. Functions

  • Callable objects that execute a block of code

Example

function greet(name) {
  return "Hello, " + name;
}

4. Dates

  • For working with dates and times

Example

let today = new Date();

5. Regular Expressions

  • For pattern matching in strings

Example

let pattern = /hello/i;

6. Maps

  • Key-value collections (introduced in ES6)

Example

let map = new Map();
map.set('name', 'Alice');

7. Sets

  • Collections of unique values (introduced in ES6)

Example

let set = new Set([1, 2, 3, 4]);

Key Characteristics of Non-Primitive Types:

  • They are mutable (can be changed after creation)
  • They are reference types (variables store a reference to the memory location, not the actual value)
  • They have methods and properties
  • They can contain any combination of primitive and non-primitive types

Unlike primitive types (number, string, boolean, null, undefined, symbol, bigint), non-primitive types

Difference Between Primitive vs Non-Primitive

PrimitiveNon-Primitive
Primitive Data types are predefined. Non-Primitive data types are created by the programmer
Primitive Data types will have certain values.Non-Primitive data types can be NULL.
Size depends on the type of data structure.Size is not fixed
Examples are numbers and strings.Examples are Array and Linked List.
It can start with a lowercase.It can start with uppercase.