JavaScript is a popular programming language for web development. Developers can create dynamic and interactive web applications by manipulating web page elements and responding to user interactions.
JavaScript supports several primitive data types, including numbers, strings, booleans, null, and undefined, and it also supports more complex data types like arrays and objects. Each data type has its unique properties and behaviors, and understanding how to use them effectively can make a big difference in the performance and reliability of your code.
This article will review the various JavaScript data types in depth, looking at their characteristics and best practices for using them in web development projects.
What Are Data Types?
Data types describe the characteristics of data. Also, a data type is a classification of data that tells the compiler or interpreter how the programmer intends to use the data. Data types can be classified into two: primitive data types and non-primitive data types.
Primitive data types in JavaScript
Primitive data types are non-modifiable data types. Once a primitive data type is created, we cannot modify it. Primitive data types in JavaScript include:
Numbers:
Numbers are integers or decimal values which can perform arithmetic operations.
let a = 25; // integer value
let b = 27.0; // decimal value
Strings:
Strings are text enclosed by a single, double, or backtick quote. We need a variable name, an assignment operator, and a value enclosed by a single, double, or backtick quote to declare a string.
let nameOne = “Ade”; //This is a string
let nameTwo= ‘Ola’;
let name = love;
Let's consider another example below :
let animal = "Dog";
animal[0] = "C";
console.log(animal); //This returns Dog
The expression above indicates that the variable "animal" value remains unchanged after evaluating the expression. As a result, we can conclude that strings are immutable.
Rule of thumb: Primitive data types are compared by their value. This means that when two primitive variables are compared, their values are compared directly to determine whether they are equal.
Boolean:
Boolean gives either true or false values. They are mostly used to check a logical condition
let a = 5;
let b = 6;
console.log(a==b) // returns false
let a = 5;
let b = 5;
console.log(a==b) // returns true
Let's consider some more examples below:
let firstName = "Ade";
let lastName = "Ade";
console.log(firstName == lastName); // This returns true
//Another example
let ageOne = 10;
let ageTwo = 11;
console.log( ageOne == ageTwo); // This returns false
Null:
Null is an empty value
let a = null;
console.log(a) //This returns null
Undefined:
A declared variable without a value
let a;
console.log(a) // This returns undefined
Non-Primitive Data types in Javascript
Non-primitive data types are modifiable or mutable, i.e., the value of non-primitive data types can be changed after it gets created. Non-primitive data types in javascript include:
Object: An object is a collection of properties, which are key-value pairs.
Array: An array is a list of data values in a square bracket. Arrays can contain the same or different data types.
Let's consider the code below
let name = ["Adeola", "Tosin", "Comfort"];
name[1] = "Daniel";
console.log(name); // ["Adeola", "Daniel", "Comfort"]
An array is a mutable non-primitive data type, meaning its contents can be changed.
Note: To avoid unexpected results, it is generally recommended not to directly compare non-primitive data types like objects and arrays, as they are typically compared by reference rather than by value.
// array example
let age = [10, 26, 38]
let ages = [10, 26, 38]
console.log(age == ages) // This returns false
// object example
let user_info_One = {
name: 'Adeola',
role: 'Writer',
country:'Nigeria'
}
let user_info_Two = {
name: 'Adeola',
role: 'Writer',
country: 'Nigeria'
}
console.log(user_info_One == user_info_Two) // This returns false
Note: Two objects are only strictly equal if they refer to the same underlying object.
// array example
let age = [10, 26, 38]
let ages = age
console.log(age == ages) // This returns true
// object example
let user_info_One = {
name:'Adeola',
role:'Writer',
country:'Nigeria'
}
let user_info_Two = user_info_One
console.log(user_info_One == user_info_Two) //This returns true
String Concatenation
Concatenation is the term used to describe the process of joining multiple strings together to create a single string.
Let's consider the code below
let firstName = "Adeola";
let lastName = "Ajiboso";
let gender = "Girl";
let hobby = "writing";
let fullName = firstName + ' ' + lastName;
let userInfo = fullName + ' is a ' + gender + ' and she loves ' + hobby;
console.log(userInfo);
// Output
Adeola Ajiboso is a Girl and she loves writing
Template Literals
Template literals provide an easy way to interpolate variables and expressions into strings.
Backticks (``) are used instead of single or double quotes to create a template string. We can include placeholders for expressions or variables within a template string by enclosing them in curly braces () and prefixing them with a dollar sign ($).
For example,
let name = "Peter";
let age = 20;
let message = My name is ${name} and I am ${age} years old.;
console.log(message)
//output
My name is Peter and I am 20 years old.
String Methods
JavaScript methods are actions that can be performed on objects. Common string methods include:
- toUpperCase():
toUpperCase()
is a built-in string method that changes a string to uppercase
let myWord = "hello, world!";
let myUppercase = myWord.toUpperCase();
console.log(myUppercase); // Output: "HELLO, WORLD!"
- toLowerCase(): This method changes the string to lowercase.
let myWord = "Hello, World!";
let myLowercaseString = myWord.toLowerCase();
console.log(myUppercaseString); // Output: "hello, world!"
- length():
length()
returns the number of characters in a string, including space.
let fruit = "Banana ";
console.log(fruit.length); // This return 7
- substr():
substr()
takes two arguments, the substring's starting index and the substring's length to be returned.
let myString = "hello, world!";
let mySubstring = myString.substr(7, 5);
console.log(mySubstring); // Output: "world"
- split(): This is a built-in string method that splits a string into an array of substrings based on a specified separator.
let string = 'Technical writing is fun'
console.log(string.split())
console.log(string.split(' '))
//output
// Changes to an array -> [ 'Technical writing is fun' ]
// Split to an array at space -> [ 'Technical', 'writing', 'is', 'fun' ]
- trim(): This method removes trailing space at a string's beginning or end.
let firstName = ' Prestige '
console.log(firstName)
console.log(firstName.trim())
//output
// Prestige
//Prestige
- includes():
includes()
returns a boolean value indicating whether the specified string is within the original string.
let word = "hello, world!";
let isWordFound = word.includes("world");
console.log(isWordFound); // Output: true
- replace(): This is used to replace all occurrences of a particular substring in a string with a new substring or character.
The syntax for replace looks like this
string.replace(oldsubstring, newsubstring)
For example,
let hobby = 'I love writing'
console.log(hobby.replace('writing', 'singing')) // I love singing
- indexOf(): Takes a substring, and if the substring exists in a string, it returns the first position of the substring; if it does not exist, it returns -1.
Let’s consider the code below
let string = 'Writing is fun'
console.log(string.indexOf('W')) // 0
console.log(string.indexOf('fun')) // 11
console.log(string.indexOf('Fun')) // -1
console.log(string.indexOf('i')) // 2
console.log(string.indexOf('Writing')) // 0
console.log(string.indexOf('Is')) //-1
console.log(string.indexOf('r')) // 1
Casting and Checking of Data Type
Casting
Casting refers to the process of converting a value from one data type to another. We use parseInt()
, parseFloat()
, Number()
, +()
, str()
String to int
We can use various methods to convert a string number to a numeric value. As mentioned, any number inside a pair of quotes is considered a string number. We can convert string to number using the following methods:
parseInt()
,Number()
,+()
For example, let's consider the code below
//using parseInt to convert from string to int
let num = '10'
let numInt = parseInt(num)
console.log(numInt) // 10
//using Number to convert string to ont
let num = '20'
let numInt = Number(num)
console.log(numInt) // 20
//using + to convert from string to int
let num = '40'
let numInt = +(num)
console.log(numInt) // 40
Float to int
We can convert float numbers to integers using the following methods
parseInt()
Let’s consider the code below
let num = 7.82
let numInt = parseInt(num)
console.log(numInt) // 7
Checking Of Data Type In Javascript
We make use of the typeof
method to check data type.
Let's consider the code below
let firstName = 'John'
let lastName = 'Doe'
let country = 'Nigeria'
let city = 'Lagos'
let age = 25
let job;
console.log(typeof 'lastName') // string
console.log(typeof firstName) // string
console.log(typeof country) // string
console.log(typeof city) // string
console.log(typeof age) // number
console.log(typeof 3.14) // number
console.log(typeof true) // boolean
console.log(typeof false) // boolean
console.log(typeof NaN) // number
console.log(typeof job) // undefined
Conclusion
In conclusion, understanding JavaScript data types is essential for web development. By knowing the different types of data used in JavaScript, developers can write more efficient and effective code.
Do not hesitate to ask questions or leave comments on this post. I'm available on Twitter, LinkedIn, and GitHub. Keep an eye for my upcoming blog post,in which I will cover another important area of web development. As a developer, I'm glad to provide additional knowledge
Until then, happy coding, and take care!