Variables are one of the fundamental concepts in any programming language. Their use varies in programming languages, yet all variables can be described as a special container for storing data during script execution. This data can be retrieved, modified and assigned to other variables, for example, to any string or logical state (true/false).

In JavaScript, the specifics of using variables depend on the current version of JS (ECMA Standards). All variables are dynamically typed, meaning that the compiler manually determines the required data type (string, bool, etc.) according to the context. But since ES2015, two new ways to declare variables have emerged, which differ significantly from each other. 

Modern JavaScript code writing standards recommend using these new types of variables only. However, there is always a possibility that one would have to deal with legacy code, so we will consider the features of 3 types of variables in JavaScript.

Terms

  • Variable - a special "container" for storing data. Access and use rules of a variable  depend on the type and content inside it.

  • Data type - in JavaScript variables can be stored in 3 data types, called primitives: string, number, bool. In addition, Objects and Arrays can be stored as well.

  • Type of variable - one of three types of variables (let, const, var), which determines its use during the script, in particular its scope.

  • Variable name - allows accessing a variable to read its data (content) or adding new content to it. Depending on the context, requirements may be imposed in regards to the name uniqueness and symbols used.

  • Declaring a variable - the process of specifying the type and name of a variable. 

  • Variable initialization - the assignment of a specific value to a declared variable.

  • Scope - conditional part of the code, within which a variable is available to requests from other parts of the script. Depending on a selected variable type, global and local scope can be distinguished.

Types of variables

There are 3 types of variables in JavaScript, each with peculiar characteristics.

  1. let variable -  available only within a block, function, or expression. For such variables, it's not required to immediately specify the value as it can be changed during the execution of the script.

  2. const variable - unlike let, its value must be set after declaration and can't be changed later. But this doesn't apply to the values inside Objects and Arrays values.

  3. var variable - has global visibility if declared outside a function. It's value can be changed at any time.

The type of a variable always must be written first during variable declaration, while a proper one must be selected according to the data stored inside. For example, const is best for frequently requested and unchanged data, such as a unique ID or some kind of numerical coefficient.

const ID;
const Pi = 3.14;

let should be used for those variables that can take on different values during script execution, such as UserID, day of the week, or e-mail.

let UserID;
let Day = "Monday";
let price = "23.95";

The use of var is not recommended because it's considered as a deprecated type. However, just like let, it can take on different meanings.

var hour;
var Pi = 3.14;

Scope of variables

We request variables inside the script, to work with the data stored in them. But for optimization and security, Javascript has the concept of variable scoping, which determines the availability of a variable, for example, on line 4 - for a function from line 395. There are 2 types of visibility: global and local. In addition, inside the local type there could be additional scopes: functional and block scopes.

Global scope - a variable with this scope is available from any part of the script. To get this scope for a variable, you must declare it in the body of the script, which means, outside of any functions and statements.

Local scope - the variable is available only within certain parts of the script.

Functional scope - variable, declared inside a function, which is available for any interaction only within this function.

Block scope - variable declared inside a block of code, which is denoted by curly braces in JavaScript. Most often, blocks of code are statements and loops (if, for, etc.) specified outside of functions. But if a code block is placed inside a function, its variables will not be accessible from the function areas located around this block.

let date;
const changer = true;
ChangeDay();
function ChangeDay(){
    let month = "December";
    if (changer){
        let year = 2022;
        date = year + month;
    }
}
console.log(date);

In this example, the variables date and changer have global scope. The month has functional scope, year has block scope, and they both have local scope within their borders. Accordingly, date and changer are available from anywhere in the script, the month variable being used only within the ChangeDay function, while the year is available only inside the if code block.

Variable naming rules

The name of a variable in JavaScript is an identifier that allows you to access its contents. Therefore, there are certain rules for how you can (and should) name variables in order to maintain the code readability and correctness.

  • Variables in the global scope must have unique names.

  • Variables inside the functions (local scope) can have names matching with names of variables from global scope. But in this case, this block of code (or function) during execution will ignore the existence variable with the same name from the global scope.

let text = "send";
SelectText();
function SelectText(){
let text = "word";
console.log(text);
}
console.log(text);

Result

send
word
  • All names are case sensitive. For example, all these lines declaring different variables:

let word;
let WORD;
let wORD;
let WorD;
  • Only upper and lower case English letters, numbers, "$" and "_" symbols can be used in the variable name. In this case, the name of a variable cannot start from the number.

Valid variable names:

let word;
let Word2;
let $wORd;
let wor$_d;
let Wo1_$rd;
  • You can't use spaces and JavaScript reserved words (let, function, else, etc) as a variable name. 

These words can (but not recommended) be used as part of others, for example: myFunction, leftString, newClass. Full list of reserved keywords in JavaScript: link.

Invalid variable names:

let new word; //space
let 1word; // number at the beginning of the name
let w@ord; // signs other than $ and _
let let; // reserved word using
  • It's recommended to use names that outline their goal as clearly as possible. Also "camel input" can be used for complex names.

Simple variable names:

let lastmonthname;
let totalsum;
let currentday;

Variables named with "camel input":

let lastMonthName;
let totalSum;
let currentDay;
  • You can assign a value to a variable in the same line where it was declared.

let currentDay = "Monday".
  • You must declare let and const variables in the code before assigning or requesting their values. This rule doesn't apply to var variables, but their use is generally discouraged.

Allowed let and const variables locations in the code:

let Month;
Month = "January";
const day = "Monday";

Invalid location of let (or const) variables in code:

Month = "January";
let Month;

Valid location for var variables in code:

Month = "January";
var Month;
var day = "Monday";
  • If a requested variable does not exist (isn't declared), it will return null.

console.log(year);

Result

null
  • If a requested variable is declared, but not initialised, it will return undefined.

let year;
console.log(year);

Result

undefined