Data Types in JavaScript: Primitive and Non-Primitive

JavaScript data types

Data types in JavaScript help hold values and shape code rules. They set clear plans for text, numbers, and other data.

Developers choose the right data types in JavaScript to prevent errors and keep code clear. It also improves performance and supports scalability.

Understand the Data Types in JavaScript

Data types show what kind of data a variable can hold. They tell the code how to apply operations. The code uses types to decide what work to perform. In this way, the program shows order in its system.

So, how does JavaScript handle data internally?

JavaScript decides on a type when you create a variable. The code does not need a label to show the type. The value itself shows the type. JavaScript keeps the data in a simple format that it can track. The code assigns memory based on the type of data.

A basic list shows two groups of data types. One group holds simple values. The other group holds objects and more. You get simple values when you use strings or numbers. You get objects when you use arrays, functions, or other composite forms.

A quick example shows the difference. Let a variable hold a number. Then let another hold an object. The first action shows a primitive type. The second action shows a reference type.

Data types matter because they lead to secure and clear code. They bring order and help reduce runtime errors. Every code part wins from sound type use.

Types of Data in JavaScript

We can categorize data types in JavaScript which are:

  • Primitive Data Types
  • Non-Primitive

Let’s take each one in-depth:

JavaScript primitive data types

They are basic values that are not objects and have no methods. They include: string, number, boolean, null, undefined, symbol, and bigint. These types store only one simple value.

Let’s take each one in-depth:

Strings

A string is used to store text, like letters, numbers, or symbols inside quotes (' ' or " ").

Here is an example:

let name = "Ali";

You use strings for names, sentences, messages, or any readable text. You can join (combine) strings with +, like "Hello " + "World".

Number

A number stores any kind of numeric value—whole numbers or decimals.
Example:

let price = 99.99;

You use numbers for counting, math, prices, or measurements. JavaScript uses the same type for integers and floating-point numbers.

Boolean

A boolean holds just two values: true or false.

Here is an example:

let isLoggedIn = false;


It’s useful for when you need to do decisions.

For example, in an if-statement:

if (isLoggedIn) {
  showPage();
}
Null

Null means the variable is empty on purpose—it has no value.
For example:

let selectedItem = null;

You set something to null when you want to clear it or mark it as empty. It’s not an error—just a way to say “nothing here”.

Undefined

Undefined means the variable is created but no value is assigned to it. For example:

let age;

If you try to use a variable before setting it, JavaScript gives it the value undefined by default.

Symbol

A symbol is a unique, hidden value often used as a special key in objects.

For example:

let id = Symbol("user");

Even if you create two symbols with the same name, they’re not equal. Symbols help avoid name clashes in large programs.

BigInt

BigInt is used for numbers bigger than JavaScript’s safe limit (2^53 - 1).

For example:

let bigValue = 1234567890123456789012345n;

Add n at the end to make a BigInt. Use it when dealing with huge numbers like in banking, science, or encryption.

JavaScript Non-Primitive types (Reference) Data Types:

Non-primitive (or reference) data types store collections or objects. Unlike primitive types, they do not hold the actual value, but a reference (or address) to the value in memory. This means if you copy them, changes affect both.

There are three main non-primitive types in JavaScript:

Object

Objects store multiple values in key-value pairs.

Here is an example:

let user = { name: "Ali", age: 25 };

Use objects when you want to group related data together. You can access values with user.name or user["age"].

Array

Arrays store a list of items in a specific order. For example:

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

You use arrays when working with a group of similar data, like names or numbers. Access items by index: colors[0].

Function

Functions are blocks of code you can run again and again. Here is an example:

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

Functions let you reuse logic. You call them like greet("Ali") to get "Hello, Ali".

Type Checking in JavaScript

Type checking means finding out the type of a value (like string, number, object, etc.).

The typeof Operator

You use typeof to check the type of a variable or value.

For example:

let age = 25;
console.log(typeof age);

The output:

number

Here are more examples:

typeof "hello";     // "string"
typeof true;        // "boolean"
typeof undefined;   // "undefined"
typeof null;        // "object" (this is a known JavaScript bug)
typeof {};          // "object"
typeof [];          // "object"
typeof function(){} // "function"

Type Conversion in JavaScript

Type conversion means changing a value from one type to another. There are two kinds:

