JavaScript DataTypes Tutorial

What are Data Types?

  1. Data types are classifications of data that tell the compiler or interpreter how the programmer intends to use the data.
  2. Most programming languages support various types of data, including integer, real, character or string, and Boolean.
  3. For example, many programming languages use the data type string to classify text, integer to identify whole numbers and floating point to designate numbers with decimal points.

Types of Data Types in JavaScript?

  1. In JavaScript, data types are divided into two categories: primitive and non-primitive.
  2. Primitive data types are immutable, meaning that they cannot be changed once they are created. For example, Number, String, Boolean, and Symbol
  3. Non-primitive data types are mutable, meaning that they can be changed after they are created. For example, Object, Array, Function, and etc.

Number

  1. Represents both integers and floating-point numbers.
let balance = 79000;
let price = 9.978;

In the above example program, two variables are declared and initialized. The first variable, named balance, is set to 79000, it represents a financial balance or amount.

The second variable, price, is initialized with the value 9.978 signifies the cost of a product.

String

  1. The String data type represents sequences of characters enclosed in single or double quotes.
let greeting = 'Hello, World!';
console.log(greeting); // Output: Hello, World!

In the above example program, a variable named greeting is declared and assigned the value 'Hello, World!'.

Subsequently, the content of the greeting variable is printed to the console using console.log(), resulting in the output 'Hello, World!'.

Boolean

  1. The Boolean data type represents true or false values.
let isOnline = true;
console.log(isOnline); // Output: true

The above program represents boolean values in JavaScript. When isOnline is true, it suggests that the user might be online; otherwise, not

Undefined

  1. The undefined data type is used for uninitialized variables or missing object properties.
let name;
console.log(name); // Output: undefined

In the above example, we declared a name variable without initializing any value. As a result, the output is undefined.

Null

  1. The null data type represents the intentional absence of any object value.
let emptyValue = null;
console.log(emptyValue); // Output: null

You can use null to reset or clear the value of a variable or property.

let userLoggedIn = true;
// User logs out, reset the user status
userLoggedIn = null;

Symbols

  1. The Symbol data type represents unique and immutable values, often used as object property keys.
const uniqueSymbol = Symbol('description');
console.log(uniqueSymbol); // Output: Symbol(description)

The symbols data type can be used as an identifier for object properties.


// Creating a Symbol
const mySymbol = Symbol('description');

// Using the Symbol as an object property
const myObject = {
[mySymbol]: 'This is a Symbol property'
};

console.log(myObject[mySymbol]); // Output: This is a Symbol property

BigInt

  1. The BigInt data type represents large integers that cannot be represented as regular Number values.
const bigIntValue = 1234567890123456789012345678901234567890n;
console.log(bigIntValue); // Output: 1234567890123456789012345678901234567890n

Object

  1. The Object data type represents collections of key-value pairs.
const userProfile = {
    name: "John",
    id: "af32ding",
    email: "john7879@gmail.com",
    isSubscribed: true,
    displayDetails: function() {
        console.log(`Name: ${this.name} \n User Id: ${this.id} \n Email: ${this.email}`);
    }
};

// Call the displayDetails method
userProfile.displayDetails();

/*Output:
Name: John
User Id: af32ding
Email: john7879@gmail.com
*/

This code defines an object named userProfile representing a user profile with various properties and a method.

The userProfile object is created with properties like name, id, email, and isSubscribed, along with a method named displayDetails. The displayDetails method prints user details to the console using template literals.

userProfile.displayDetails();

This line invokes the displayDetails method of the userProfile object. It prints the user details to the console.

I will explain this keyword in later tutorials

The backslash character (\) is used to escape special characters in JavaScript.

The \n escape character represents a newline character. Newline characters are used to start a new line of text.

There are plenty of some other like \t, \r, \v, and etc.

Arrays

  1. The Array in JavaScript is a data type that represents an ordered lists of values.
const colors = ['red', 'green', 'blue'];
console.log(colors) // [ 'red', 'green', 'blue' ]
console.log(colors[0]); // Output: red
    
const mixed = ["Jack", 42, {name:"Jack", age:19}, ["New York", "Texas"], colors];
console.log(mixed);
/* Output: 
[
'Jack',
42,
{ name: 'Jack', age: 19 },
[ 'New York', 'Texas' ],
[ 'red', 'green', 'blue' ]
]
*/

In the given code, we start by creating an array called colors with three colors: 'red', 'green', and 'blue'. We then print the entire colors array, showing it as [ 'red', 'green', 'blue' ]. Next, we print the first color in the array separately, which is 'red'.

Moving on, we create another array named mixed. This array is quite diverse, containing a mix of data types. It includes a name ('Jack'), a number (42), an object with a name and age ({name:"Jack", age:19}), a list of places (["New York", "Texas"]), and the entire colors array.

Finally, we print the entire mixed array to the console.

Type Conversions

  1. JavaScript provides functions and operators for type conversion. For example, you can convert a string to a number using parseInt or parseFloat.
const numericString = '42';
console.log(typeof(numericString)) // string
const numericValue = parseInt(numericString);
console.log(numericValue); // Output: 42
console.log(typeof(numericValue)) // number

The above code takes a set of characters (specifically, '42') that looks like a number but is treated as a word.

It first checks and shows that it's recognized as a word. Then, it converts it into a real number and displays the result, showing that it's now seen as a number, not a word.

You might wonder why I'd use this. When taking user input, we often receive values as strings. However, for certain operations, we need these values as numbers. So, we convert them, especially since the prompt method takes inputs as strings by default.

// Taking user input as a string using prompt
let userInput = prompt("Enter a number:");

// Converting the string to a number
let userNumber = parseInt(userInput);

// Checking if the conversion was successful
if (!isNaN(userNumber)) {
// Performing a simple calculation
let result = userNumber * 2;

// Displaying the result
alert(`You entered: ${userNumber}\nAfter doubling: ${result}`);
} else {
// Handling the case where the input is not a valid number
alert("Invalid input. Please enter a valid number.");
}