JavaScript Data Types with Examples

In JavaScript, you can assign various types of data to a variable, such as a string, number, boolean, and more. This is because JavaScript is a loosely typed (or dynamically typed) language — meaning variables are not bound to a specific data type.

Example: A Variable with Different Data Types

let myVariable = 1;       // Number
    myVariable = 'one';       // String
    myVariable = true;        // Boolean

In this example:

  • 1 is a number

  • 'one' is a string

  • true is a boolean

This shows how JavaScript allows the same variable to hold different types of values at different times.

JavaScript Data Types

JavaScript data types are categorized into two main types:

  1. Primitive Data Types

  2. Structural (Non-Primitive) Data Types

Primitive Data Types

Primitive data types are the most basic kinds of data in JavaScript. They represent a single value and are immutable (cannot be changed).

Data TypeDescriptionExample
StringA sequence of characters enclosed in single ' ', double " ", or backticks ` `.'Hello', "World", `JavaScript`
NumberRepresents both integer and floating-point numbers.100, 3.14
BigIntRepresents large integers beyond the safe limit of Number. It ends with n.123456789123456789123456789n
BooleanRepresents a logical value: either true or false.true, false
NullRepresents an intentional absence of any object value.let data = null;
UndefinedA variable that has been declared but not assigned a value is undefined.let x; console.log(x); // undefined





 Structural (Non-Primitive) Data Types

Structural data types are used to store collections of values or more complex entities.

