Get started with data-types in JS

Get started with data-types in JS

Hey developers! Today, I'm here to discuss a fundamental yet crucial topic in JavaScript. It’s called “data types”. While this topic may seem basic, having a clear understanding of data types is essential for your future coding journey. Grab some coffee, take a sip, and let's dive in!

Before diving into the main topic let me ask you something

What is Data?

Well in simple terms, data is nothing but ‘raw information’. In computer science and programming, data refers to any piece of information that a computer can process, store, and manipulate. It can be in many forms like string, number, Boolean etc.

What is Data-Type?

A data type defines the type of data a variable can store and how the system processes it. It determines the possible values, memory usage, and the operations that can be performed on that data. In simple terms data type determines in which form a data is stored.

How to declare variables

In java Script we use key words like let and const to declare a a variable. Unlike programming languages like C or C++ where each data types is needed to be specified separately while declaring, JavaScript doesn’t require that much specification. The JavaScript engine is smart enough to identify the data type by itself. So let and const are enough.

let: Variables declared by let can be changed later.

const: Variables declared by const can not be changed later.

Types of Data in JavaScript:

There are many types of data in JavaScript. They’re mainly categorized in 2 categories:

  1. Primitive

  2. Non primitive.

Primitive Data Types in JavaScript

In JavaScript, primitive data types are the most basic types of data. They are immutable (cannot be changed) and stored directly in memory. In simple terms once Primitive Data Types are declared you can not edit or mutate the data anymore.

There are 7 types of primitive data in JavaScript:

  • Number

  • BigInt

  • String

  • Boolean

  • Undefined

  • Null

  • Symbol

Non-Primitive Data Types in JavaScript

Non-primitive (reference) data types are mutable and stored by reference. There are mainly 3 Non Primitive Data Types in JavaScript:

  • Object

  • Array

  • Function

Primitive data-type

1. 🔢Number🔢:

This data type is pretty self explanatory. As the name suggests Number is a data type that stores or represents “Numeric Value”.

You can declare a number in 2 ways:

1️⃣ Declaring a Number By directly assigning

let age = 22;  //integer
let height = 181.5;  //float

2️⃣ Using the Number Constructor

let age = Number(22);  // output: integer
let height = Number(181.5);  // output: float

In JavaScript, numbers can be categorized into:

  • Integers (also known as whole numbers like 22)

  • Floats (also known as decimal numbers like 181.5)

Unlike languages such as C or C++, JavaScript does not require explicit type declarations for integers or floats. The JavaScript engine automatically determines the number type at runtime.

console.log(typeof age) // output: number

In the example above, we use typeof to check the data type of age, which confirms that it is a number.

2. 🔢BigInt🔢:

BigInt is same as Number data type, the only difference is BigInt is only used to store bigger numbers than Number datatype can store.

You can create a BigInt by adding n to the end of a number:

let bigNumber = 9007199254740991n;
console.log(bigNumber); // 9007199254740991n

BigInt is a datatype that you’ll rarely use in any production level code.

3.🧵 String🧵:

String is nothing but a collection of one or more characters. String data types is used to store data in text form.

You can declare String in 2 ways:

1️⃣ Declaring a String by directly assigning value

let name = "Rajib"

2️⃣ Using the String Constructor

let name = new String("Rajib");

Both the ways are correct. But you’ll mostly use the first one.

Here name is a variable which has stored a string type data. Here the quotes ( ” ” or ‘ ’ or ) are required to store a string.

As long as the quotes are there you can write anything within it and it will be treated as a “String”.

For example:

let email = "myName1234@example.com";
let age = "22"

As you can see in the first example, we have used English characters, numbers and also symbols (or special characters) and in the 2nd example I have used nothing but numbers, yet it’ll behave like a string.

I hope you have deduced it by now that whatever we write within the quotes ( ” “ or ‘ ‘ ) behaves like a string.

You have a task now:

let name = "Rajib"
let email = "myName1234@example.com";
let age = "22"

console.log(typeof name);
console.log(typeof email);
console.log(typeof age);

Copy this code and run it on your IDE and find out what results we can get from this. If you write everything from scratch instead of copying, that’s an extra point 😎.

4.✅ Boolean❌:

A Boolean represents one of two values: true ✅ or false ❌. It is commonly used for conditions and comparisons in JavaScript.

Here’s is an example:

let isEmployed = true;
let isMarried = false;

console.log(isEmployed); // output: true
console.log(isMarried);  // output: false

In this example, the variables isEmployed and isMarried store Boolean values and return their respective values when printed.

Boolean from Comparisons

JavaScript also returns Boolean values when performing comparisons:

console.log(9>6) // output: True
console.log(9<6) // output: false

Here I have printed two operations and compared 2 numbers in each.

  • The first comparison checks if 9 is greater than 6, which is true, so it returns true.

  • The second comparison checks if 9 is less than 6, which is false, so it returns false.

5. Undefined:

In JavaScript if a variable is not initialized yet then by default it’s assigned undefined. As the name suggests undefined means the variable type is not defined.

let networth;
let salary = undefined;

Here you can observe I have written 2 variables:

  • networth with nothing assigned to it.

  • salary with undefined assigned to it.

