JavaScript Essentials: Understanding Variables and Data Types

August 26, 2024 in Frontend development, JavaScript, Coding11 minutes

Are you a beginner in JavaScript? This article will put you on the right path of learning the basic building blocks of JavaScript.

Header

Introduction

JavaScript is a popular, verstile programming language that allows developers to create dynamic and interactive online applications. Variables and data types are two key elements in JavaScript that are required for storing and manipulating information within your code.

This article will go over variables in detail, how to declare and assign values to them, as well as the various data types available and how to use them effectively. Mastering these ideas provides a solid basis for creating powerful and efficient JavaScript applications.

Understanding Variables

Variables acts as a container that holds and stores data for later use. They allow you to assign names to values, thereby, making your code more readable and maintainable.

The Var, Let and Const keywords are used to declare variables. The variables are assigned a value using the assignment operator (=).

Variables holds different data types such as numbers, string, booleans, arrays, objects, and more. Now, let’s take a look at each one.

Var

The Var keyword is an old method of declaring a variable and it’s not recommended due to its hoisting and scope concerns. Using Var can lead to accidental reassignment of variables.

1var x = 5;
2var name = "Sophie";

Explanation

var x = 5 : In this line of code, a variable “x” is declared and it is then assigned (using the assignment operator = ) to a numerical value “5”.

var name = “Sophie” : In this line of code, a variable “name” is declared and it is assigned to a string value “Sophie”.

Don’t worry about what a string is, we’ll talk about it later in this article.

1var x = 10;
2var y = 20;
3var z = x + y;
4var name = "Dave";
5
6console.log(x);    // 10
7console.log(y);   // 20
8console.log (z);  // 30
9console.log(name);  // Dave

Explanation

var x = 10 : In this line a variable “x” is declared and assigned to a number “10”

var y = 20 : A variable “y” is declared and assigned to a number “20”

var z = x + y : A variable ‘z" is declared and it is assigned to the result of adding the values of “x” and “y”

var name = “Dave”: In this line of code, a variable “name” is declared and is then assigned to a string value “Dave”.

console.log(x), Console.log (y) : These prints to the console each of the value of variables “x” and “y”, which are 10 and 20 respectively.

console.log(z) : This line prints to the console the result of the addition of var “x” and “y”, which is 30.

console.log(name) : This line prints to the console the value of the var “name”.

Let

The let keyword is the most common way of declaring a variable. This keyword is a good choice for declaring variables whose values will be reassigned.

1let x = 10;
2let color = "Red";
3color = "Blue";  // values can be reassigned
4
5console.log(x); // 10
6console.log (color);  // Blue

Explanation

let x = 10; This line declares a variable “x” using the “let” keyword and assigns it to a number value “10”.

let color = “Red”; This line declares a variable “color” and assigns it to a string value “Red”

color = ‘Blue"; This line reassigns a new value “Blue” to the variable “color”. The original value “Red” will be overwriten by the new value “Blue”.

console.log(x) : This line prints to the console the value of the variable “x”, which is “10”.

console.log(color) : This line prints to the console the current value of the variable “color”, which is “Blue”.

Const

The const keyword is used to create variables whose values you won’t reassign. They are useful for variables that should remain constant throughout their lifetime. This helps prevent accidental changes to your code and improves code maintainability. Note that values of variables declared with const can’t be changed.

1const pi = 3.14159;
2
3console.log(pi); // 3.14159

Explanation

The above code block defines a constant named “pi” and assigns it the value 3.14159. This value represents the mathematical constant pi, which is the ratio of a circle’s circumference to its diameter.

console.log(pi): Prints the value of the constant pi to the console

The const keyword is used to declare a constant variable, it is useful for values like mathematical constants

Understanding Data Types

Data Types are another fundamental building blocks of JavaScript. The most common ones are the primitive and complex data types.

The primitive data types consists of Number, String, Boolean, BigInt, Null and Undefined while the Complex data types consist of but not limited to Arrays and Objects.

