There are 3 Types of variables or ways to define them in JavaScript. The var, let and const keywords are used before the declare variables in JavaScript.
- var – It declares a variable globally or locally to an entire function. This type of variable is function-scoped.
- let – It declares a block-scoped variable that can be updated but not re-declared within the same block.
- const – Declare a block-scoped variable that cannot be updated or re-declared. This type of variable is read-only.
Types of variables in JavaScript example
Simple HTML example code.
<!DOCTYPE html>
<html>
<body>
<script>
// var variable
var x = 5;
function foo() {
var y = 10;
console.log(x);
console.log(y);
}
// let variable
let z = 15;
if (true) {
let z = 20;
console.log(z);
}
console.log(z);
// const variable
const a = 0;
// This will throw an error
//a = 1;
// This will also throw an error
//const a = 2;
</script>
</body>
</html>
Output:
Rules while declaring a JavaScript variable
- Variable names must start with a letter, underscore (_), or dollar sign ($). They cannot start with a number.
- Variable names can contain letters, numbers, underscores, or dollar signs. No other characters are allowed.
- Variable names are case-sensitive, which means that “myVar” and “myvar” are two different variables.
- Avoid using JavaScript-reserved keywords as variable names.
- Always declare your variables with the
var
,let
, orconst
keyword before using them. This will prevent errors and make your code more readable.
let firstName = "John";
const lastName = "Doe";
var age = 30;
JavaScript local variable vs global variable
Local variables are declared inside a function, and they can only be accessed within that function. Global variables, on the other hand, are declared outside any function, and they can be accessed from anywhere in the code, including inside functions.
local variable
function myFunction() {
let x = 10; // local variable
console.log(x); // Output: 10
}
myFunction();
console.log(x); // Output: Uncaught ReferenceError: x is not defined
global variable
let y = 20; // global variable
function myFunction() {
console.log(y); // Output: 20
}
myFunction();
console.log(y); // Output: 20
Do comment if you have any doubts or suggestions on this Js variable topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version