Implicit Conversion (Type Coercion):

JavaScript automatically changes types when needed. For example:

let result = "5" + 2; // "52" (number 2 is changed to string)

Here is another example:

let sum = "10" - 2; // 8 (string is changed to number)

Explicit Conversion (Manual Conversion)

You change the type on purpose using functions.

To string:

String(123); // "123"
(123).toString(); // "123"

Convert to number:

Number("45"); // 45
parseInt("42"); // 42
parseFloat("4.5"); // 4.5

To boolean:

Boolean(1); // true
Boolean(0); // false
Boolean(""); // false
Boolean("hello"); // true

Truthy and falsy values:

Some values behave like true or false when converted to booleans.

Falsy values (become false):

  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN
  • false

All other values are truthy.

Examples of Data Types in JavaScript

Example 1 – Primitive Type with a String and a Number A developer sets a string value in a variable. Then the developer sets a number value in another variable. Code appears as:

let greeting = "Hello";  
let count = 5;

This code shows a simple text and numeric values. The output shows “Hello” and 5 when printed. The example shows clarity when variables hold clear types.

Example 2 – Type Checking with typeof A variable holds a boolean value. The code checks the variable with typeof. Code appears as:

let active = false;  
console.log(typeof active);

The output prints “boolean”. This example shows how typeof checks data types. The code helps maintain clean tests in code.

Example 3 – Creating an Object A developer builds an object with keys. Code appears as:

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

The output prints “Bob”. The object holds a name and an age. This code shows how objects hold multiple values together.

Example 4 – Manipulating an Array and Checking Its Type A developer builds an array. Code appears as:

let items = [10, 20, 30];  
console.log(Array.isArray(items));

The output prints true. The code shows how arrays serve as lists for numbers. Each example helps to see the use of data types in clear steps.

These examples show clear code steps. Developers see the output and learn the proper type use.

Wrapping Up

In this article you learned how data types in javascript shape code and hold values. You learned that each type makes the code run in an order that helps avoid errors.

You also saw that simple values and complex objects get treated with distinct styles.

Here is a quick recap:

Primitive Data Types:

  • String: Holds text, like "Hello"
  • Number: Holds numbers, like 42 or 3.14
  • Boolean: True or false values, like true
  • Null: Empty value on purpose, like null
  • Undefined: Variable declared but no value, like let x;
  • Symbol: Unique identifier, like Symbol("id")
  • BigInt: For very large numbers, like 123456789n

Non-Primitive (Reference) Data Types:

  • Object: Stores key-value pairs, like {name: "Ali"}
  • Array: Ordered list of values, like [1, 2, 3]
  • Function: Reusable block of code, like function greet() {}

FAQs

What are the 8 primitive data types?

Primitive types stand as the basic values in javascript. They include String, Number, BigInt, Boolean, Undefined, Null, and Symbol. In some explanations, developers add one more by considering literal types as separate examples. Each type holds a simple value that does not change in place. This setup gives the code clearer handling of data and reduces mix-ups during conversion tests.

What are the 5 Non-Primitive data types?

Non-primitive types hold collections of values. They include Objects, Arrays, Functions, Dates, and Maps with Sets. Each type lets the code bundle and hold multiple values at once. Code tasks find strength when data clusters in these forms. The structure holds keys with values and brings order to the code. Developers use these types to group information for better management and access.

When should I use null vs undefined?

The code uses undefined when a value does not exist. Developers often see undefined as a default state for unset variables. The code uses null when a developer wants to show that a variable holds no value. Each choice gives the code a clear marker that helps future checks. Clear value settings help avoid mistakes and make error tracing simpler.

Can an array be considered an object?

An array stores values in an ordered list. The code builds arrays with square brackets. Internally, arrays share traits with objects. Each array holds keys for items as numbers. Developers call arrays objects because they hold properties. This dual use gives code ease when accessing lists and using object methods.

How do I check if a variable is a number or not?

You call typeof on the variable and watch the output. The code shows "number" when the value qualifies. Developers sometimes use Number.isNaN to test for numbers that make no sense. This two-step check proves useful in tests. The clear result helps debug and keeps code order intact. Developers work with such tests for proper type checking.
Previous Article

How to Use PHP count() to Get Array Length

Next Article

Git Pull Rebase: How It Works, and When to Use It

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.