JS Variable

A JavaScript variable is a named storage location for data. There are two main types of variables in JavaScript: local variables and global variables.

Rules for Declaring JavaScript Variables

1. Name must start with a letter (a to z or A to Z), underscore (_), or dollar ($) sign.

2. After the first letter, you can use digits (0 to 9), for example, value1.

3. JavaScript variables are case sensitive; for example, x and X are different variables.

Correct JavaScript Variables

var x = 10;
var _value = "javascript";

Incorrect JavaScript Variables

var 123 = 30; // Error: variable name cannot start with a digit
var *a = 32; // Error: variable name cannot start with an asterisk

Example:

<!DOCTYPE html>
<html>
<body>

<script>
var x = 35;
var y = 45;
var z = x + y;
document.write(z);
</script>

</body>
</html>

Output:

80

Local and Global Variables

Local Variables

Local variables are declared inside a function and can only be accessed within that function.

function myFunction() {
var localVar = "I'm a local variable";
console.log(localVar); // This will work
}
console.log(localVar); // This will throw an error: localVar is not defined

Global Variables

Global variables are declared outside any function and can be accessed from any function in the script.

var globalVar = "global variable";
function myFunction() {
console.log(globalVar); // This will work
}
console.log(globalVar); // This will also work

Understanding how to correctly declare and use variables is fundamental in JavaScript programming, enabling you to store and manipulate data effectively.