Primitive Data types

Number : Numeric values

Number represents numerical values. They could be intergers or floating-point numbers and are also used to perform mathematical operations.

1let person1Age = 16;
2let person2Age = 20;
3const pi = 3.14159
4let totalAge = person1Age + person2Age;
5
6console.log (person1Age);  // 16
7console.log(person2Age);   // 20
8console.log (pi); // 3.14159
9console.log(totalAge);  //36

Explanation

“person1Age” and “person2Age” stores the ages of two people.

“pi” holds the approximate value of the mathematical constant pi (a floating point value).

“totalAge” is used to calculate and store the sum of “person1Age” and “person2Age”.

The line “let totalAge = person1Age + person2Age; " calculates the total age by adding the ages of two people and assigns the result to the “totalAge” variable.

The console.log statements print the values of each of the variable to the console. Person1Age : 16 Person2Age : 20 Value of pi : 3.14159 totalAge : 36

You can see that all of these are assigned to a numerical value.

Use case : In a E-commerce, you can use Numbers to calculate product prices, discount etc.

String : Textual data

String represent sequences of characters and textual data. They must be enclosed within a single (’ ‘) or double (" “) quotes.

1let name = "Patricia Lawson";
2let greeting = "Hello, world!";
3
4console.log(name); // Patricia Lawson
5console.log(greeting); // Hello, world!

Explanation

The code block defines two variables, name : which stores the string “Patricia Lawson” greeting : stores the string “Hello, world!”

The console.log statements then print the values of these variables to the console, console.log(name); prints “Patricia Lawson” console.log(greeting); prints “Hello, world!”

Note: It is a string data type when they are enclosed in a single or double quotes.

Use case : In a To-do application, you can use String to store the To-do tasks.

Booleans : True or False

Booleans represents logical values either true or false. The are often used for conditional statements and logical operations. true means “yes or correct”, and false means “no or incorrect”

1let isWeekend = true;
2let isRaining= false;
3
4console.log(isWeekend) // true
5console.log(isRaining) // false

Explanation

The above code defines two boolean variables, isWeekend : Stores the boolean value “true”, indicating that it is indeed the weekend. isRaining: Stores the boolean value “false”, indicating that it is not raining.

The console.log statements then prints the values of these variables to the console, console.log(isWeekend); prints “true” because it is weekend. console.log(isRaining); prints “false” because it is not raining.

Use case: In a Social media application, you can use Boolean to determine if the user is a female or male when creating a profile.

BigInt : large Integers

BigInt are used to store numbers that are too large to be stored in the Number data type. They provide precise calculation for large intergers. To create a BigInt, add n to the end of an integer or call BigInt()

1let largeNumber = 123456789023456789098765432155575643213456789n;
2let y = BigInt (12345678909876543213456788904567890643224566788)
3
4console.log(largeNumber); //  123456789023456789098765432155575643213456789
5console.log(y); // 12345678909876543213456788904567890643224566788

Explanation

let largeNumber = 123456789023456789098765432155575643213456789n; This line declares a variable named “largeNumber” and assigns it a large interger value. The “n” suffix indicates that this value is a BigInt.

Same goes for “let y = BigInt (12345678909876543213456788904567890643224566788);”

The console.log statements print the values of each of the variable to the console.

largeNumber : 123456789023456789098765432155575643213456789 y : 12345678909876543213456788904567890643224566788

Use case: In a financial application, you can use BigInt to store values that are too big to be stored in Number.

Null : Absence of a value

Null is used to explicitly state the intentional absence of a value. It represents “nothing “, “empty” or “unknown value”. It’s often used to intentionally set a variable to an empty state.

1let emptyValue = null;
2
3console.log(emptyValue); // null

Explanation

let emptyValue = null; This line declares a variable named emptyValue and assigns it the value “null”.

console.log(emptyValue); This line prints the value of “emptyValue” to the console. Since “emptyValue” is assigned the value “null”, the output will be “null”.

Use case: Imagine you’re building a form where users can enter their informations . You can use Null to indicate the user chose not to answer a particular question.

Undefined : Uninitialized variable

Undefined represents variable that has been declared but has not yet been assigned a value. It means the variable exists, but it doesn’t hold any specific data yet.

1let name;
2
3console.log(name);  //  undefined

Explanation

let name; This line declares a variable named “name”. Since no value is assigned to it, “name” currently has the value “undefined”.

console.log(name); This line prints the value of “name”, because “name” is “undefined”, the output will be : undefined.

Use case: Imagine you’re building an E-commerce website, when a user registers but hasn’t completed their profile, their profile information could be undefined.

Complex Data types

Arrays : Ordered collections

Arrays are used to store and manipulate mutiple values in a specific order. Each of these value is termed an element, and the each of these elements can be accessed using their index number, which starts from “0”, because they are zero-indexed.

That means, the first element of an array is at index “0”, the second element is at index “1”, the third at index “2”, and so on.

1let fruits = ["Strawberry", "Watermelon", "Grapes"];
2
3console.log(fruits[0]); //Strawberry
4console.log(fruits[1]); //Watermelon
5console.log(fruits[2]); //Grapes

Explanation

let fruits = [“Strawberry”, “Watermelon”, “Grapes”]; This line declares an array named “fruits” and assigns it to the values “Strawberry”, “Watermelon” and “Grapes”.

console.log(fruits[0]); This line of code prints to the console the element at index 0 of the “fruits” array, which is “Strawberry”.

console.log(fruits[1]); This line of code prints to the console the element at index 1 of the “fruits” array, which is “Watermelon”.

console.log(fruits[2]); This line of code prints to the console the element at index 2 of the “fruits” array, which is “Grapes”.

Use case: Imagine you want to create a simple application that allows a user to input their favourite fruits. You can use a JavaScript Arrays to store the fruits.

Objects : Unordered collections

Objects are unordered collections of key-value pairs used to store data in a structured way and each of these key-value pair is termed a property.

An object literal is a collection of key-value pairs, enclosed in curly braces {}. Objects also allows you to store different data types and the properties can be acessed using the properties names.

 1let person = {
 2  name: "Doris",
 3  age : 18,
 4  isFemale : true,
 5  country : "Nigeria"
 6};
 7
 8console.log(person.name);  // Doris
 9console.log(person.age);  // 18
10console.log(person.isFemale);  // true
11console.log(person.country);  // Nigeria

Explanation

Let person = { . . . }; This line declares a variable named “person” and assigns it an object literals.

name: “Doris”; This line defines a property named “name” with the value “Doris”. The “name” property is used to store the person’s name.

age : 18; This line defines a property named “age” with the value “18”. The “age” property stores the person’s age.

isFemale : true; This line defines a property named “isFemale” with the value “true”. The “isFemale” property stores a boolean value indicating the person’s gender.

country : “Nigeria”; This line defines a property named “country” with the value “Nigeria”. The country property stores the person’s country.

console.log(person.name); This line prints the value of the name property of the person object to the console, which is “Doris”.

console.log(person.age); This line prints the value of the age property of the person object to the console, which is 18.

console.log(person.isFemale); This line prints the value of the isFemale property of the person object to the console, which is true.

console.log(person.country); This line prints the value of the country property of the person object to the console, which is “Nigeria”.

Use case: In an online store project, you might represent the product information as an Object, containing properties such as name of product, price, description, quantity available etc.

Conclusion

In this article, we’ve explored the fundamental building blocks of JavaScript: Variables and Data types.

We’ve looked into how these JavaScript essentials store and manipulate data in your scripts as well as real-life use cases for each of the Data types.

As you continue your journey in JavaScript these concepts will form the foundation for more complex topics and help you create powerful, efficient and interactive web apps.

Connect

Connect with me on Linkedln and Twitter