JavaScript Variables: Var, Let and Const

JavaScript Variables: Var, Let and Const

Declaration of Variables in JavaScript and Understanding the Difference between Var, Let and Const

What is a Variable

Variables help us to store values so that we can reuse them. Variables refer to locations in the computer memory where we can store values(information/data) and easily retrieve and reuse them when needed.

Value is the smallest unit of information/data in JavaScript and other programming languages.

The ability to store data in variables that our code can access later on in its execution is an important feature of any programming language.

Variables are an important part of anyone’s JavaScript code. Understanding the various ways to declare variables and why you use them in your code, will help you write code that is clean, easier to read and easier to maintain.

There are three different ways of declaring variables in JavaScript.

  • Var

  • Let

  • Const

Variable declaration with Var

Declaring variables using the var keyword is the oldest way of declaring variables in JavaScript.

Scoping in Var

Scope refers to where these variables are available for use, based on how they are declared by the programmer or the software engineer.

Global Scope: Variables declared with var OUTSIDE the function body are globally scoped and hence the values stored in them are accessible anywhere in the code. Thus you can call, retrieve or reuse the values anywhere in the code.

Hint: Any variable that is declared with the var keyword outside a function block is available for use in the whole window.

Local/Function Scope: Variables declared with var INSIDE the function body are locally scoped and hence their values can only be accessible within the function block.

When you try to access the values of locally scoped variables, outside the function block, it throws ReferenceError.

var person = "Mars"; //Global variable. globally scoped

function greetings() {
  var greet = "Hello JavaScript";//Local variable. functionally scoped
}

// Accessing the variables

console.log(person);//Outputs "Mars"... Because it is globally scoped

console.log(greet);//ReferenceError: greet is not defined... This is so since the variable are Local and only accessible inside the function block

Re-assignment and initialization

The variables declared with the var keyword can be re-assigned, re-declared and updated to another value and do not require initialization upon defining them. Hence you can even use the variable's values before defining the variable

var person; // Variable declared without initialization

person = "Mars"; // variable assignment

console.log(person); // Outputs "Mars"

var person = "Mars"; // Variable declared and initialized

person = "Ifeanyi"; // variable Re-assignment

console.log(person); // Outputs "Ifeanyi"

Hoisting in var

In JavaScript, hoisting is the process by which variables and function declarations are moved to the top of their scope before code execution.

The variables declared using the var keyword are hoisted to the top of their scope and initialized as undefined, hence you can use the variable before it is initialized.

Hint: variable declarations with the var keyword is prone to code conflicts especially when you have the same name in various places in your code. it bugs your code.

Variable declaration with Let

We use the "let" keyword to declare variables that can change later, basically during our program execution. Thus when you have the intention to reassign values to variables then declare the variable with the "let" keyword.

The precise use case for let is to mutate variables in a program ie you can mutate and reassign values to variables declared with the let keyword.

Scoping in Let

Block scope: Variables declared with the let keyword are block-scoped and hence their values are only accessible within the block.

A block is a chunk of code bounded by the curly braces, {}. Anything within curly braces is a block.

let language = "JavaScript";

if (language) {
  // Code Block
  let greeting = "Hello I Love JavaScript"; // Outputs: Hello I Love JavaScript
  console.log(greeting);
}

console.log(greeting); //ReferenceError: greeting is not defined... This is so because the variable "greeting" is block scoped (defined inside a code block)

Re-assignment and initialization

The variables declared with the let keyword can be Re-assigned, Updated but cannot be Re-declared.

As shown in the code snippet, Re-declaring the variables throw SyntaxError

let language;

language = "JavaScript";

console.log(language);

let language = "Solidity"; // warning
console.log(language); //SyntaxError: Identifier 'language' has already been declared

Also, variables declared with the let keyword can be defined without initialization

let language; // variable defined without initialization

language = "JavaScript"; // variable assignment

console.log(language); // Outputs: JavaScript

language = "Solidity"; // variable re-assignment
console.log(language); // Outputs: Solidity

Hoisting in let

The variables declared with the let keyword are hoisted to the top just like var, however, they are NOT initialized. since the variables are not initialized, if you try to use them before declarations, then you will get a Reference Error

Hint: For variables declared with the let keyword, you don't have to bother if you have used a name for a variable before as a variable exists only within its scope.

Also, since a variable cannot be declared more than once within a scope, you are ensured not to have code conflicts and unnecessary bugs

Variable declaration with Const

Const simply means constant, We use the "const" keyword to declare variables that are not supposed to change at any point in the future ie the value in a constant variable cannot be changed.

Thus you cannot mutate or reassign values to a const variable. const helps us to create an immutable variable.

We cannot declare an empty const variable since the variable in const cannot change.

Scoping in Const

Block Scope: Just like in let, variables declared with the const keyword are block-scoped and are only accessible with the code block

function greeting() {
  // code block
  const sayHello = "I love JavaScript";

  console.log(sayHello); // Outputs: I love JavaScript
}
greeting();

console.log(sayHello); //ReferenceError: sayHello is not defined

Re-assignment and initialization

Variables declared with the const keyword are constant and thus cannot be updated nor re-assigned or re-declared. Thus if you try to declare them you will get a warning and SyntaxError upon code execution.

const language = "JavaScript";

console.log(language);

const language = "Solidity"; // Warning
console.log(language); // SyntaxError: Identifier 'language' has already been declared

Also, variables declared with const must be initialized upon the declaration, hence you cannot declare a const variable without assigning a value to it.

Hint: Every const declaration, therefore, must be initialized at the time of declaration.

Hoisting in const

The variables declared with the const keyword are hoisted to the top but are NOT initialized, just like the let, hence you cannot use them before initialization

Which Variable type should you use

Every beginner in JavaScript is often faced with the question of which variable type should I use.

To write clean codes always use 'const' by default and then use 'let' only when you are sure that the variable need to change at some point in the future.

By now you should have known that Var is similar to let but with differences in the scope, however, don't use var because is an old way of declaring a variable and it can bug your code.

Best practices for declaring variables

  • Your variable names should be descriptive enough, to convey information to anyone reading your code. The name should reflect what the variable you declared is doing

  • When declaring your variables, the Constant should be written in Capital Letter. Examples of some known constants are PI (3.142)

  • Use Camelcase for writing your variable names

Summary:

  • variables declared with the var keyword are globally scoped or function scoped while the variables declared with the let and const keywords are block scoped.

  • variables declared with the var keyword can be re-assigned, updated and re-declared within their scope.

  • variables declared with the let keyword can be updated but NOT re-declared.

  • variables declared with the const keyword can neither be updated nor re-declared, they are CONSTANT.

  • variables declared with the var keyword are hoisted at the top of their scope and initialized as undefined.

  • variables declared with the let and const keywords are hoisted at the top of their scope and are NOT initialized.

  • variables declared with the var and let keywords can be declared without being initialized, while variables declared with const MUST be initialized upon declaration.