The JS Series: JavaScript Variables.
Tags: webdev, javascript, beginners, programming
Published: 2024-03-09 10:16:30

## Introduction

Variables are important in not just JavaScript but other programming languages as well. This article talks about variables and how they can be used in JavaScript.

#### Table of Contents
- What is a Variable?
- How to declare a Variable.
- How to Initialize a Variable.
- Variable naming conventions and multi-word formatting.
- var, let and const.
- Difference between var, let and const.
- Variable scope and hoisting.
- Summary.

### What is a Variable?
JavaScript variables are containers for pieces of data. They store and track data to be used in a code base. Variables can be likened to a label used to identify a product. An example would be labelling a spice jar in a kitchen cabinet. Let's call it a curry spice jar. Initially, it can be filled with a certain amount of curry, say 50 grams.The jar (variable) holds the dynamic quantity needed for cooking (program). Whenever the cook (programmer) needs to add curry to the meal, she fetches the jar (variable) and adds the quantity needed to the meal. 

### How to declare a Variable
Declaring a variable in Javascript simply means using the javascript reserved keywords to create a named storage location for holding data. The JavaScript reserved words used for this are the `var` and `let` keywords. Reserved words are keywords in JavaScript that have special meanings and specific functions. These keywords cannot be used as identifiers. Other examples include the `switch,const, return, this` etc. 
```javascript
// Syntax for declaring a variable.
var <identifier>; 
let <identifier>;

// Examples
var car;
var fullname;
let gender;
```

### How to Initialize a Variable
Initializing a variable simply means assigning a value to the declared variable using an assignment operator. A variable can be initialized using the `var`, `let` and `const` keywords. When a variable is declared in many programming languages, a named storage location in memory is created. Initializing the variable means giving it an initial value. This can be done at the time of declaration or later in the code. A variable can take any data type as its value. 

```javascript
// Syntax for initialising a variable.
var <identifier> = <value>;
const <identifier> = <value>;
let <identifier> = <value>;

//Examples.
let schoolname = "Marist Brothers" ;
let age = 5;
const color = "red";

// Multiple variables can also be declared in one statement.
let age = 5, carname = "volvo" ,location = "canada" ;
```
Note: A semi-colon is added at the end after a variable has been declared or initialized. This is an indicator to terminate the statement. 

A variable can have its value reassigned, but this can only be done with `let` and `var` but not `const`. The `const` keyword, as its name suggests, is specifically designed for variables that act as constants, signifying that their values are meant to stay constant and not be altered during the program's execution. This is better explained with the examples below.

```javascript
// Examples

let age = 6;
age = 7;
console.log(age);
// Result: 7;

var name = "Rick";
name = "Morty";
console.log(age);
// Result: Morty;

const car = "Impala";
car = "Volvo";
console.log(car)
// Result: An error will be logged.
```
However, when a variable initialised with `const` has an array or an object as its value, the properties of the object or the contents of the array can be updated. This is because Arrays and Objects in JavaScript are mutable. It means that an object or an array can be modified or altered after it has been created. Remember that the value of a variable initialized with `const` cannot be changed.

```javascript
// Correct
const employeeNames = ["Ricky", "Dom", "Charlize"];
employeeNames.push("Clare");
console.log(employeeNames);
// Result: Ricky, Dom, Charlize, Clare.

const employeeNames = ["Ricky", "Dom", "Charlize"];
employeeNames[3] = "Victoria";
console.log(employeeNames);
// Result: Ricky, Dom, Charlize, Victoria.

const employeeDetails = {
 age:4,
 location:"Nigeria"
} 
employeeDetails.title = "Developer";
console.log(employeeDetails);
// Result: {age:4,location:Nigeria,title:Developer}

// incorrect
const car = "Impala";
car = "Volvo";
console.log(car)
// Result: An error will be logged.

//or
const employeeNames = ["Ricky", "Dom", "Charlize"];
employeeNames = 5;
console.log(employeeNames);
// Result: An error will be logged.

const employeeNames = ["Ricky", "Dom", "Charlize"];
employeeNames = ["Stella", "Clara", "Bosco"];
console.log(employeeNames);
// Result: An error will be logged.
```

