Variables are an essential part of every programming language. So, you should understand the variables’ basics before diving into the application.
In this article, I would like to present a few points about Javascript variables.
Variables are used to store data values. They simplify multiple usage by calling the variable name.
An equal sign is used to assign values to variables.
To declare a variable in JavaScript, we can use three keywords:
let x = 5;
You can declare many variables in one statement.
var name = "Butter", age = 2;
let
only allows us to declare a variable once.let
is limited to a block statement that it’s declared.var
, it’s declared globally or locally if it’s inside a function.With var
function checkScope() {
"use strict";
var i = "function scope";
if (true) {
i = "block scope";
console.log("Block scope i is: ", i);
}
console.log("Function scope i is: ", i);
return i;
}
checkScope();
// Block scope i is: ,"block scope"
// Function scope i is: ,"block scope"
With let
function checkScope() {
"use strict";
let i = "function scope";
if (true) {
let i = "block scope";
console.log("Block scope i is: ", i);
}
console.log("Function scope i is: ", i);
return i;
}
checkScope();
// Block scope i is: ,"block scope"
// Function scope i is: ,"function scope"
const
has all features of let, but it’s read-only, and we can’t reassign the value of const.
However, we can mutate an array declared with const
.
const s = [1, 2, 3];
function edit() {
"use strict";
//s = [4, 5, 6];
s[0] = 4;
s[1] = 5;
s[2] = 6;
}
edit();
Like other languages, JS variable name must follow these rules:
Example
// Correct
const book;
const _book;
const book1;
// Wrong
const 10book;
Scope indicates if some variables are accessible/inaccessible from other parts of the program.
The global namespace is the space in our code that contains globally scoped information.
We have scope pollution when too many variables exist in a namespace, or variable names are reused.
Global variables are variables that exist within the global scope. They can be accessed by any code in the program, including code in blocks.
const name = "Mira";
const returnName = () => {
return name;
};
console.log(returnName()); // Mira
Local variables are variables that exist within the block scope.
When a variable is defined inside a block, it is only accessible to the code within the curly braces {}
const returnName = () => {
let name = "Mira";
console.log(name); // Mira
};
returnName(); // Mira
console.log(name); // ReferenceError