Skip to content

Primitive and Non-primitive Data Types in JavaScript: Explained in Plain English

A Brief History of Data Types in JavaScript

JavaScript was created in 1995 by Brendan Eich. The first version had only primitive data types like numbers, strings, and booleans. Over time, with the introduction of ECMAScript standards, more data types and capabilities were added.

ECMAScript 2015 (ES6) introduced Symbols and template literals for strings. ECMAScript 2020 brought BigInt for safer mathematical operations on large numbers. Non-primitive data types like objects and arrays were also added early on.

So in summary, JavaScript started simple but has evolved to support more complex data structures and capabilities required for modern web development.

What Are Primitive and Non-primitive Data Types?

In JavaScript, a data type defines what kind of data can be stored and manipulated in a program.

They are broadly divided into two categories:

Primitive Data Types

Primitive data types are basic building blocks and havefixed values stored directly in the location the variable accesses.

Primitive data types are immutable. This means their values cannot be altered once assigned.

For example:

let x = 10;
x = 20; // allowed
x.someMethod(); // not allowed, primitive types don‘t have methods

The 7 primitive data types in JavaScript are:

  • Number
  • String
  • Boolean
  • null
  • undefined
  • symbol (new in ES6)
  • BigInt (new in ES2020)

Non-primitive Data Types

Non-primitive data types can store collections of data like arrays and more complex entities like objects.

They are mutable, meaning their contents can be changed after creation.

For example:

let person = {
  name: "John"  
};

person.name = "Jane"; // This works! We can change property values

The 2 most used non-primitive data types are:

  • Object
  • Array

Now let‘s explore the primitive data types in more detail with examples.

Diving Deep into JavaScript‘s Primitive Data Types

Numbers

The number data type in JavaScript represents both integers and floating point numbers like:

let count = 10; // Integer
let price = 9.99; // Floating point number

Some special number values are:

  • Infinity – Represents infinity 💫
  • -Infinity – Represents negative infinity
  • NaN – Represents an error/invalid number

Here‘s an example with these special values:

let maxNumber = Infinity;
let crazyMath = 10 / ‘Apple‘; // Gives NaN

You can check for NaN using the isNaN() function:

let crazyMath = 10 / ‘Apple‘;

console.log(isNaN(crazyMath)); // Logs true

Type Conversion with Numbers

You can convert other data types to numbers using:

  • Number() – Converts string, boolean, etc to number
  • parseInt() – Convert string to integer
  • parseFloat() – Convert string to float

Here are some examples:

Number(‘10‘); // Returns number 10
parseInt(‘12.93‘); // Returns integer 12
parseFloat(‘12.93‘); // Returns float 12.93

Strings

The string data type contains text expressed as a sequence of UTF-16 code points wrapped in single quotes, double quotes or backticks.

For example:

let message = ‘Hello world‘;
let name = "Bob";
let greeting = `Welcome ${name}!`; 

You can use special character escape sequences like \n for new line as well.

Some useful string methods are:

  • length – Get string length
  • includes() – Check if substring exists
  • slice() – Extract substrings
  • toUpperCase() – Convert to upper case

Here are some examples of using these methods:

let str = ‘Hello world!‘;

str.length; // 12
str.includes(‘Hello‘); // true
str.slice(0, 5)); // ‘Hello‘ 
str.toUpperCase(); // ‘HELLO WORLD!‘

Type Conversion with Strings

You can convert other data types to strings using the String() function.

Here are some examples:

String(12); // returns string "12"
String(true); // returns string "true"
(100).toString(); // returns string "100"

Boolean

The boolean data type represents logical values – true or false.

It‘s helpful for evaluating conditions and controlling program flow like in if...else statements.

For example:

let loggedIn = true;
let hasPosts = false; 

if (loggedIn) {
  // Show admin panel
} else {
  // Show login
}

In JavaScript, these falsy values evaluate to false:

  • Empty string
  • null
  • undefined
  • NaN

You can also get booleans by comparing values, for example:

10 > 5; // Evaluates to true 
10 == 5; // Evaluates to false

Type Conversion with Booleans

You can convert data types to boolean using the Boolean() function:

Boolean(0); // false
Boolean(‘‘); // false
Boolean(‘Hello‘); // true

null

The null data type represents intentional absence of a value. It is typically used to indicate:

  • A variable is empty or has no value yet
  • An object is purposefully set to have null value

For example:

let empty = null;

let person = {
  name: ‘Bob‘,
  age: null 
}; 

null is different from…

undefined – Which means a variable has been declared but not defined yet

false – Which has a boolean value

So in summary – use null when you intentionally want something to have no value.

undefined

A variable in JavaScript is undefined before a value is assigned.

For example:

let score;
score; // evaluates to undefined

Undefined can also mean a property does not exist on an object or a function did not have a return value.

