JavaScript Primitive Data Types: An In-Depth Learning Guide


Primitive datatypes in JavaScript
In the previous articles, we have discussed the distinction between primitive and reference data types and their significance in JavaScript. We have also examined the classification of various data types, which fall under primitive data types. Now, it's time to explore each datatype in detail, let's dive deeper into each type of data type, understanding its behavior and how we can efficiently utilize them in our code.
Primitive datatypes
Let's have a quick recap of what do we mean by primitive datatypes and what are the datatypes which are classified as primitive datatypes.
Primitive datatypes are those datatypes whose size is fixed at compile time. Memory allocation for primitive datatypes is typically done on the 'Stack'.
There are primarily five primitive datatypes :
Numbers
Strings
Boolean
Undefined
Null
These primitive data types are essential for basic operations and data manipulation in programming languages. Now, let's briefly discuss each of these data types and their usage.
Numbers
Numbers are used to represent numeric values, which can be integers or floating-point numbers.
In JavaScript all numeric values are internally represented as double-precision 64-bit floating-point numbers and thus JavaScript does not make a strict distinction between integers and floating-point numbers. However, JavaScript provides methods to work with both integer and floating-point numbers.
Examples
index.js
1
2let integerNumber = 3; 3console.log(typeof(integerNumber)); // number 4 5let floatNumber = 3.14; 6console.log(typeof(floatNumber)); //number 7 8let output = integerNumber + floatNumber; 9// Result will be a floating-point number 10 11console.log(output); // 6.14
In JavaScript, we can perform arithmetic operations on numbers, including addition, subtraction, multiplication, and division.
index.js
```cpp
1
2let number1 = 13; 3let number2 = 10; 4 5let sum = number1 + number2; 6console.log(sum); // 23 7 8let product = number1 * number2; 9console.log(product); // 103 10 11let quotient = number1/number2; 12console.log(quotient); // 1.3
Moreover, JavaScript also provides several built-in methods for working with numbers, such as 'parseInt()' and 'parseFloat()' for converting strings to numbers.
index.js
```cpp
1
2let strNum = "25"; 3console.log(typeof(strNum)); // string 4 5let strFloat = "35.63"; 6console.log(typeof(strFloat)); // string 7 8let parsedInteger = parseInt(strNum); 9let parsedFloat = parseInt(strFloat); 10 11console.log(typeof(parsedInteger)); // number 12console.log(typeof(parsedFloat)); // number
## **Strings**
In JavaScript, the "Strings" primitive data type represents sequences of characters. Strings are used to store and manipulate textual data, such as words, sentences, or any other sequence of characters.
### **Creation of strings**
Creation of strings is possible in three ways, we can create a string using **double-quotes("")**, **single-quotes('')** and **template literals or backticks(\`\`)**.
index.js
```cpp
1
2let string1 = "Namaste";
3console.log(typeof(string1)); // string
4
5let string2 = 'Namaste';
6console.log(typeof(string2)); // string
7
8let string3 = Namaste
;
9console.log(typeof(string3)); // string
### **Concatenating strings**
We can concatenate multiple strings in JavaScript using two different ways:
* Using the '+' operator
* String interpolation with template literals
Let's understand the different ways of concatenation with the help of examples:
**Concatenation using '+' operator:**
index.js
```cpp
1
2let string1 = "Mobile"; 3 4let string2 = "Charger"; 5 6let finalSentence = string1 + " and " + string2 + "!"; 7 8console.log(finalSentence); 9 10//Output : Mobile and Charger!
**Concatenation using string interpolation using template literals(\`\`):**
Backticks allow for string interpolation, where we can embed expressions within **${}** inside the string, which are then evaluated and concatenated into the string.
index.js
```cpp
1
2let string1 = "Mobile";
3
4let string2 = "Charger";
5
6let finalSentence = ${string1} and ${string2}!
;
7
8console.log(finalSentence);
9
10//Output : Mobile and Charger!
JavaScript provides numerous built-in methods for working with strings, such as **length**, **toUpperCase()**, **toLowerCase()**, **substring()**, **charAt()**, **indexOf()**, **split()**, **replace()**, and many more, which allows us to perform various operations on strings, such as manipulation, searching, and formatting.
### **Length method on strings**
In JavaScript, the **length** property is used to know the length of various data types such as strings, arrays, and other iterable objects. When applied to a string, the *length* property returns the number of characters (including spaces, punctuation, and other characters) within that string.
**Syntax:**
index.js
```cpp
1
2let length = string.length;
**Example**
index.js
```cpp
1
2let message = "Hello coders"; 3 4let messageLength = message.length; 5console.log(messageLength); // 12
### **Uppercase and Lowercase methods on strings**
In JavaScript, we can convert a string to uppercase or lowercase using the **toUpperCase()** and **toLowerCase()** methods, respectively. These methods return a new string with all alphabetic characters converted to uppercase or lowercase, while leaving non-alphabetic characters unchanged.
**Syntax:**
index.js
```cpp
1
2let upperCaseString = string.toUpperCase(); 3 4let lowerCaseString = string.toLowerCase();
**Example**
index.js
```cpp
1
2let message = "Hello coders"; 3 4let upperCaseMessage = message.toUpperCase(); 5console.log(upperCaseMessage); // HELLO CODERS 6 7let lowerCaseMessage = message.toLowerCase(); 8console.log(lowerCaseMessage); // hello coders
### **Substring method on strings**
In JavaScript, the substring() method is used to extract a portion of a string, starting from a specified index position to another specified index position, or to the end of the string.
**Syntax:**
index.js
```cpp
1
2string.substring(startIndex, endIndex);
* **startIndex** : The index position at which to begin extracting characters from the string. This parameter is required.
* **endIndex** : The index position before which to end the extraction. If we don't mention the endIndex then, the substring() extracts characters to the end of the string.
**Example**
index.js
```cpp
1
2let message = "Hello coders"; 3 4let substr1 = message.substring(2, 8); 5console.log(substr1); // llo co 6 7let substr2 = message.substring(3); 8console.log(substr2); // lo coders
It's important to note that **substring()** extracts the characters between *startIndex* and *endIndex* but does not include the character at the endIndex position.
### **Split method on strings**
In JavaScript, the **split()** method is used to split a string into an array of substrings based on a specified separator.
**Syntax:**
index.js
```cpp
1
2string.split(separator);
***separator*** : Separator is a string or regular expression used to specify where to split the original string. The output is the array of substrings.
**Example**
index.js
```cpp
1
2let message = "Once upon a time"; 3 4let splittedArray = message.split(" "); 5 6console.log(splittedArray); 7 8/ 9Output 10[ 'Once', 'upon', 'a', 'time' ] 11/
### **Join method on strings**
In JavaScript, the **join()** method is used to concatenate all the elements of an array into a single string. This method joins array elements using a specified separator and returns the resulting string.
**Syntax:**
index.js
```cpp
1
2array.join(separator);
***separator***: Here in *join* method using the separator string is optional. The string used to separate each element of the array when they are concatenated into the resulting string.
If we don't specify the separator, the default separator is a comma(,).
**Example**
index.js
```cpp
1
2let array = ["India", "is", "the", "best"]; 3 4let message1 = array.join(" "); 5console.log(message1); 6 7//Output : India is the best 8 9let message2 = array.join(); 10console.log(message2); 11 12//Output : India,is,the,best
## **Boolean**
Another type of primitive datatype in JavaScript is **boolean**. The Boolean primitive datatype represents a logical value, which can be either true or false. Booleans are used to represent the truthfulness or falseness of an expression or condition.
In JavaScript, Boolean values are often used in conditional statements (such as if statements, while loops, etc.) to control the flow of execution based on whether certain conditions are true or false.
Let's understand with the help of examples.
**Example**
index.js
```cpp
1
2let isSleeping = true; 3 4let isRunning = false; 5 6if(isSleeping){ 7 console.log("He is sleeping"); 8}else{ 9 console.log("He is Running"); 10} 11 12/ 13Output : He is sleeping 14/ 15 16 17 18let x = 10; 19let y = 16; 20 21let isGreater = x > y; 22console.log(isGreater); // False
## **Undefined**
In JavaScript, **undefined** is a primitive value that represents a variable that has been declared but has not been assigned a value. It also serves as the default value of variables that have not been initialized.
**Example**
index.js
```cpp
1
2let range; 3 4console.log(range); // undefined
## **Null**
In JavaScript, **null** is a primitive value that represents the intentional absence of any object value. It is used to signify that a variable, object, or property does not have a value.
Unlike *undefined*, which typically means a variable has been declared but not initialized, *null* is explicitly assigned to indicate that there is no value present.
**Example**
index.js
```cpp
1
2let range = null; 3 4console.log(range); // null 5console.log(typeof(range)); //object ```
It's important to note that null is not the same as undefined. While both represent absence of value, null is a deliberate assignment, whereas undefined typically arises when a variable has been declared but not initialized.
Conclusion
Wow! If you've made it this far, I hope you now have a good understanding of the various data types that fall under primitive data types. I trust that you found it beneficial and that you've gained insight into how to use these data types effectively. Moving forward, let's dive into the data types classified as reference types.
It's going to be fun! See you next time.
Subscribe to my newsletter
Read articles from RAJU KUMAR directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
