If you‘re just getting started with JavaScript, understanding the different data types is crucial for writing effective code. In this comprehensive guide, we‘ll explain primitive and non-primitive data types in plain English with plenty of examples so you can master these concepts.
What are Data Types?
In programming, a data type simply refers to the type and format of data being stored and manipulated. They act as blueprints that determine what operations can be performed on different data values.
For example, you can add two numbers together but cannot add a string and a number. The data type provides those rules for the values.
Primitive vs Non-primitive Data Types
The main difference lies in their mutability.
Primitive data types are immutable, meaning the values cannot be altered once assigned. Some examples include numbers, strings, booleans, etc.
Non-primitive data types are mutable or changeable. These include more complex types like objects and arrays.
Another key difference is, primitive data types are passed by value while non-primitives are passed by reference. We‘ll expand more on this later.
Now let‘s look at the primitive data types in JavaScript.
Primitive Data Types
1. Number
The number data type represents numeric values – integers, floating point numbers, Infinity, -Infinity. Some examples:
let age = 30 // integer
let price = 29.99 // floating point number
let bigNum = 4567890n // BigInt
You can perform all basic math operations on number data type. But there are some intricacies to keep in mind:
- Integer values have a max safe value of 2^53 – 1. Beyond that precision may be lost.
- Floating point numbers cannot accurately represent most fractional values (0.1 + 0.2 ≠ 0.3) due to how they are stored in binary format. This can cause precision errors.
To control precision, functions like Number.EPSILON
and Number.MAX_SAFE_INTEGER
can be used.
2. String
The string data type consists of text values – letters, numbers, special characters, whitespace enclosed within single or double quotes:
let greeting = "Hello world!"
let name = ‘John‘
Strings are immutable, meaning the contents cannot be changed after creation. But you can concatenate strings with the + operator to form a new string.
Useful methods are available on the string prototype like length
, indexOf
, slice()
, etc. to manipulate string values.
3. Boolean
The boolean data type represents logical or truth values – true
or false
. For example:
let isPublic = true
let isValid = false
It is commonly used for conditional testing and flow control in code using if...else
statements and boolean operators like &&
and ||
.
4. undefined
The undefined data type represents the absence of a value though a variable has been declared. By default, unassigned variables have a value of undefined:
let name
console.log(name) // undefined
Trying to access properties of undefined variables will result in errors so checks should be made before using them.
5. null
Similar to undefined, null also represents the absence of a value though it is set deliberately to indicate ‘no value‘:
let guest = null
// deliberately no guest right now
The main difference between null and undefined is that null is an assignment value while undefined is type.
6. Symbol
The symbol data type was introduced in ES6. Symbols are unique, immutable and can be used as object property identifiers:
let sym1 = Symbol(‘symbol‘)
let sym2 = Symbol(‘symbol‘)
sym1 === sym2 // false - symbols are unique
This prevents property name collisions in objects. Symbols also support methods like toString()
and valueOf()
.
7. BigInt
BigInt is used to represent large integer values which cannot be accurately stored with the Number data type due to precision:
const value = 900719925124740998n
const bigNum = BigInt(900719925124740998)
value + 1n // 900719925124740999n
Mathematical operators like +, -, *, / can be used with BigInts. But BigInts cannot be mixed with regular numbers.
These are the primitive data types available in JavaScript. Now let‘s look at non-primitive types.
Non-primitive Data Types
Non-primitive data types comprise of objects and arrays. They have methods and properties associated with them and are mutable in nature.
Objects
Objects represent a collection of properties enclosed within curly braces { }
. We can store data values along with functions inside an object:
const person = {
name: "John",
age: 26,
greet: function() {
console.log(`Hello!`)
}
}
person.greet() // Hello
New properties can also be added or modified on objects dynamically. They provide a simple structure to store records and complex entities.
Since objects are passed by reference, multiple variables can reference the same object in memory. Changes made through one variable therefore reflect in all of them.
Arrays
Arrays represent ordered collections of values enclosed within square brackets []
:
let fruits = [‘apple‘, ‘orange‘, ‘banana‘]
let mixed = [ 10, ‘hello‘, true]
Arrays are also objects at the core and support methods like push
, pop
to mutate themselves. While arrays can hold mixed data types, it is best to keep them homogeneous for easier manipulation.
Arrays have a length
property to indicate the number of stored items. Using the index position, individual elements can be accessed, added or removed from them.
Best Practices for Data Types
Here are some handy best practices to keep in mind while working with data types:
- Use strict equality checks (===) instead of loose equality checks (==)
- Initialize variables properly to avoid undefined errors
- Use built-in functions like
parseInt
,parseFloat
for type conversion instead of relying on implicit coercion - Check for null or undefined before accessing properties to avoid errors
- Keep arrays and objects homogeneous for easier iteration
And that wraps up the essential concepts around data types in JavaScript! Let‘s move on to some frequently asked questions around these topics…
FAQs around Primitive and Non-primitive Data Types
What is the main difference between primitive and non-primitive data types in JavaScript?
The main differences are:
- Mutability – Primitive data types are immutable while non-primitives are mutable
- Passing mechanism – Primitives are passed by value while non-primitive types like objects and arrays are passed by reference
What is better TypeScript or JavaScript for data types?
TypeScript builds on JavaScript and provides static typing of variables. This means data types in TypeScript are explicitly declared during development while JavaScript uses dynamic or duck typing to determine types during execution.
TypeScript catches many bugs during development due to strict typing while JavaScript data type errors may fail during runtime. TypeScript thus provides better code quality in complex applications.
Should I use == or === equality comparisons in conditional checks in JavaScript?
Always use strict equality checks (===) instead of lose checks with ==.
The == operator does type coercion so values may match unexpectedly. The === ensures values and types are both equal avoiding weird behavior from type coercion.
I hope this article helped explain the fundamental data types in JavaScript for you. Understanding them well will help prevent entire classes of errors. Happy coding!