Skip to main content

Building Blocks in JS

Data types in Javascript

Remember the box of Laddus we had from the article "Variables in Javascript"? Let me quickly help you remember. A variable is like a box, an empty box, the data we assign to it is the content, just like a box and Laddus inside it!

But do we store everything we have in the same box?

Imagine generated with Meta Imagine

Here we see Laddus on the paper box, water in a bottle, and chocolate in a wrapper cover. How would it be if we put Laddus in the bottle, water in the paper cover, and chocolate in a basket? It is just not right, isn't it?

Just like certain containers are meant for certain variables, we have different containers (boxes) for different kinds of data in programming as well.

Different Datatypes in Javascript

Javascript is a "dynamically typed" language, which means any datatype can be assigned to a variable and it automatically accepts the data type. The below example should help understand it better.

Primitive Data Types

Number: This type represents both integer and floating-point numbers. JavaScript does not differentiate between integers and floating-point numbers, and all numbers are of type Number. For instance, 42 and 3.14 are both Number types. Special numeric values include Infinity, -Infinity, and NaN (Not-a-Number), which is a result of undefined or erroneous mathematical operations.

let text = "Hello LearnYard";
text = 3.1415;
text = "3.1415";

In line 1, the type of the variable text is a string, in the second, it is a number, and in the third, it is a string again.

  • Infinity represents the mathematical Infinity (∞).
alert(100/0);

This brings up the alert that shows "Infinity". I would recommend you try this out in the console of your browser.

How to open the console

To open the console of the browser, refer to the article "Debugging" in the Javascript section.

If you are using a Chrome browser, right-click and use the inspect option and then click on the "console" option, alternatively, use ctrl + shift + C for Windows, for the mac use command + shift + C and then click on the "console" tab

  • NaN ( Not a Number ) represents a mathematical/computational error.

For example:

alert("Hello"/2);

Logically, this makes no sense, hence it is computationally wrong leading to NaN.

Note that any computation on NaN is also NaN.

BigInt: Introduced in ECMAScript 2020, BigInt is used for representing large integers that are beyond the range of the Number type. Unlike Number, BigInt can handle arbitrarily large values. For example, 9007199254740991n is a BigInt value.

It is safe to state that mathematical operations are safer in Javascript.

All the below operations do not let the script throw an error, the result could lead to NaN.

Note: Please give the above statements a try in your preferred JS editor or the browser console.

Although there is no error, since Javascript works mostly on the UI, computations leading to NaN can lead to a bad User experience, such as, say in Flipkart, the price of a product could be shown as NaN, which is a bad user experience. Hence ensuring safe calculations, and adding error guards are crucial in coding. More about handling errors will be discussed in future topics.

String: String is a data type that helps save text. Strings can be declared using quotes.

There are a couple of ways in which we can declare a string.

// Using double quotation marks
const str = "Hello";

// Using single quotes.
const hi = 'Hi';

// Using backticks
const hey = `Hey`;

The "backtick-way" of declaring a string is used when we need to use a variable to add a chunk of dynamic content to complete the string. The expression inside the ${<content>} is evaluated and it becomes a part of the string.

const greeting = "Hey";

const completeMessage = `${greeting} there!`; // Hey there!

Note that ${} works only inside of the backticks and they will not work inside of single and double quotes.

There is no practical difference between the single and double tick way of declaring the strings, they functionally serve the same purpose - i.e. to create a string. The choice is a personal preference most of the time.

Boolean

A boolean has only two values true or false . They play a crucial role in controlling the flow of logic within applications, particularly in conditional statements and loops ( more about loops and statements is discussed in the logical operators section ). In JavaScript, a Boolean value can be explicitly declared using the Boolean constructor or the literal keywords true and false. This data type is often employed in decision-making constructs like if, while, and for loops to execute code based on specific conditions.

const isTrue = new Boolean(true)
const allowAccess = true;

if(allowAccess) {
  return "Login successful";
};

Let's consider the above code where allowAccess is a boolean with a value of true assigned to it. The code inside the if statement will only work if the value is true. Otherwise, the code is skipped during execution.

