The following article discusses variables in detail alongside their usage examples as well as their distinguished differences between var, let and const in javascript.
What is Variables
You must first grasp the meaning of data and its programming language use before moving onto variables. A computer program utilizes data as fundamental information which we insert into the system. Users can find data representation on their Twitter profile name.
Instructions in programming exist to handle and present data screens. Programmers must have a method to store data temporarily when their programs execute. This explanation will become clearer by using an illustrative scenario.
Our program executing tool represents the primary requirement before starting. You can run the program using the google chrome dev tool. Shortcut for Windows Ctrl + Shift + J, for Mac Cmd + Option + J.
The console demands a numeric or any form of data entry from us right now. The program will show the same value after you click Enter. The need to retrieve this number later within the program exists.
That’s where Variables come in. The data can be saved inside a variable and its retrieval becomes possible by calling its designated name.
Variables in JavaScript
A variable functions like a name which identifies specific numerical values. Similar to labeled containers filled with oranges one can find the name orange written on the outside. This example points to the value oranges through its variable name orange.
To demonstrate our point we will create a variable named dog and name it my dog jimmy. The var keyword serves us for this use. The assignment operator equal sign functions as the mechanism for assigning variable values.
var dog = ‘jimmy’;
Programmers employ Variables as storage elements for project data which they can later alter or retrieve. Every JavaScript data type can be stored within Variables.
We have placed the value jimmy into the dog variable. The value remains accessible to the program from start to end. Contact the console and input the dog variable name to receive the return value jimmy.
Use Var Keyword in JavaScript
Some reserved words exist within JavaScript known as keywords because JavaScript already defined their meanings. The JavaScript keyword Var functions as a declaration instrument for Variables.
You can initialize a variable anytime after using the Var keyword without initial value requirements. The variable value can be redefined in future instances. Let’s see how to do this.
var dog;
dog = ‘jimmy’
//Or
var dog = ‘jimmy’;
//We can replace like this
dog = ‘Tommy’;
You will obtain the value ‘Tommy’ from the variable dog during your attempt to console it. The written sequence determines how the variable value evolves.
The variable declaration through var keyword enables repetitive variable declaration in your code.
var dog = ‘jenny’;
The result will be the value ‘jenny’.
The developers who created JavaScript specified the var keyword as the exclusive syntax for variable declaration. JavaScript received its recent ECMAScript2015 version which brought both const and let keyword declarations. Understanding the concept of scope must come before studying const and let.
What is Scope?
Scope is simply what it says. There exist rules which regulate the accessibility of declared variables from their creation point. A variable declared inside a function prevents outside functions from reaching it.
var age = 20;
function myAge () {
console.log(age);
}
myAge();
The code established a variable named age that received the numerical value 20. The code implements a myAge function after the age variable assignment. Then we call myAge function. The application demonstrates the number 20 within your console output when executed.
A variable declared in the global scope via the var keyword maintains global scope accessibility. According to its functionality this variable can be utilized in any section of your code base including function parameters.
To achieve function-scoping we must define variables within a function body thus making them accessible only from inside that function.
function myAge () {
var age = 20;
console.log(age)
}
myAge()
console.log(age);
//Result:
//20
//age is not defined
An explanation follows about the 20 years of age and why ‘age is not defined’ occurs. The code execution starts with the function call of myAge which displays the value 20 in the console. The program attempts to display the age variable which resides within the function after its execution. The variable age exists only within the function which produces the error ‘age is not Defined’.
The following section explains the issue that arises from using var inside JavaScript.
Var Keyword Problem in JavaScript
Another example can help us learn this point. The program introduces a variable age before implementing double age operations if age exists.
var age = 20;
if (age) {
var doubleAge = age + age;
console.log(doubleAge);
}
You will find 40 written in the system command.
You can access global variable doubleAge by entering it in the console.
doubleAge
40
The variable doubleAge becomes function-scoped when declared inside a function because we used var keyword outside all functions to create a global variable. The variable maintains availability across all code outside function declaration since we placed it outside of any function. Inside the if condition the doubleAge variable is used but becomes inaccessible outside its block. The functionable scope chairs the issue by making this doubleAge variable available globally throughout the program.
Let’s understand what is blocked.
var age = 20;
if (age) {
// inside the block means, inside this opening and closing braces
var doubleAge = age + age;
console.log(doubleAge);
}
console.log(doubleAge);
// we are able access the doubleAge variable outside the block.
The latest JavaScript update included const together with let because of this problem requirement.
Const Keyword in JavaScript
The constant keyword shares similarities to var yet maintains distinct differences between them.
Block scope defines const while var operates from the scope of functions. The following code contains the const keyword for comparison.
const age = 20;
if (age) {
const doubleAge = age + age;
}
console.log(doubleAge);
Running this code produces the doubleAge is not defined error. The doubleAge variable cannot be accessed because we declared it as const both at the start of the code and within the if block. The block prevents any external access to the doubleAge variable.
The solution to our former problem has been achieved. The doubleAge variable has been permanently assigned to the local scope. The functionality of const keywords deserves examination within the context of functions.
function printX () {
const a = 5;
return a;
}
printX();
The code execution produces the value of ‘a’ as its result. You will encounter the error “x is not defined” when you attempt to access it from locations outside the function. Access to ‘x’ variable outside the function remains impossible because the function block status prevents this action.
A variable cannot acquire a second declaration when created as const. The declaration status makes values immutable since const variables maintain constant values which cannot be modified.
const b = 10;
const b = 20;
The example produces an error which states that “Identifier ‘x’ has already been declared”.
The value of this identifier remains unalterable.
const c = 10;
c = 20;
The display shows “Error: Assignment to constant variable”.
Let Keyword in JavaScript
Let functions similarly to const although it differs in one area. The value of variables declared with let can be updated. Let’s understand with an example.
let isPass = false;
const mark = 60;
if (mark > 50) {
IsPass = true
}
The value of the isPass variable can be changed to true within this section.
Thank you for reading!
We have discussed in this article what variables are as well as the var keyword and variable scopes and blocks alongside const and let keywords. The information in this article should have been beneficial to read.