Introduction

This tutorial would explain what a variable means generally, how to declare a variable in JavaScript using var, const and let.

What is a variable?

A variable in general terms can be anything that holds or stores a value. So you can simply think of a variable as a container that stores a value for usage.

In JavaScript, a variable is a identifier that can accept or store a value.

A variable can store value of data type such as: number, string, array, object amongst others.

How To Declare a variable

To declare a variable in JavaScript, you will type the keyword, the variable name and then assign it with your intended value.

Here are some examples of variable declaration with different data types:

// variable with data type number
$ var numberVariable = 5; // type number


// variable with data type string
$ var stringVariable = 'This is a simple string variable'; // string


// variable with data type array
$ var arrayVariable = [1, 2, "three", "four"]; // type array


// variable with data type object
$ var objectVariable = {
                    one: 1,
                    two: 2,
                    three: "three",
                    "four": "four"
                };// type object

/**
* You noticed that the key "four" in the object was added in a quote   ("") while other keys were not, both options are possible as JavaScript is smart enough to know what you are referring to.
*/

Variables can also be declared with let and const in ES6 or ECMAScript 2015.

Example declaring variable using let:

// variable with data type number
$ let numberVariable = 5; // type number


// variable with data type string
$ let stringVariable = 'This is a simple string variable'; // type string


// variable with data type array
$ let arrayVariable = [1, 2, "three", "four"]; // type array


// variable with data type object
$ let objectVariable = {
                    one: 1,
                    two: 2,
                    three: "three",
                    "four": "four"
                };// type object

Example declaring variable using const:

// variable with data type number
$ const numberVariable = 5; // type number


// variable with data type string
$ const stringVariable = 'This is a simple string variable'; // type string


// variable with data type array
$ const arrayVariable = [1, 2, "three", "four"]; // type array


// variable with data type object
$ const objectVariable = {
                    one: 1,
                    two: 2,
                    three: "three",
                    "four": "four"
                }; // type object

You can learn about the differences between var, let and const here.

Thanks for reading 🙏

Happy coding guys 😊 🚀