Variables are simply data storage containers.
- The variable names must always begin with a letter (a-z or A-Z), dollar ($) symbol, or underscore ( )
- We can put numbers (0 to 9) after the initial letter.
Data is raw information that we utilize in computer programs during coding. Your Instagram username, for example, is a raw piece of data.
A large portion of programming is concerned with modifying or presenting data. To accomplish so, programmers require a method of storing and tracking data. Let me provide an example to show this.
We'll start by launching our JS console. Use the shortcut Ctrl + Shift + J on Linux and Windows to open your JS console in the Chrome browser. In contrast, you can use Command + Option + J on a Macbook.
After launching the console, think of a random number and input it into the console. For this article, I'll be using the number Eight (8).
What if we need to refer back to that random number? We'll have to enter it a second time. That's why we need a mechanism to refer to this raw data so that we may use it all through our software.
Thinking of variables as tags for our values is a good comparison. Consider a Peanut jar with the word "Peanuts" on it. The variable, Peanuts, in this case, points to a value, which is the Peanuts themselves.
Let's define a variable, age, then we assign our random number (value), 8, to it using the assignment operator. We'll employ the "var" keyword.
var age = 8
We may refer to this number later now that we have assigned it to the variable age. If you now put the variable age into your console, you will get the number 4 back. It's like a shortcut to that number "Eight."
- Local Variables, on the other hand, are only accessible within the function in which it is declared. Function parameters always have to be function-specific.
A local variable having the same name takes priority over a global variable having the same name in the body of a function. When you define a local variable having the exact name as a global variable, the global variable is essentially hidden. Consider the following illustration:
Declaring Multiple Variables
These can be specified on the same line, split with a comma.
var one = 1, two = 'two', three;