### Variable naming conventions and multi-word formatting
JavaScript variables are given unique names or identifiers. They are case-sensitive as well, meaning that _mycar_ is different from _MYCAR_ and _myCar_. Below are some of the rules involved in naming variables.
- A variable name can include an alphabet, a digit, an underscore and a dollar sign.
- A variable name must not start with a digit but can start with a letter, an underscore or a dollar sign.
- A variable name must not be/contain reserved words in JavaScript.

Multi-word formatting is the strategy we use when naming variables that are made up of two words in JavaScript. It involves arranging and presenting compound words to generate meaningful and understandable variable names within the language. Some of the different formats we can use include;
- Camel Case - myCar, mySchool, myAge.
- Pascal Case - MyCar, MySchool, EmployeeName.
- Snake Case - employee_name, my_current_age, current_index.
- Kebab Case - current-index, current-age,my-variable.
- Uppercase - MYCAR, NEWAGE, ROLE.

### var, let and const
The `var`, `let` and `const` keywords are JavaScript-reserved words used to declare and initialize a variable. Using the `var` keyword is the oldest and still acceptable way to declare a variable. It is compatible with older browsers. The `let` and `const` are part of the features that were introduced in 2015 as an ECMAScript standard, specifically in ECMAScript 6 (ES6). Though they all perform the same function, there are differences between the three.

### Difference between var, let and const
- `var` does not have block scope while `const` and `let` both have block scope.
- Variables declared with `var` can be used before it is declared(hoisting).
- Variables declared with `let` and `const` must be declared before it is used.
- Variables declared with `const` cannot be reassigned while 
 variables declared with let and const can be reassigned.
```javascript
// Example
const pi = 3.14;
pi = 2; // throws an error.
```
- Variables declared with let cannot be redeclared in the same scope.

### Scope and Hoisting
Scope refers to where variables are available for use in the code. There is the Global scope, the Function scope and the Block scope. A variable declared in a global scope means that it can be accessible from any point of the codebase. 

```javascript
var name = "Alex";
function handlePrintName (){
 console.log(name);
}
handlePrintName();
// Result: Alex.
```
The example above explains the global scope. The variable name is accessible from every part of the code.

A variable declared in the function scope means that it is only accessible inside the function where it is declared.

```javascript
function handlePrintName (){
 var name = "Alex";
}
console.log(name);
// Result: An error in the console
```
The above example means that the variable name can only be accessed inside the `handlePrintName` function.

The Block scope means that a variable can only be accessed within a particular block of code. The `let` and `const` keywords have block scope but the `var` keyword does not. 
```javascript
var age = 27;
if(age){
 var doubleAge = age + age;
}
console.log(doubleAge);
// Result: 54
```
The result above is referred to as leakage because it shouldn’t be accessible outside of the block. To fix this, we can use a `let` or `const` keyword and print the _doubleAge_ variable inside the if block.
```javascript
// Correct
let age = 27;
if(age){
 let doubleAge = age + age;
 console.log(doubleAge);
}
// Result: 54

// Incorrect
let age = 27;
if(age){
 let doubleAge = age + age;
}
console.log(doubleAge);
// Result: An error in the console.
```
Hoisting is JavaScript's behavior of moving declarations to the top. In other words, a variable in JavaScript can be used before it is declared. Note that variables declared with `let` and `const` cannot be hoisted.
```javascript
// An example of hoisting with var keyword.
x = 4;
var x;
console.log(x);
// Result: 4.
```

### Summary
Javascript variables are containers for storing different types of data and understanding them and  their declaration, initialization, naming conventions, and scope is fundamental for effective coding and data management in JavaScript programming.