JavaScript Variables, Scope, and Hoisting

What Are Variables?

In simple terms, variables are containers that store values. For instance, if we want to store some information that we refer to several times, we could store it in a variable to access it later or modify it. We could store a number, string, or object, or any other data types in JavaScript variable containers. Modern JavaScript is based on the ECMAScript 2015 (ES6) language specification, which expanded variable declarations from the var keyword that was the only one available initially. That is why you will only find the var in older learning resources. In this tutorial, we have dedicated an entire section to explore the differences between var, let, and const keywords below. We shall use just one type o define the variable concept by declaring it and then assigning a value to it:

// Assign the string value Sam to the username identifier
var username = "sam_shark";
  1. The var keyword has been used to declare a variable
  2. The username is our variable identifier or variable name
  3. The = syntax represents an assignment operation for our statement
  4. The value in our case is “sam_shark”
// Check if variable is equal to value
if (username === "sam_shark") {
console.log(true);
}
Output
true
// Assignment of various variables
var name = "Sam";
var warriors = 300;
var kingdoms = [ "mammals", "birds", "amphibian" ];
var poem = { roses: "red", bananas: "green" };
var success = true;
var nothing = null;
// Send warriors variable to the console
console.log(warriors);
Output
300
// Assign value to password variable
var password = "pass1";
// Reassign variable value with a new value
password = "pass2";
console.log(password);
Output
'pass2'

How to Name Variables

In JavaScript, variable names are also referred to as identifiers. However, you need to have the following rules in mind when you are naming variables:

  1. The composition of variable names can only be letters (a-z), numbers (0–9), dollar sign symbols ($), or underscores (_)
  2. You may include whitespace characters (tabs or spaces) in variable names
  3. The names of variables cannot begin with numbers
  4. You cannot use any of the reserved keywords as variable names
  5. Variable names are case sensitive

Differentiating var, let, and const

As mentioned earlier, the three keywords are the only way to define JavaScript variables. Their use-cases are three-pronged, scope, hoisting and reassignment as described by the rable below:

Understanding Scope

When defining the current context of code, we use scope as the metric. It is a measure of variable accessibility in JavaScript. Scope id of two types: local and global:

  1. We define scope as Global when variables outside of a block
  2. The scope is Local when variables are inside of a block
// Initialize a global variable
var creature = "fox";
// Initialize a global variable
var species = "man";
function transform() {
// Initialize a local, function-scoped variable
var species = "cat";
console.log(species);
}
// Log the global and local variable
console.log(species);
transform();
console.log(species);
Output
man
cat
man
var fullMoon = true;// Initialize a global variable
let species = "man";
if (fullMoon) {
// Initialize a block-scoped variable
let species = "cat";
console.log(`It is a full moon. Presley is currently a ${species}.`);
}
console.log(`It is not a full moon. Presley is currently a ${species}.`);
Output
It is a full moon. Presley is currently a cat.
It is not a full moon. Presley is currently a man.
// Use var to initialize a variable
var species = "man";
if (fullMoon) {
// Attempt to create a new variable in a block
var species = "cat";
console.log(`It is a full moon. Presley is currently a ${species}.`);
}
console.log(`It is not a full moon. Presley is currently a ${species}.`);
Output
It is a full moon. Presley is currently a cat.
It is not a full moon. Presley is currently a cat.

Hoisting

In the examples that we have explored above, we have declared variables using var and also used a value to initialize it. Subsequently, we can further access or reassign variables that have been declared and initialized. Trying to use variables before declaring and initializing them returns undefined.

// Attempt to use a variable before its declaration
console.log(x);
// Variable task
var x = 300;
Output
undefined
// Attempt to use a variable before it is declared
console.log(x);
// Variable task without var
x = 300;
Output
ReferenceError: x is not defined
// The code we used
console.log(x);
var x = 300;
// JavaScript interpretation
var x;
console.log(x);
x = 300;
// Initialize x in the global scope
var x = 300;
function hoist() {
// this condition should not affect the outcome of our code
if (false) {
var x = 400;
}
console.log(x);
}
hoist();
Output
undefined
// We initiate x in the global scope
let x = true;
function hoist() {
// Initiate x in the function scope
if (3 === 4) {
let x = false;
}
console.log(x);
}
hoist();
Output
true
// Try to overwrite a variable that is declared with var
var x = 2;
var x = 3;
console.log(x);
Output
3
// Attempt to overwrite a variable declared with let
let y = 2;
let y = 3;
console.log(y);
Output
Uncaught SyntaxError: Identifier 'y' has already been declared
In summary, when we introduce variables with var, they are exposed to hoisting since JavaScript may end up saving them in the memory. The result for the behavior may be code with some undefined variables. With let and const variables, however, we can avoid the problem since it will not allow declaration of a variable twice. They also do not allow using variables before declaring them.

JavaScript Constants

You are likely to encounter constants in nearly all programming languages. Constants cannot be either changed or modified. The JavaScript representation of a constant is by the const identifier. It is not possible to reassign values assigned to a const. Commonly, const identifiers are written in uppercase to distinguish them from other variables. Let us explore this concept by initializing a variable SPECIES as a constant with const. any attempt to reassign the variable yields an error:

// Assign the value to const
const SPECIES = "man";
// Try to reassign value
SPECIES = "cat";
console.log(SPECIES);
Output
Uncaught TypeError: Assignment to constant variable.
// Declare the constant but do not initialize it
const DO;
console.log(DO);
Output
Uncaught SyntaxError: Missing initializer in const declaration
// Create a VEHICLE object with two properties
const VEHICLE = {
color: "red",
price: 25000
}
// Modify a property of VEHICLE
CAR.price = 30000;
console.log(CAR);
Output
{ color: 'red', price: 30000 }

Conclusion

We have explored in this tutorial the concept of variables, rules governing their naming and the method of reassigning values in variables. You may also compare how the approach works with other programming languages.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alibaba Cloud

Alibaba Cloud

4.97K Followers

Follow me to keep abreast with the latest technology news, industry insights, and developer trends. Alibaba Cloud website:https://www.alibabacloud.com