JavaScript Variables
JavaScript Variables
JavaScript variables are containers used to store data values. Variables are used to hold data in the memory. You can think of them like labeled boxes where you keep information that you want to use later in your program.
Declaring Variables
JavaScript provides three ways to declare variables:
-
var
– Old way (function-scoped, not recommended for modern code). JavaScript variables are declared with the var keyword. It can be used to hold any types of values like numbers, Boolean, strings, objects, etc. -
let
– Modern way (block-scoped, can be updated but not redeclared in the same scope). -
const
– Block-scoped (cannot be reassigned after declaration, but objects/arrays can still be modified).
Examples
Some of the examples are as follows:
var name = "Alice"; // Using var
let age = 25; // Using let
const pi = 3.1416; // Using const
Variable Naming Rules
-
Must start with a letter, underscore
_
, or dollar sign$
. -
Cannot start with a number.
-
Cannot use reserved keywords (like
let
,if
,class
). -
Case-sensitive (
myVar
andmyvar
are different).
Valid Names
let userName = "Naini";
let _count = 5;
let $price = 99.99;
Invalid Names
let 123name = "John"; // Cannot start with number
let let = 10; // Cannot use reserved keywords
—
JavaScript Tutorials
JavaScript tutorials on this website can be found at:
To learn more about JavaScript, visit
- https://www.javascript.com/