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.”
- 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.
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.
test = 10, where the test is the variable’s name and has been given the value of 10.
- Const: A constant variable is one that, once given a value, cannot be modified; it is declared with the const keyword.
- 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.
- Reserved words, such as abstract, final, etc., cannot be used as variable names.
// 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(*)
- Local Scope
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.
Now, consider the following scenario when a user wants to access a local variable specified in one method from another method:
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
For instance, in the code excerpt below:
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.