Every programming language has a fundamental requirement to store data in memory such that computations can be performed on it. The memory location requires a name to store and retrieve this data, and this name is “Variable.”
Additionally, only one type of data can be stored in each memory location. The variable’s “DataType” helps to determine this. In short, each programming language permits the definition and declaration of variables of particular data types because it must perform some computation, and JavaScript is no exception.
What are JavaScript Variables?
Anything that can change is considered to be a variable. A variable in JavaScript saves data that can be modified later.
An object (or designated memory space) called a JavaScript variable is used to hold a value that can be used throughout program execution. Just as in other programming languages, a variable in JavaScript has a title, a value, and a memory address.
- The variable is uniquely identified by its name,
- The value pertains to the information kept in the variable, and
- The variable’s memory location is indicated by the memory address.
To put it another way, a variable can be thought of as a container that can be used to hold values, and you must declare a variable before using it.
How to Declare a Variable in JavaScript?
In JavaScript, defining a variable is referred to as “Declaring” a variable. Additionally, the “var” keyword is utilised to declare the variable.
Example: var test
Here, the declared variable’s name is test. Hence the syntax is var test.
The equal (=) sign can be used to give the variable a value after the declaration.
Example:
test = 10, where the test is the variable’s name and has been given the value of 10.
The JavaScript keywords var, let, and const can be used to declare variables.
- Var: Since JavaScript was developed, the var keyword has been used to declare variables. When variables are declared using var, it is unclear and prone to error.
- Let: The let keyword gets rid of var’s ambiguity and error. The new and advised method of declaring variables in JavaScript is this one.
- Const: A constant variable is one that, once given a value, cannot be modified; it is declared with the const keyword.
In JavaScript, variable names are case-sensitive. The let keyword cannot be used to declare a duplicate variable with the same name or case. A syntax error will be issued by JavaScript. Nevertheless, if they are declared with the var keyword, variables might share the same name (this is why it is best to use let).
Rules for Establishing JavaScript Variables
JavaScript has created a set of rules that regulate the appropriate naming conventions for the variables, much like all other programming languages. A few of these laws include:
- The first character of a variable name must be a letter, an underscore (_), or a dollar symbol ($).
- You can use numbers after the initial letter, underline, or dollar.
- Spaces are not permitted in variable names.
- JavaScript class variables are case-sensitive.
- Reserved words, such as abstract, final, etc., cannot be used as variable names.
- The script> tag allows JavaScript code to be included in an HTML document.
Example:
// Valid variables
var test1 = 10; // Started with letter
var _test = “Demo”; // Started with UnderScore(_)
var $test1 = true; // Started with dollar sign($)
// Invalid variables
var 1test = 10; // Started with letter 1
var *test = “value”; // Started with special character(*)
What Is the Scope of JavaScript Variables?
The section of the program that grants access to a variable is its scope. There are two categories of scopes in JavaScript:
- Local Scope
JavaScript environment variables fall under the local scope when they are declared inside a function, method, or block. These methods/functions or blocks are the only places where these variables can be accessed.
E.g., Consider the code excerpt below, where the checkVariable() method contains the myVar variable’s declaration and accessibility. This variable in no way has access outside of this procedure.
<html>
<head>
<script type = "text/JavaScript">
function checkVariable( ) {
// local variable just accessed in this feature
myVar = "ToolsQA";
document.write(myVar);
}
</script>
</head>
<body onload = checkVariable()>
</body>
</html>
Now, consider the following scenario when a user wants to access a local variable specified in one method from another method:
<html>
<head>
<script type="text/JavaScript">
function checkVariable( ) {
// local variable declaration and setup
var myVar = "ToolsQA";
}
function clickButton(){
// try accessing local variable in another method
alert(myVar);
}
</script>
</head>
<body onload=checkVariable()>
<button onclick="clickButton()">Click me</button>
</body>
</html>
Open any browser and save the file with the name localVariablesOutOfScope.html (Chrome, Firefox, or IE). Let’s say we launch the Chrome browser and open the Html document. Now, right-click the browser screen and choose inspect from the context menu to launch the Chrome browser’s “console.” To access Chrome’s console, click the “console” tab. To view the output, press the “Click me” button now.
- Global Scope
In JavaScript, variables declared outside of all the functions or methods are referred to as global variables and are accessible to all methods, functions, and blocks.
For instance, in the code excerpt below:
<html>
<head>
<script type="text/JavaScript">
//this is the global variable, and it can be accessed in all the functions
var myVar;
function checkVariable( ) {
// Assign value to the global variable
myVar = "ToolsQA";
}
function clickButton(){
// Print value of the global variable
alert(myVar);
}
</script>
</head>
<body onload=checkVariable()>
<button onclick="clickButton()">Click me</button>
</body>
</html>
The variable myVar is declared in the global scope (immediately within the script> element). Additionally, it is given a value inside the checkVariable method (). The variable is then notified again in the method clickButton(), which publishes the same value that was assigned to it in the method checkVariable(). This demonstrates that global variables maintain their values throughout the global scope, regardless of where they are invoked.
Conclusion
A JavaScript variable is the name of a storage location. It is a label for a value, such as a string or a number. However, you must declare a variable before using it. Now that you know the basics of JavaScript variables, don’t be afraid to use them in your projects.
5 Day Coding Challenge – learn JavaScript basics
Code Institute’s free 5 Day Coding Challenge can offer you some insights into HTML, CSS & JavaScript. The best thing about the challenge, other than learning the basics, is that it’ll let you know if you have an aptitude for software development. Register for this weekly challenge through the form below. Alternatively, if you want to learn more about our Full Stack Software Development programme, follow this link.