Interestingly, JavaScript has a concept called "truthy" and "falsy" values which extends the use of Booleans. While true and false are explicit Boolean values, JavaScript also evaluates other data types based on their inherent truthiness or falsiness in conditional expressions. For example, an empty string (""), 0, null, undefined, and NaN are considered falsy and will evaluate to false in conditional statements, whereas most other values, including objects, arrays, and non-zero numbers, are considered truthy and will evaluate to true.

If the data is logically positive, it is "truthy", else it is "Falsy".

Symbol:

The Symbol data type in JavaScript is a unique and immutable primitive value introduced in ECMAScript 6 (ES6) that is primarily used as a unique identifier for object properties. Each Symbol is guaranteed to be unique and distinct from any other value, including other Symbols. This feature makes Symbols particularly useful for defining property keys that are not intended to clash with other property names, even if those names are added dynamically or by third-party libraries. For example, const uniqueSymbol = Symbol('description'); creates a new Symbol that can be used as a key in an object without risk of name collision ( that is the same name being given for two items ).

Although symbols are used in multiple instances, The mdn documentation clearly states the purpose of the symbol as "The purpose of symbols is to create unique property keys that are guaranteed not to clash with keys from other code". Which means that a symbol is to be used to create unique identifiers. Read more about symbols here.

Essentially a symbol helps create a unique key.

Example:

const uniqueSymbol = Symbol('description');

Note:

const s1 = Symbol();
const s2 = Symbol();
console.log(s1 === s2); // false

Undefined:

Undefined represents the absence of a value. When a variable is created without initiating a value to it, it is undefined .

let name;

The value of name would be undefined. I would recommend you to try running the above code and evaluate for yourself. We could assign undefined specifically to a variable but is not recommended, if we need to explicitly assign a falsy value, null is the go-to.

Note: The type of undefined is undefined

Null:

Null represents the absence of an object. It is one of the primitive types and is a falsy value, that means the conditional statement we discussed about earlier would not be executed if allowAccess is set to null. To explicitly state the absense of a value or an object, use null.

Type of null is object.

Null vs Undefined:

In JavaScript, null and undefined are distinct types used to represent the absence of value or an uninitialized state, but they serve different purposes and convey different meanings. undefined is the default value assigned to a variable that has been declared but not yet initialized or to a function parameter that hasn't been provided an argument. It is also the return value of functions that do not explicitly return anything.

On the other hand, null is a special value that is explicitly assigned to a variable to indicate that it is intentionally empty or lacks a value. It is often used to represent the intentional absence of any object value, as opposed to simply not having been set yet.

Let's look at a few scenarios below:

typeof null; // "object"
typeof undefined; // "undefined"
null === undefined; // false
null == undefined; // true
null === null; // true
null == null; // true
!null; // true
undefined === undefined; // true
undefined == undefined; // true
!undefined; //true

Note: Be careful while using == versus === in Javascript. The former performs type conversion while the latter does not. More about this is discussed in the operators section.

== checks the value only while === operator checks both type and value.

Non-primitive data types:

Objects

Objects in detail are covered in the Objects section but let's understand about what they are in brief in this blog.

Definition: In computer science, an object is a value in memory that is possibly referenced by a variable/entity.

Objects are called the non-primitive data type. What is so "non-primitive" about them?

While all other types can hold just a single value, like a string holds a string value, a boolean holds either true or false, not both at a time, etc. An object is like a container that can hold multiple things. Imagine it like a bag. You can almost fill a bag with anything that can possibly fit inside of it, right?

Just like we put our laptop, books, pen, Jacket, earphones, and multiple entities in a bag while the bag on its own has no direct relationship with these items, just as so, an object is a complex entity that enables us to store multiple primitive and nonprimitive data inside of it. A bag can have a bottle and a book (primitive) or another smaller bag inside of it which again holds a pen and the left out laddu from the other box?

const obj = {
  name : "Shrikanth",
  age: 28,
  gender: "male",
  address : {
    city: "Bengaluru",
    state: "Karnataka"
  }
}

Here as we see, an object can have a primitive type such as name which is a string, but address here is again a non-primitive data type which is again an object - a bag inside a bag!

The type of an object is object .

I hope this blog helped you understand the data types in Javascript better! Let's move on!