Data TypeDescriptionExample
ObjectA collection of key-value pairs (properties and methods).



 
   let person = {
  firstName: "James",
  lastName: "Bond",
  age: 30
};
``` |
| **Array** | A list-like object that stores multiple values in an ordered way. |  
```javascript
let numbers = [1, 2, 3, 4];
``` |
| **Date** | Represents dates and times. |  
```javascript
let today = new Date("2021-07-25");
``` |

---

### ? Summary

- **Primitive types** include: `String`, `Number`, `BigInt`, `Boolean`, `Null`, and `Undefined`.
- **Structural types** include: `Object`, `Array`, and `Date`.
- JavaScript allows flexibility in assigning and reassigning types to variables due to its dynamic nature.

Note: Type Coercion in JavaScript

When adding a number and a string, JavaScript automatically converts the number to a string. This behavior is called type coercion.

 let result = 5 + "10";
console.log(result); // Output: "510"

Left-to-Right Evaluation in JavaScript

In JavaScript, expressions are evaluated from left to right. This means that the order in which you write the operations can impact the result. Understanding how JavaScript evaluates expressions is crucial for avoiding unexpected outcomes.

let result = 5 + 10 + "20";
console.log(result); // Output: "1520"

Explanation:

  • First, 5 + 10 is evaluated, which results in 15 (a number).

  • Next, 15 + "20" is evaluated. Since one of the operands is a string, JavaScript converts the number 15 to a string and concatenates it with "20", resulting in "1520".

String and Addition
let result = "5" + 10 + 15;
console.log(result); // Output: "51015"

Explanation:

  • First, "5" + 10 is evaluated. JavaScript converts 10 to a string and concatenates it with "5", resulting in "510".

  • Then, "510" + 15 is evaluated. JavaScript converts 15 to a string and concatenates it with "510", resulting in "51015".

JavaScript Arrays 

An Array is a special variable in JavaScript used to store a collection of values. It can hold multiple values of different types, including strings, numbers, objects, or even other arrays.

Key Characteristics of Arrays:

  • Arrays are ordered collections of data.

  • They can hold multiple values in a single variable.

  • They use indexing to access elements (indices start from 0).


Creating Arrays

You can create arrays in JavaScript using either of the following methods:

1. Using Array Literals

let fruits = ['Apple', 'Banana', 'Cherry'];

2. Using the Array Constructor

let numbers = new Array(1, 2, 3, 4);

Accessing Elements in an Array

You can access elements in an array using their index. The index starts at 0.

Example:

let colors = ['Red', 'Green', 'Blue'];
console.log(colors[0]); // Output: 'Red' (first element)
console.log(colors[1]); // Output: 'Green' (second element)

Array Properties and Methods

Arrays in JavaScript come with many built-in properties and methods that make it easy to manipulate data.

Common Array Properties

  • length: Returns the number of elements in the array.

let colors = ['Red', 'Green', 'Blue'];
console.log(colors.length); // Output: 3

Common Array Methods

  • push(): Adds one or more elements to the end of an array.

let fruits = ['Apple', 'Banana'];
fruits.push('Cherry');
console.log(fruits); // Output: ['Apple', 'Banana', 'Cherry']

  • pop(): Removes the last element from an array and returns it.

let fruits = ['Apple', 'Banana', 'Cherry'];
let removed = fruits.pop();
console.log(fruits); // Output: ['Apple', 'Banana']
console.log(removed); // Output: 'Cherry'
  • shift(): Removes the first element from an array and returns it.

let fruits = ['Apple', 'Banana', 'Cherry'];
let removed = fruits.shift();
console.log(fruits); // Output: ['Banana', 'Cherry']
console.log(removed); // Output: 'Apple'
  • unshift(): Adds one or more elements to the beginning of an array.

let fruits = ['Banana', 'Cherry'];
fruits.unshift('Apple');
console.log(fruits); // Output: ['Apple', 'Banana', 'Cherry']
  • concat(): Combines two or more arrays into a new array.

let array1 = ['Apple', 'Banana'];
let array2 = ['Cherry', 'Date'];
let combined = array1.concat(array2);
console.log(combined); // Output: ['Apple', 'Banana', 'Cherry', 'Date']

Iterating Over Arrays

JavaScript provides several ways to loop through arrays, such as using for loops or forEach.

1. Using a for loop

let fruits = ['Apple', 'Banana', 'Cherry'];
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]); // Output: Apple, Banana, Cherry
}

2. Using forEach() Method

let fruits = ['Apple', 'Banana', 'Cherry'];
fruits.forEach(function(fruit) {
    console.log(fruit); // Output: Apple, Banana, Cherry
});

Multidimensional Arrays

You can also create arrays of arrays, which is known as a multidimensional array.

Example:

let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

console.log(matrix[0][1]); // Output: 2 (First row, second column)
console.log(matrix[2][0]); // Output: 7 (Third row, first column)

Array Methods for Searching

  • indexOf(): Returns the index of the first occurrence of an element in the array.

let fruits = ['Apple', 'Banana', 'Cherry'];
console.log(fruits.indexOf('Banana')); // Output: 1
console.log(fruits.indexOf('Grapes')); // Output: -1 (not found)
  • includes(): Returns true if an array contains a specified element.

let fruits = ['Apple', 'Banana', 'Cherry'];
console.log(fruits.includes('Banana')); // Output: true
console.log(fruits.includes('Grapes')); // Output: false


Array Destructuring

With array destructuring, you can easily extract values from arrays into variables.

Example:

let fruits = ['Apple', 'Banana', 'Cherry'];
let [first, second, third] = fruits;

console.log(first);  // Output: 'Apple'
console.log(second); // Output: 'Banana'
console.log(third);  // Output: 'Cherry'

Summary

  • Arrays in JavaScript are used to store multiple values in a single variable.

  • You can access elements using their index, and arrays have useful methods for modifying, searching, and iterating through data.

  • JavaScript arrays are dynamic, meaning they can grow or shrink in size as needed.

JavaScript Objects

An Object in JavaScript is a collection of key-value pairs, where each key (also called a property) is a string, and its associated value can be any data type, including other objects, arrays, or functions. Objects allow you to store and organize data more flexibly than arrays.

Key Characteristics of Objects:

  • Objects are unordered collections of key-value pairs.

  • The keys (also called properties) are typically strings or symbols, and the values can be any data type (including arrays, numbers, strings, etc.).

  • Objects are useful for representing complex data structures, like a person, car, or book.

Creating Objects

There are two common ways to create objects in JavaScript:

1. Using Object Literals (the most common and preferred method)

let person = {
    firstName: 'John',
    lastName: 'Doe',
    age: 30,
    greet: function() {
        console.log("Hello, " + this.firstName);
    }
};