Understanding Data Types and Conversion in JavaScript

Data Types in JavaScript

JavaScript works with different kinds of values. Each value has a type, known as a data type. These types help JavaScript decide how the value should behave when used in your code.

You do not need to declare data types in JavaScript. It is a dynamically typed language.

That means the type of a variable can change at runtime. This makes JavaScript flexible, but it also brings hidden problems when you do not handle types correctly.

JavaScript has many data types, which can be categorized into two main groups: primitive types and reference (or non-primitive) types. Let’s take each one in-depth.

Primitive Data Types in JavaScript

JavaScript has a few simple, basic data types. These are not objects. They hold single values.

Here is the list:

  • Number
  • String
  • Boolean
  • Undefined
  • Null
  • Symbol
  • BigInt

Let’s take a look at each one in detail.

Number

JavaScript uses one type to store all numbers. That includes integers and decimals. It also handles edge cases like division by zero or invalid math with:

  • Infinity
  • -Infinity
  • NaN (Not a Number)

You can store whole numbers or decimals in the same type. For example:

let balance = 100.00000000000001 - 0.00000000000001;
console.log(balance);

This prints 100 because it has a floating-point rounding.

String

Strings are text. They are written with single quotes or double quotes. Or even backticks. Here is a list that shows you an example for each one:

  • 'cat'
  • "dog"
  • `bird`

You can assign them to variables like this in JavaScript:

let fruit = 'apple';
let taste = `This ${fruit} tastes sweet.`;
console.log(taste);

The backticks allow expressions inside ${}.

Boolean

Booleans have two values: true or false. They help with decisions and control flow. Here is an example:

let hasWater = true;
let isThirsty = false;
console.log(hasWater && !isThirsty);

This prints true because the person has water and is not thirsty.

Undefined

A variable you declare but do not assign has the value undefined.

let temperature;
console.log(typeof temperature);

This prints "undefined" because no value was given.

Null

The null means an intentional empty value. It shows that a value is missing on purpose.

let response = null;
console.log(response === null);

This prints true. The value is set to nothing by choice.

Symbol (ES6)

Symbols are new and unique. You use them to create hidden object properties.

For example:

let secret = Symbol('id');
let person = {};
person[secret] = 123;
console.log(Object.keys(person));

This prints [] because the Symbol key is not visible.

BigInt (ES11)

Use BigInt when numbers go beyond safe integer limits.

For example:

let big = 9007199254740991n + 2n;
console.log(big);

This prints 9007199254740993n. It would not be safe without BigInt.

Now that you saw primitive types, let’s move to the next group: non-primitive types.

Non-Primitive (Reference) Data Types in JavaScript

These types hold collections or more complex values. They are stored by reference.

Here is the list:

  • Object
  • Array
  • Function
  • Date
  • RegExp
  • Others

Let’s explain each one in depth.

Object

Objects store key-value pairs. Each key maps to a value.

For example:

let settings = {
  darkMode: true,
  fontSize: 16,
};
console.log(settings.darkMode);

The value is accessed using the key.

Array

Arrays store items in order. You can reach them by index. Here is an example:

let books = ['JS Basics', 'JS Advanced'];
console.log(books[1]);

This prints the second book title.

Function

A function is a block of code. You can call it by name.

function greet(name) {
  return 'Hi ' + name;
}
console.log(greet('Sam'));

This prints "Hi Sam".

Functions are also objects. You can assign properties to them.

Date, RegExp, etc.

Date helps with time. RegExp works with patterns.

let now = new Date();
let match = /cat/.test('catalog');
console.log(now, match);

The first part shows the time. The second checks for a pattern.

typeof Operator in JavaScript

The typeof operator tells you the type of a value. Here is the syntax:

typeof variable

You use it to debug and check types.

Common results:

  • 'string'
  • 'number'
  • 'boolean'
  • 'undefined'
  • 'object'
  • 'function'

Quirks:

console.log(typeof null); // "object"

This is a known bug in JavaScript.

Type Conversion (Type Coercion) in JavaScript

JavaScript changes types automatically in many cases. You can also do it by hand.

Implicit conversion:

JavaScript converts values during operations. For example:

console.log('4' * 2); // 8
console.log(false + 1); // 1

Explicit Conversion:

You can force a type change. Here are function examples:

  • Number()
  • String()
  • Boolean()
  • parseInt()
  • parseFloat()

Truthy and Falsy Values

JavaScript treats some values as false in logic. Here are false values:

  • false
  • 0
  • ""
  • null
  • undefined
  • NaN

All other values are truthy.

Special Cases and Gotchas

  • NaN === NaN is false
  • null == undefined is true, but not strict
  • JavaScript wraps primitives like strings and numbers in objects when needed
  • Mixed types in math cause odd results
console.log('5' - true); // 4

Examples of JavaScript Data Types

Storing screen size with BigInt:

let screenPixels = 1920n * 1080n;
console.log(screenPixels);

This handles large integer math without rounding.

Function inside object

let user = {
  name: 'Ana',
  greet: function () {
    return 'Hello, ' + this.name;
  }
};
console.log(user.greet());

The object stores both data and behavior.

Data Conversion Examples in JavaScript

Number to String:

let age = 30;
let ageText = String(age);

This turns the number into '30'.

String to Boolean:

let input = 'yes';
let active = Boolean(input);

Any non-empty string becomes true.

Object to Primitive:

let user = {
  valueOf: () => 5
};
console.log(user + 2);

valueOf gives a number, so the result is 7.

Array to String/Number:

let ids = [1, 2, 3];
console.log(String(ids), Number(ids));

String becomes '1,2,3', number becomes NaN.

Wrapping Up

In this article, you learned what data types exist in JavaScript and how to convert them. You saw both simple and complex types, along with special cases.

Here is a quick recap:

  • JavaScript types include primitives and non-primitives
  • typeof checks a value’s type
  • JavaScript converts values automatically and manually
  • Watch out for quirks like typeof null

FAQs

What are the main data types in JavaScript?

They include Number, String, Boolean, Undefined, Null, Symbol, BigInt, Object, Array, and Function.

Why is typeof null an object?

It is a bug in JavaScript from early versions. It remains for backward compatibility.

What is the difference between undefined and null?

undefined means no value was set. null means the value is empty on purpose.

How does JavaScript convert types automatically?

It uses rules based on the context, like math or comparisons.

What is a truthy value?

Anything that is not one of the falsy values: false, 0, "", null, undefined, or NaN.
Previous Article

JavaScript Functions: How to Create Functions in JavaScript

Next Article

How to Remove the Last Character from a String in PHP

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.