Both approaches will behave the same. You can either leave the variable uninitialized, in which case JavaScript implicitly assigns undefined, or you can explicitly assign undefined yourself.

Now a question for you. What do you think will be the typeof of undefined?

Let’s try:

let salary = undefined;
console.log(typeof salary);

// output:
undefined

As you can see the “data type” of undefined is also undefined. So is undefined itself a data-type.

In JavaScript, undefined is a primitive data type that represents the absence of an assigned value.

6. 🫙Null🫙:

The null value represents the intentional absence of value in a variable. It is often used when a variable is explicitly set to have "no value."

Here’s an example:

let userProfile = null; // No profile exists yet

📌 NOTE: null and 0 are different.

For example, if you search for the temperature of your area on a website and it fails to fetch the data, it will return null, indicating that no value is available.

However, if the temperature is 0°C, the API will return 0, because 0 is still a valid temperature.


let temperature = null; // No data available
let actualTemperature = 0; // Valid temperature (0°C)

This distinction is important, as null means "no data", while 0 is a legitimate numerical value.

Null vs Undefined:

At this point you might be confused by null and undefined and their differences. So let’s talk about it a bit.

Featurenullundefined
Typeobject (typeof null returns "object", which is a known JavaScript quirk)undefined
MeaningRepresents an intentional absence of valueRepresents an uninitialized variable or missing value
Assigned by?Manually assigned by developersAssigned by JavaScript when a variable is declared but not initialized
Examplelet user = null;let user; console.log(user); // undefined
Use CaseUsed when we want to explicitly indicate that a variable has no valueUsed when JavaScript automatically sets a variable as uninitialized

Non-Primitive data-type

1. 📃Array📃:

Array is a non primitive data-type. It is the collection of multiple data.

You can declare array in 3 ways:

1️⃣ Using Square Brackets []

let skills = ["Git", "HTML", "CSS", "Java Script"];

2️⃣ Using new Array() Constructor

let skills = new Array("Git", "HTML", "CSS", "Java Script")

3️⃣ Declaring an Empty Array and Adding Values Later

let skills = [];
skills.push("Git");
skills.push("HTML");
skills.push("CSS");
skills.push("Java Script");

It doesn’t matter how you declare, it will behave the same way.

Access Array elements:

Array elements’ position start from 0 and continue. It’s a convention that programmers follow.

Now to access array items you follow this syntax:

console.log(skills[0])         // Git
console.log(skills[2])         // CSS

2. 🚗Object🚗:

Object is one of the Non Primitive data type. Object is a data-type that can store multiple data like array, but here the data is in “key-value” pair form.

Treat object in programming like a real life object. An object has name, property and functionalities. It’s same here as well.

Here’s the most common way to declare an object:

let engineer = {
    name: "Rajib",
    age: 22,
    height: "181.5 cm",
    isMarried: false,
    skills: ["Git", "HTML", "CSS", "Java Script", "Backend", "Front End"]
}

As you can see the data in object item are in “key-value” pair form.

Access Object items:

You can access the object items in 2 different ways:

1️⃣ Using dot . property:

Here you use the objectName.propertyName syntax to access the value.

// Accessing object properties using dot notation
console.log(engineer.name)   // output: Rajib
console.log(engineer.age)    // output: 22

2️⃣ Using square brackets []:

Here you use the objectName.["propertyName"] syntax to access the value.

console.log(engineer["name"])   // output: Rajib
console.log(engineer["age"])    // output: 22

Both work the same way, so you can use whichever syntax you like.

Other ways to declare an object:

Using new Object():

This is same as declaring array and adding item by .push() method. Here you declare an object and then add items by following objectName.propertyName syntax.

let engineer = new Object();

engineer.name = "Rajib";
engineer.age = 22;
engineer.height = “181.5cm”;

Using a Constructor Function

function Person(name, age, isEmployed) {
  this.name = name;
  this.age = age;
  this.isEmployed = isEmployed;
}

let user1 = new Person("Rajib", 22, true);

To understand object using constructor you need to study constructor more in detail.

3. ⚒️Function⚓

Function is a block of reusable code. In JavaScript function is considered a non-primitive data-type. And it is stored by reference just like object and array.

Declaring a Function in JavaScript

There are multiple ways to declare functions:

1️⃣ Function Declaration (Named Function)

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

console.log(greet("ARajib")); // Hello, Rajib

2️⃣ Function Expression (Anonymous Function)

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

console.log(greet("Rajib")); // Hello, Rajib

3️⃣ Arrow Function

const greet = (name) => `Hello, ${name}`;

console.log(greet("Rajib")); // Hello, Rajib

You can use all the types based on requirement.

Conclusion:

In this article, we explored the different data types in JavaScript, covering their key characteristics and basic usage. Our goal was to provide an overview rather than an in-depth analysis of any single topic. However, we have covered enough to help you get started and build a strong foundation.

Remember, coding isn't something you can master just by watching tutorial videos or reading blog articles and documentation. The real learning happens when you write code yourself and gain hands-on experience.

So, go ahead and practice working with the data types we discussed. Experiment, make mistakes, and learn from them.

Happy coding! 🚀