For example:

let person = { };
person.age; // undefined

function getName() { } 
getName(); // No return, so undefined

Remember undefined is different from…

null – Which is an intentional empty value

false – Which is a boolean value

So in summary – a variable/property is undefined if no value exists for it yet.

symbol

The symbol data type was introduced in ES6.

It represents a unique identifier that can‘t be changed. You create symbols using Symbol():

let id = Symbol(‘user id‘);

Symbols let you add unique property keys to objects that won‘t conflict with existing keys.

For example:

let user = {
  name: ‘John‘
};

let id = Symbol(‘id‘);

user[id] = 12345;
console.log(user[id]); // Access symbol property 

BigInt

The BigInt data type represents integers with arbitrary precision.

You define BigInt literals by adding n to then end of an integer:

const bigNumber = 1234567890123456789012345678901234567890n;

BigInt allows you to safely store and operate on large integers beyond the Number max value.

Certain operations like bitwise operators don‘t work with BigInt. You also can‘t mix BigInt and Number data types.

Working with JavaScript‘s Non-primitive Data Types

Now let‘s explore the two most commonly used non-primitive data types – objects and arrays.

Object

The object data type represents complex structured data. Objects store key-value pairs and can contain properties and methods.

An object literal looks like:

let person = {    
  name: ‘John‘,
  age: 30,
  greet: function() {
    console.log(‘Hello!‘); 
  }
}

person.greet(); // Call greet method

You can access properties using dot notation like person.name or bracket notation like person[‘name‘].

Some useful Object methods are:

  • Object.keys() – Get object keys
  • Object.values() – Get object values
  • Object.entries() – Get keys + values

Here‘s an example using these:

const person = {
  name: ‘John‘,
  age: 30
};

Object.keys(person); // [‘name‘, ‘age‘]  
Object.values(person); // [‘John‘, 30]
Object.entries(person); // [[‘name‘, ‘John‘], [‘age‘, 30]]

You‘ll likely use objects to structure data in your apps.

Array

The array data type represents ordered data stored in list. Array elements can be any data type.

You define arrays with square brackets []:

let fruits = [‘Apple‘, ‘Banana‘, ‘Orange‘];

let mixed = [10, ‘Hello‘, true]; 

You access array elements using indexes starting from 0:

let fruits = [‘Apple‘, ‘Banana‘, ‘Orange‘];

fruits[0]; // ‘Apple‘ 
fruits[1]; // ‘Banana‘

Some useful Array methods and properties are:

  • length – Get array length
  • join() – Join elements into string
  • slice() – Extract subarray section
  • push()/pop() – Add/remove from end
  • shift()/unshift() – Remove/add from start

Here are examples using these methods:

fruits.length; // 3
fruits.join(‘-‘); // ‘Apple-Banana-Orange‘
fruits.slice(0, 2); // [‘Apple‘, ‘Banana‘] 
fruits.push(‘Strawberry‘); // Add to end 
fruits.shift(); // Remove Apple from start

Arrays make working with ordered data easy.

Best Practices for Working with Data Types

Here are some tips for working with data types efficiently:

✅ Use strict equality checks (===) instead of loose equality checks (==) whenever possible.

✅ Initialize variables – let count = 0; vs just let count; to avoid unexpected undefined values.

✅ Use parsing functions like parseInt and parseFloat to convert from string to number types explicitly.

✅ Check for undefined or null values before accessing properties to avoid errors.

For example:

let user;

if (user !== undefined) {
  console.log(user.name);  
}

✅ Ensure arrays have homogeneous elements to make iteration easier.

✅ Use built-in methods and helpers like Array.isArray, Number.isInteger rather than trying to check types manually.

Following these best practices will help you avoid frustrating bugs!

Key Takeaways

  • JavaScript has 7 primitive data types: Number, String, Boolean, Undefined, Null, Symbol and BigInt.
  • And 2 commonly used non-primitive data types: Object and Array
  • Primitive types store immutable values directly in the variable.
  • Non-primitive types like objects and arrays are mutable collections of values.
  • Use strict equality checks and value initialization to avoid bugs.

I hope this article helped you learn about the different JavaScript data types with easy-to-understand explanations and examples! Let me know if you have any other questions.

Frequently Asked Questions

What is the key difference between primitive and non-primitive data types?

Primitive data types store fixed single values directly in the variable‘s memory location. Non-primitive data types store references to objects that have mutable collections of values.

What‘s the difference between null vs undefined?

Null represents an intentional absence of a value, while undefined represents the default value before initialization. Use null when you want something to explicitly have no value.

Should I use == or === for comparisons?

Prefer triple equals === for strict equality checks whenever possible. == does type coercion which can lead to unexpected results.

I hope these primitive and non-primitive JavaScript data type explanations were helpful! Let me know if you have any other data type questions.