loading...
Cover image for JavaScript Variables πŸ€”

JavaScript Variables πŸ€”

irenejpopova profile image Irena Popova πŸ‘©πŸ»β€πŸ’» ・5 min read

DCI πŸ‘©πŸ»β€πŸ’»
Variables are a fundamental part of many programming languages, and are among the first and most important concepts for novice coders to learn. There are a number of different properties of variables in JavaScript, as well as several rules which must be followed when naming them. In JavaScript, there are three keywords used to declare a variable β€” var, let, and const β€” and each one affects how the code will interpret the variable differently.

I will cover what variables are, how to declare and name them, and also take a closer look at the difference between var, let, and const. The effects of hoisting and the significance of global and local scope to a variable’s behavior will also be reviewed.

What is actually a variable? πŸ€”

A variable is a named container used for storing values. A piece of information that we might reference multiple times can be stored in a variable for later use or modification. In JavaScript, the value contained inside a variable can be any JavaScript data type, including a number, string, or object.

In ES5 there was only one way to declare a variable β€” using the var keyword. As a result, most older code and learning resources will only use var for variables. I will point out the differences between var, let, and const keywords later.

How we can use var?

We can use var to demonstrate the concept of a variable itself. In the example below, we will declare a variable, and assign a value to it.

// Assign the string value Sammy to the username identifier
var username = "irie_flower";

The parts of this statement are:

πŸ‘‰ The declaration of a variable using the var keyword
πŸ‘‰ The variable name (or identifier), username
πŸ‘‰ The assignment operation, represented by the =syntax
πŸ‘‰ The value being assigned, "irie_flower"

πŸš€ Let's use username in code. JavaScript will remember that username represents the string value πŸ‘‰ irie_flower.

// Check if variable is equal to value
if (username === "irie_flower") {
  console.log(true);
}
// Output:
true

Actually variables can be used to represent any JavaScript data type. In this example, we’ll declare variables with string, number, object, Boolean, and null values.

// Assignment of various variables
var name = "Floris";
var participants = 100;
var countries = [ "England", "France", "Germany" ];
var poem = { roses: "red", violets: "blue" };
var success = true;
var nothing = null;

If we want to see the value contained in a specific variable this can be done by using console.log.

// Send spartans variable to the console
console.log(participants);
Output
100

πŸ€” Variables store data in memory which can later be accessed and modified. Variables can also be reassigned and given a new value. The simplified example below demonstrates how a password might be stored to a variable and then updated.

// Assign value to password variable
var password = "sunflower23";

// Reassign variable value with a new value
password = "sunflower20";

console.log(password);
// output: sunflower20

The example illustrates a situation in which we might need to update the value of a variable. The value of password was sunflower23, but reassigned it to sunflower20 which is the value JavaScript recognises from that point forward. But for security reasons the password can be stored in a database.

How to name variables ? πŸ€”

In JavaScript variable names are known as identifiers

πŸ‘‰ Variable names can consist only of letters (a-z), numbers (0-9), dollar sign symbols ($), and underscores (_)
πŸ‘‰ Variable names cannot contain any whitespace characters (tabs or spaces)
πŸ‘‰ Numbers cannot begin the name of any variable
πŸ‘‰ There are several reserved keywords which cannot be used as the name of a variable

JavaScript also has the convention of using camel case (sometimes stylized as camelCase) in the names of functions and variables declared with var or let. This is the practice of writing the first word lowercase, and then capitalizing the first letter of every subsequent word with no spaces between them. Most variables that are not constants will follow this convention, with some exceptions. The names of variables that are constant, declared with the const keyword, are typically written in all uppercase.
Difference Between var, let, and const
JavaScript has three different keywords to declare a variable, which adds an extra layer of intricacy to the language. The differences between the three are based on scope, hoisting, and reassignment.

USAGE

var has:

  • Function scope, hoisting, can be reassigned and declared ; let
  • Block scope, can be reassigned; const
  • Block scope

If you are wondering which of the three you should use in your own programs. A commonly accepted practice is to use const as much as possible, and let in the case of loops and reassignment. Generally, var can be avoided outside of working on legacy code.

What is a Variable Scope? πŸ€”

Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript. There are two types of scope are local and global:

Global variables are those declared outside of a block
Local variables are those declared inside of a block
In the example below, we will create a global variable.

// Initialize a global variable
var creature = "fairy";

Variables can be reassigned. Using local scope, we can actually create new variables with the same name as a variable in an outer scope without changing or reassigning the original value.

In the example below, the global variable is species.

  • Within the function is a local variable with the same name;

  • By sending them to the console, we can see how the variable’s value is different depending on the scope, and the original value is not changed.

// Initialize a global variable
var species = "human";

function transform() {
  // Initialize a local, function-scoped variable
  var species = "fairy";
  console.log(species);
}

// Log the global and local variable
console.log(species);
transform();
console.log(species);

// Output : human, fairy, human

In the example above, the local variable is function-scoped. Variables declared with the var keyword are always unction-scoped, meaning they recognise functions as having a separate scope. This locally-scoped variable is therefore not accessible from the global scope.

  • The new keywords let and const, however, are block-scoped. This means that a new, local scope is created from any kind of block, including function blocks, if statements, and for and while loops.

To illustrate the difference between function- and block-scoped variables, let's assign a new variable in an if block by using let.

var dayLight = true;

// Initialize a global variable
let species = "human";

if (dayLight) {
  // Initialize a block-scoped variable
  let species = "fairy";
  console.log(`It is a day light. Morgana is currently a ${species}.`);
}

console.log(`It is not a day light.  is currently a ${species}.`);
// Output
//It is a day Light. Morgana is currently a fairy.
//It is not a day Light. Morgana is currently a human.

The species variable has one value globally (human), and another value locally (fairy). If we were to use var, however, there would be a different result.

// Use var to initialize a variable
var species = "human";

if (dayLight) {
  // Attempt to create a new variable in a block
  var species = "fairy";
  console.log(`It is a day light. Morgana is currently a ${species}.`);
}

console.log(`It is not a day light. Morgana is currently a ${species}.`);

//Output
//It is a day light. Morgana is currently a fairy.
//It is not a day light. Morgana is currently a fairy.

In the output of this example, both the global variableand the block-scoped variable end up with the same value, fairy.

  • This is because instead of creating a new local variable with var, the same variable is reassigned in the same scope. var does not recognise if to be part of a different,new scope. It is generally recommended that you declare variables that are block-scoped, as they produce code that is less likely to unintentionally override variable values.

Posted on by:

Discussion

markdown guide