2.3 JavaScript Data Types: The Building Blocks of Programming

19 min read

In the previous lesson, we delved into the concepts of values and variables in JavaScript. Now, in this lesson “JavaScript Data Types,” let’s explore the idea that in every programming language, values can assume different types based on the kind of data they represent.

We’ve already encountered strings and numbers, but there’s a diverse range of JavaScript Data Types. Let’s take a closer look at them.

JavaScript Data Types

In JavaScript, every value essentially falls into one of two categories: it’s either an object or a primitive value.

Primitive Data Types

Primitive values are the focus of our attention for now. They are simple, immutable values. Here are the seven primitive data types in JavaScript:

  1. Number: This data type handles both integers and floating-point numbers. Even whole numbers like 23 are considered floating-point numbers, like 23.0.
   let personAge = 23;
  1. String: Strings are used to represent sequences of characters and are enclosed in either single (') or double (") quotes. For example:
   let firstNamePerson = "Amit";
  1. Boolean: Booleans can only be true or false. They are fundamental for making decisions in code.
   let fullAge = true;
  1. Undefined: Undefined represents a value assigned to a variable that hasn’t been defined or given a value yet.
   let children;

Undefined signifies an empty value or a variable that’s not yet initialized.

  1. Null: Null also denotes an empty value, but it’s used in different contexts.
   let someValue = null;
  1. Symbol (ES2015): Symbols introduce unique and unchangeable values. While not frequently used, they have their applications.
   let uniqueSymbol = Symbol("description");
  1. BigInt (ES2020): BigInt is designed to handle extremely large integers that can’t be represented by the Number type.
   let largeNumber = 1234567890123456789012345678901234567890n;

What is Dynamic Typing in JavaScript?

One crucial aspect of JavaScript is its dynamic typing. Unlike many other programming languages where you explicitly declare the data type of a variable, JavaScript automatically determines the data type of a value when it’s stored in a variable.

In JavaScript, it’s the value that has a type, not the variable itself. This means that you can reassign a variable with a different data type at any point in your code, making it incredibly flexible but potentially leading to unexpected results or errors if not managed carefully.

Now, let’s see these principles in action. Before we dive into data types, we’ll briefly cover code commenting.

ALSO READ:  2.6 Operator Precedence in JavaScript: Order of Operations

Code Commenting

In programming, comments are used to annotate code for clarity or to temporarily deactivate sections of code without deleting them. You can write single-line comments using // or multi-line comments using /* ... */.

For instance:

// This is a single-line comment.

   This is a
   multi-line comment.

Commented code is ignored by JavaScript, and it’s a useful practice for documenting and maintaining your code.

In the next sections, we’ll explore each of these data types in more detail, illustrating their usage and dynamic typing in various examples.

Understanding JavaScript Data Types with examples

1. Number and string

Let’s delve back into the realm of data types. In a previous lesson, we explored numeric data types like this:

let PI = 3.1415; // Here, we have a number.

But what if we want to store text instead? We can do so using string data types, like this:

let myFirstJob = "Programmer";
let myCurrentJob = "Teacher";
// Here, we have two values, "Programmer" and "Teacher," both of which are strings.

2. Booleans

Moving on, let’s discuss Booleans, which can only be either true or false. If we write true, it automatically becomes a Boolean value, like this:

// We can also log this in the console to verify it's not a string.
console.log(true); // true

You can store Booleans in variables as well. For example:

let javaScriptIsFun = true;
console.log(javaScriptIsFun); // This variable holds a Boolean value.

Remember, it’s the value that determines the data type, not the variable itself. So, you can change the type of a variable, as shown here:

javaScriptIsFun = "true";
console.log(javaScriptIsFun); // true
javaScriptIsFun = false; // Now it's a Boolean again.

3. typeof operator

Now, let’s introduce a special operator called typeof. It’s similar to arithmetic operators like + or -, but it reveals the data type of a value:

console.log(typeof true); // boolean
console.log(typeof false); // boolean

We’ll explore operators in more detail later in the tutorial. For now, understand that typeof returns a string indicating the type of the value it’s used on.

What are arithmetic operators like + or -?

Arithmetic operators in JavaScript, such as + (addition) and – (subtraction), are symbols used to perform mathematical operations on numeric values. These operators allow you to manipulate numbers in various ways within your JavaScript code.

Here’s a brief overview of some common arithmetic operators:

Addition (+): The addition operator is used to add two or more numbers together. For example, 2 + 3 will result in 5.

Subtraction (-): The subtraction operator is used to subtract one number from another. For example, 5 - 2 will result in 3.

Multiplication (*): The multiplication operator is used to multiply two or more numbers. For example, 3 * 4 will result in 12.

Division (/): The division operator is used to divide one number by another. For example, 10 / 2 will result in 5.

Modulus (%): The modulus operator is used to find the remainder of a division operation. For example, 10 % 3 will result in 1 because 10 divided by 3 is 3 with a remainder of 1.

ALSO READ:  2.11 Type Conversion and Coercion in JavaScript

Exponentiation (): The exponentiation operator is used to raise a number to a power. For example, 2 ** 3 will result in 8 because it’s equivalent to 2 raised to the power of 3.

These arithmetic operators are fundamental for performing mathematical calculations and are often used in various JavaScript applications, from simple calculations to more complex mathematical algorithms.

What are the Special numbers?

In JavaScript, there are three special values classified as numbers, but they exhibit unique behaviors distinct from regular numbers. The first two special values are Infinity and -Infinity, representing positive and negative infinities, respectively. When you perform mathematical operations involving these values, they remain unchanged; for instance, Infinity – 1 still results in Infinity. However, it’s important to note that relying too heavily on computations involving infinity can lead to issues because such calculations are not mathematically rigorous.

The third special number is NaN, which stands for “not a number.” Surprisingly, NaN is categorized as a value of the number type, even though it doesn’t behave like typical numbers. You encounter NaN when attempting calculations that do not produce a meaningful result, such as dividing zero by zero (0 / 0), subtracting Infinity from Infinity (Infinity – Infinity), or engaging in other numeric operations that lack a well-defined outcome.

In summary, these special numbers, Infinity and -Infinity, represent positive and negative infinities but have limitations in mathematical precision. NaN, on the other hand, signifies situations where numeric operations fail to provide a valid result, making it a valuable indicator of such scenarios in JavaScript.

To further illustrate, let’s apply typeof to different values:

console.log(typeof javaScriptIsFun); // boolean
console.log(typeof myFirstJob); // string
console.log(typeof 27); // number
console.log(typeof "Amit"); // string

As you can see, it correctly identifies the data types.

4. Matching quotes (single or double) to create a string

Speaking of strings, remember to always use matching quotes (single or double) to create a string. For example:

console.log("Amit"); // This is a string.

Using mismatched quotes, like "Amit', will lead to an error.

console.log("Amit'); // Uncaught SyntaxError: Invalid or unexpected token

In this line, there’s a mismatch of quotes. The string starts with a double quote (") but ends with a single quote ('). In JavaScript, strings must have matching quotes to define the beginning and end of the string. To fix this, you should use the same type of quote at both ends, either single or double. For example:

console.log('Amit'); // Amit
console.log("Amit"); // Amit

Without quotes, JavaScript will interpret the text as an undefined variable:

console.log(Amit); // Uncaught ReferenceError: Amit is not defined

In this context, Amit is assumed to be a variable. JavaScript treats anything without quotes as a variable. It is attempting to access the value stored in the variable Amit and print it to the console. The, “Uncaught ReferenceError: Amit is not defined,” error message that appears when the code is executed. It tells us that JavaScript couldn’t find a variable named Amit in the current scope. In other words, Amit has not been declared or defined anywhere in the code.

ALSO READ:  2.12 Truthy and Falsy Values in JavaScript

5. Observing Dynamic Typing

Now, let’s observe dynamic typing in action. Dynamic typing means we can easily change the data type of a variable. For example:

javaScriptIsFun = "Yes!";
console.log(typeof javaScriptIsFun); // string

Initially, javaScriptIsFun was a Boolean, but we changed it to a string.

6. undefined and null

Next, consider the concept of “undefined.” While there are various data types like numbers, strings, and Booleans, there are also undefined and null. In this lesson, we’ll focus on these three primary types and briefly touch on undefined and null.

Undefined signifies that a variable exists but has no assigned value. It’s legal to declare a variable without initializing it, like this:

let jobTitle;
console.log(jobTitle); // undefined
console.log(typeof jobTitle); // undefined

Whenever you declare an empty variable, it holds the value of undefined, and its type is also undefined. Although this may sound confusing, undefined serves as both the value and type for such variables. However, this detail isn’t critical to grasp.

You can assign a new value to such variables later, like this:

jobTitle = "Developer"; // Now it holds a string.
console.log(jobTitle); // Developer
console.log(typeof jobTitle); // string

It’s essential to be aware of an unusual behavior regarding the typeof operator. When applied to null, it incorrectly returns “object” instead of “null”:

console.log(typeof null); // object

This behavior is a long-standing bug in JavaScript and isn’t corrected due to legacy code compatibility. Keep this quirk in mind when working with the typeof operator.

That covers the fundamentals of JavaScript data types.

Discussion of JavaScript Data Types FAQs

Keep in mind that the process of learning is dynamic, and it’s completely normal to have inquiries. As you embark on your learning journey, you may come across questions or uncertainties. To provide guidance as you navigate this educational path, we’ve compiled a set of Frequently Asked Questions (FAQs) related to JavaScript Data Types. Embrace this chance to expand your knowledge, delve into new insights, and evolve as you advance through your lessons and engage with the FAQs.

Avatar for Amit

Amit (16)

Hello! I'm Amit Kumar, a passionate teacher specializing in web development and digital marketing. With several years of experience in the industry, I am dedicated to sharing my knowledge and expertise to empower aspiring learners like you.

Teaching Philosophy:

I believe in creating a dynamic and engaging learning environment where students can thrive. My teaching approach focuses on hands-on experience, practical applications, and real-world examples. I strive to make complex concepts understandable and enjoyable, ensuring that you not only grasp the fundamentals but also develop the skills necessary to excel in web development and digital marketing.

Web Development Expertise:

As a web development instructor, I am well-versed in HTML, CSS, JavaScript, and various frameworks such as React and Angular. I will guide you through the process of building responsive and user-friendly websites, exploring topics like front-end development, back-end integration, database management, and more. Together, we will delve into the latest trends and best practices in web development, equipping you with the tools to create stunning online experiences.

Digital Marketing Mastery:

In the rapidly evolving digital landscape, digital marketing is crucial for businesses to thrive. Through my digital marketing courses, I will help you navigate the intricacies of search engine optimization (SEO), social media marketing, content strategy, email marketing, and analytics. Gain insights into effective marketing techniques, harness the power of data-driven decision-making, and learn how to craft compelling campaigns that drive results.

Passion for Teaching:

Teaching is not just a profession for me; it's my passion. I find great joy in witnessing my students grow and succeed. I am committed to fostering a supportive learning community where questions are encouraged, ideas are shared, and challenges are overcome together. I am here to guide you every step of the way and provide the necessary resources for your personal and professional development.

Join me on this exciting journey of learning and discovery. Let's unlock your potential in web development and digital marketing together. Enroll in my courses today and embark on a transformative educational experience that will propel your career forward.
Start Learning Today!

5 1 vote
Article Rating
Notify of


Inline Feedbacks
View all comments
Would love your thoughts, please comment.x
Scroll to Top