JavaScript Variable
A JavaScript variable is essentially a name assigned to a storage location. In
JavaScript, variables can be classified into two types: local variables and
global variables.
There are certain rules to follow when declaring a JavaScript variable, also
known as an identifier.
1. The name must begin with a letter (a to z or A to Z), an
underscore (_), or a dollar sign ($).
2. After the first letter, digits (0 to 9) can be used, such as in `value1`.
3. JavaScript variables are case-sensitive, meaning `x` and `X`
are considered different variables.
Correct javascript variables
var name = "Anya";
Var age = 19;
Incorrect javscript Variables
var my,name = "Anya";
Example of javascript variable
Let's take a look at a simple example of a JavaScript variable.
<Script>
var a = 5;
var b= 4;
var c= a+b;
Console.log(c);
</Script>
Output: 9
JavaScript local variable
A JavaScript local variable is declared inside a block or function and is only
accessible within that specific function or block. For example:
<Script>
function calculateArea() {
var radius = 5;
var area = 3.14 * radius * radius;
console.log("The area is: " + area);
}
calculateArea();
</Script>
JavaScript global variable
A JavaScript global variable can be accessed from any function. A variable
declared outside of a function or with the `window` object is known as a
global variable. For example:
<Script>
var userName = "Anya";
function greetUser() {
console.log("Hello, " + userName + "!");
}
function changeUserName() {
userName = "Yor";
}
// Call the functions
greetUser();
changeUserName();
greetUser();
console.log(userName);
</Script>