Introduction
In this article, we are going to learn all you need to become a master in data types which is the most important language of the web. We shall get to know their importance, how they affect variable declaration, the various types and their uses, and how to convert from one data type to another. Understanding all we are going to cover will never leave you the same, I assure you of that as we are going to see.
PRE-REQUISITES
For you to get the most out of this article, you will need the following:
1. A JavaScript IDE either on your PC or mobile
2. An earlier/fundamental knowledge of JavaScript
3. Willing to become a master in data types
Introduction to JavaScript Data Types
In this section, we are going to learn what it means by JavaScript data types, their importance, and how they affect variable declaration and their usage.
What are JavaScript Data Types?
JavaScript data types are fundamental concepts in this programming language. They define the kind of data that can be stored and manipulated in a given program. They include number, string, boolean, null, undefined, symbol, BigInt, arrays, object literals and functions.
Importance of Data Types in JavaScript
These data types are important in the following ways:
-
Data types help specify how data is stored in the computer memory.
const firstName = "Marcus"; //string let age = 23; //number let weight = 52.41; //floating point number
The above example illustrates how a string, number and a floating point number can be declared. The two occupy different memory spaces.
-
They enable a programmer to identify which operation to perform on a given data.
when you see a number, you will have to think of calculations first and an array would mean you are storing something in a list format.
let mark = 45; let timesTwo = mark*2; const names = []; names.push("Sam"); names.push("Ted"); console.log(names); //Output: ["Sam", "Ted"], an array of name strings
They enhance code readability. A variable declared as a string makes a programmer aware of what he is going to deal with, in this case, a string of characters.
Helps in error detection by catching any type-related error during compilation hence making debugging easy.
Properly chosen data type make performance efficient due to efficiency in code as the interpreter and compiler gets to know which kind of data type is being dealt with
How Data Types are declared and used: Var, Let and Const
In JavaScript, data types can be declared in three major ways: using the var, let and const.
var rating;
let name;
const age;
When a data type is declared as a var, it means that variable can change and can be accessed everywhere in the global scope.
if(true){// an if is a block scope
let a= 12;
const b = 11;
var c = 10;
}
console.log(c); // output: 10
console.log(b); // output: error
console.log(a); // output: error
If it is declared with let, this also means that this data type can change but the difference with it is that it is block-scoped, meaning if declared in a block, it can’t be accessed outside this block.
For the variable declared with const, this variable can’t change that is it’s a constant. Const is also block scoped like let.
The above two ways (i.e. let and const) of declaring variables in a block-scope format were introduced in ES6 and since then they have been in use much more than the var.
Primitive vs Reference Types
Watch this video to understand Primitive and Reference Types in programming:
%[https://www.youtube.com/watch?v=9ooYYRLdg_g]
Primitive Data Types in JavaScript
These are data types that are directly stored in the stack where they can be accessed from. These data types include the ones shown below;
Number: An integer or floating point number for example 67 or 3.142
const age = 23; //integer or number
let weight = 54.23; //floating point number
String: A sequence of characters that represent a text value. For example, “Hello world”
const name = "James";
Boolean: true or false.
let isComing = true;
let isAdmin = false;
null: A special keyword denoting a null value. (Because JavaScript is case sensitive, null is not the same as Null or NULL, or any other variant.)
const appNumber = null;
undefined: A top-level property whose value is not defined.
let a;
console.log(a); //output: undefined
let a = undefined; // output: undefinded
BigInt: An integer with arbitrary precision. For example, 9007199254768905n.
The BigInt
type is a numeric primitive in JavaScript that can represent integers with very huge magnitude. With BigInts, you can safely store and operate on large integers even beyond the safe integer limit (Number.MAX_SAFE_INTEGER
) for Numbers.
A BigInt is created by appending n
to the end of an integer or by calling the BigInt()
function.
This example demonstrates where incrementing the Number.MAX_SAFE_INTEGER
returns the expected result:
// BigInt
const x = BigInt(Number.MAX_SAFE_INTEGER); // 9007199254740991n
x + 1n === x + 2n; // false because 9007199254740992n and 9007199254740993n are unequal
// Number
Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2; // true because both are 9007199254740992
Symbol: A data type whose instances are unique and immutable.
const id = Symbol(id);
Reference Data Types in JavaScript
These are data types stored in the heap and accessed by reference. These data types include the following;
All of the reference data types are objects and they include;
Object literals: These are objects that have a limited set of properties initialized in them. These properties can be added or removed. The properties are equivalent to key-value pairs. The property keys are either strings or symbols.
The property values can be values of any type including other objects.
const person{
name: "John",
age: 23
};
Function objects: A function is a block or scope of code that is written to perform a certain task. Below is the structure of a function:
//declaration
function sayHello(){// sayHello is the function name
console.log("Hello Programmer!");//the code in the function scope
}
//below we are calling the function
sayHello(); // output: Hello Programmer!
A function can have parameters passed into the parenthesis or it may be a function that does not have parameters like the one shown above. The passed values entered into the function when being called are assigned to the parameters, and these values are called arguments.
A function that has parameters:
function sayHello(name){//name is the parameter
console.log("Hello, " +name+"!");
}
sayHello("Tommy"); // Here "Tommy" is the argument and in this case it is a string
Date object: In JavaScript, whenever we are dealing with time, we use an object called the date object.
let d;
d = new Date();
console.log(d); // outputs the current date
Arrays: An array is a collection of multiple data values. These values can be strings, numbers, and many more.
const fruits = ['apple', 'grape', 'orange'];
const mixed = new Array['apple', 12, true, null]; // this is an array mixed with diifferent data types
// the new Array is called an array constructor an it is another way of creating an array
Type Conversion and Coercion
Type Conversion:
Also known as type casting, it refers to the transfer of data from one data type to another. This conversion can be implicit (i.e. done automatically by the JavaScript compiler) or can be explicit where you as a developer can do the conversion yourself using some given functions.
In this subsection, we shall explore the explicit:
Converting a string to a number
let amount = '100';
//converting amount to a number
amount = parseInt(amount);
amount = +amount; //using the unary operator
amount = Number(amount);
//all the above lines convert the string to a number
Converting a number to a string
let amount = 100;
amount = amount.toString();
amount = String(amount);
//all the above convert a number to a string
Converting a number to a Boolean
let amount = 1;// any integer not
amount = Boolean(amount); // will return true for all other integers while for 0 it will return false
Type Coercion:
JavaScript is said to be a weakly typed language i.e. it follows implicit type conversion; when an operation involves mismatched types, instead of throwing type errors, JavaScript will automatically convert the data type to another type that is expected or the right type for you:
This conversion can be a big problem especially when a developer doesn’t intend to change a variable type to another.
const value1 = "5";
const value2 = 9;
let sum = value1 + value2;
console.log(sum);// outputs 59 as value2 is converted to a string by the compiler
JavaScript has some rules that are followed when carrying out coercion and these are crucial for you to have at the back of your mind as they will aid you to know where to and how to deal with a given value while applying coercion. Click here to get to learn more about the rules.
Type Checking and typeof Operator
In programming, it is a very important practice for you as a programmer to know which kind of data type you are dealing with. This is called type checking which is carried out by the typeof operator.
Let's jump right in and find out the data types of the given data values.
console.log(typeof 42);
// Expected output: "number"
console.log(typeof 'blubber');
// Expected output: "string"
console.log(typeof true);
// Expected output: "boolean"
console.log(typeof undeclaredVariable);
// Expected output: "undefined"
Choosing the Right Data Type
It is very important for you as a developer to get to know how, when, and where to choose which data type to use. This will enable you to write efficient and easily ‘debuggable’ code, and other developers will also get to easily understand and reuse your code. In this section when going to guide how to do that, let's dive in:
Choose data that maintains the integrity of your data. For example, use strings for names numbers for calculations, or mathematical operations.
Consider memory usage to ensure efficiency in the program. For example, use numbers (or integers) for calculations rather than storing them as strings.
To ensure faster performance of your program, for example, you should note that numbers are easier and faster for calculations than any other data type. Also note that very big numbers especially when dealing with currency would require the ‘BigInt’ data type rather than numbers.
Choose data types that are easier to use for example when dealing with a list of items it's better to use arrays rather than objects.
To maintain compatibility of data especially when fetching external data from other sources using APIs, it is advisable to ensure your data format matches the one for the source.
Get note of type coercion as your data may be changed to another data type when you do not want it to be changed, so use explicit type coercion if necessary.
It is better to document your data type and where they are being used. This makes it easy for any programmer to debug or reuse and understand your code.
Sample Challenges on Data Types
Here are 10 beginner-friendly challenges covering a variety of JavaScript Data types. Some shall need a deeper coverage of objects and strings, I recommend the MDN docs for that.
Challenge 1: Number Operations
Problem: Write a function squareNumber(number)
that takes a number as input and returns its square.
Solution:
function squareNumber(number) {
return number * number;
}
// Example usage:
console.log(squareNumber(5)); // Output: 25
Challenge 2: String Concatenation
Problem: Write a function greet(name)
that takes a name as input and returns a greeting message.
Solution:
function greet(name) {
return "Hello, " + name + "!";
}
// Example usage:
console.log(greet("Alice")); // Output: "Hello, Alice!"
Challenge 3: Object Property Access
Problem: Create an object person
with properties firstName
and lastName
. Write a function getFullName(person)
that returns the person's full name.
Solution:
const person = {
firstName: "John",
lastName: "Doe"
};
function getFullName(person) {
return person.firstName + " " + person.lastName;
}
// Example usage:
console.log(getFullName(person)); // Output: "John Doe"
Challenge 4: Date Formatting
Problem: Write a function formatDate(date)
that takes a Date object and returns a string in the format "MM/DD/YYYY".
Solution:
function formatDate(date) {
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const year = date.getFullYear();
return `${month}/${day}/${year}`;
}
// Example usage:
const today = new Date();
console.log(formatDate(today)); // Output: "09/23/2023"
Challenge 5: Array Sum
Problem: Write a function sumArray(numbers)
that takes an array of numbers and returns their sum.
Solution:
function sumArray(numbers) {
let sum = 0;
for (let number of numbers) {
sum += number;
}
return sum;
}
// Example usage:
console.log(sumArray([1, 2, 3, 4, 5])); // Output: 15
Challenge 6: Function Parameters (let and const)
Problem: Write a function calculateArea(length, width)
that calculates and returns the area of a rectangle. Use const
for constants and let
for variables.
Solution:
function calculateArea(length, width) {
const area = length * width;
return area;
}
// Example usage:
const length = 4;
const width = 3;
console.log(calculateArea(length, width)); // Output: 12
Challenge 7: Type Conversion
Problem: Write a function concatenateStrings(str1, str2)
that takes two values, which could be numbers or strings, and returns them as a concatenated string.
Solution:
function concatenateStrings(str1, str2) {
return String(str1) + String(str2);
//the String() method converts the inputs to string a string
}
// Example usage:
console.log(concatenateStrings(5, " apples")); // Output: "5 apples"
Challenge 8: Type Coercion
Problem: Write a function multiplyByTwo(value)
that takes a value, which could be a number or a string, and multiplies it by 2. Ensure that the result is a number.
Solution:
function multiplyByTwo(value) {
return Number(value) * 2;
}
// Example usage:
console.log(multiplyByTwo("3")); // Output: 6
Challenge 9: Array Push
This challenge is kind of advanced though beginner friendly but it will require you to know array methods.
Problem: Create an empty array fruits
. Write a function addFruit(fruit)
that takes a fruit name as input and adds it to the array.
Solution:
const fruits = [];
function addFruit(fruit) {
fruits.push(fruit);
}
// Example usage:
addFruit("apple");
addFruit("banana");
console.log(fruits); // Output: ["apple", "banana"]
Challenge 10: Function Return
Problem: Write a function isEven(number)
that takes a number as input and returns true
if it's even and false
if it's odd.
Solution:
function isEven(number) {
return number % 2 === 0;
}
// Example usage:
console.log(isEven(4)); // Output: true
console.log(isEven(7)); // Output: false
These challenges cover a range of fundamental JavaScript concepts and are designed to be beginner-friendly. They provide opportunities to practice using different data types, variables, functions, and basic operations.
Conclusion
I am glad to have you here at the last section of this long data types knowledge-based article, we have come far and now am sure you are ready to dive deep right into the details of the String Object, Objects as a topic, Date Object, Math Object, Arrays, and all the various manipulations on them, not forgetting methods/functions.
I do recommend the MDN documentation for a better understanding of all the above topics.
Top comments (0)