DEV Community

Cover image for Primitive & Non-Primitive Data Types
Code Of Accuracy
Code Of Accuracy

Posted on

Primitive & Non-Primitive Data Types

In JavaScript, data types can be broadly classified into two categories: primitive and non-primitive data types. Understanding these data types is crucial for writing effective and efficient code. In this article, we will explore primitive and non-primitive data types in JavaScript, along with examples.

Primitive Data Types

Primitive data types in JavaScript are simple data types that are not objects and do not have methods. They are immutable, which means that their values cannot be changed once they are created. There are six primitive data types in JavaScript.

1. String: A string is a collection of characters that are enclosed within single or double quotes. For example:

let name = 'John Doe';
Enter fullscreen mode Exit fullscreen mode

2. Number: A number is a numerical value, which can be either positive, negative, or with decimal points. For example:

let age = 25;
let salary = 50000.50;
Enter fullscreen mode Exit fullscreen mode

3. Boolean: A boolean data type can have only two values - true or false. For example:

let isMarried = true;
Enter fullscreen mode Exit fullscreen mode

4. Null: Null represents a null or empty value. For example:

let address = null;
Enter fullscreen mode Exit fullscreen mode

5. Undefined: Undefined represents a variable that has not been assigned a value. For example:

let gender;
Enter fullscreen mode Exit fullscreen mode

6. Symbol: A symbol is a unique and immutable data type that is used to identify object properties. For example:

const mySymbol = Symbol('mySymbol');
Enter fullscreen mode Exit fullscreen mode

Non-Primitive Data Types

Non-primitive data types in JavaScript are complex data types that are objects and can have methods. They are mutable, which means that their values can be changed. There are three non-primitive data types in JavaScript:

1. Object: An object is a collection of key-value pairs, where the key is a string and the value can be any data type. For example:

const person = {
  name: 'John Doe',
  age: 25,
  isMarried: true
};
Enter fullscreen mode Exit fullscreen mode

2. Array: An array is a collection of elements, which can be of any data type. The elements are indexed and can be accessed using the index number. For example:

const numbers = [1, 2, 3, 4, 5];
Enter fullscreen mode Exit fullscreen mode

3. Function: A function is a block of code that can be invoked or called to perform a specific task. It can accept parameters and return a value. For example:

function addNumbers(num1, num2) {
  return num1 + num2;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)