JavaScript Variable: Declare, Assign a Value with Example
⚡ Smart Summary
JavaScript variables store values such as names and numbers, or the result of an expression. Declaring one with var, let, or const reserves a named slot that the rest of the script can read and update.
Variables are used to store values (name = “John”) or expressions (sum = x + y). Every value a script keeps for later — a user name, a running total, a yes-or-no flag — lives in a variable, so declaring and naming them well is the first skill to pick up in JavaScript.
Declare Variables in JavaScript
Before using a variable, you first need to declare it. You have to use the keyword var to declare a variable like this:
var name;
The declaration on its own creates the name and nothing more. At this point the variable exists but holds the special value undefined, because no value has been put into it yet.
⚠️ Version note: var is the original declaration keyword and still runs in every browser. ES6 (2015) added let and const, which are the keywords modern JavaScript uses. Both are compared against var further down this page.
Assign a Value to the Variable
You can assign a value to the variable either while declaring the variable or after declaring the variable.
var name = "John";
OR
var name; name = "John";
Both forms finish with the same result. The single equals sign is the assignment operator: it copies the value on its right into the variable on its left. It is not a test for equality, which is written == or === and belongs in conditional statements.
Naming Variables
Though you can name the variables as you like, it is a good programming practice to give descriptive and meaningful names to the variables. Moreover, variable names should start with a letter and they are case sensitive. Hence the variables studentname and studentName are different because the letter n in the name is different (n and N).
Four rules decide whether a name is legal at all:
- The first character must be a letter, a dollar sign, or an underscore — never a digit.
- After the first character, letters, digits, dollar signs, and underscores are all allowed.
- Spaces are not allowed, which is why a two-word idea is joined as studentName rather than left as two words.
- Reserved words such as var, let, const, class, and return cannot be reused as names.
By convention JavaScript names use camelCase, so the first word is lowercase and each later word starts with a capital: firstName, totalPrice, isLoggedIn.
The script below declares two variables, applies the five arithmetic operators to them, and writes each result to the page. Try this yourself:
<html>
<head>
<title>Variables!!!</title>
<script type="text/javascript">
var one = 22;
var two = 3;
var add = one + two;
var minus = one - two;
var multiply = one * two;
var divide = one/two;
document.write("First No: = " + one + "<br />Second No: = " + two + " <br />");
document.write(one + " + " + two + " = " + add + "<br/>");
document.write(one + " - " + two + " = " + minus + "<br/>");
document.write(one + " * " + two + " = " + multiply + "<br/>");
document.write(one + " / " + two + " = " + divide + "<br/>");
</script>
</head>
<body>
</body>
</html>
var vs let vs const in Modern JavaScript
Only var existed when JavaScript was first written, and it has two habits that surprise beginners: it can be re-declared silently, and it ignores block boundaries. let and const were added to fix both. The table below sets the three keywords side by side.
| Behaviour | var | let | const |
|---|---|---|---|
| Scope | Whole function | Enclosing block | Enclosing block |
| Can be reassigned | Yes | Yes | No |
| Can be re-declared in the same scope | Yes | No | No |
| Value required on the declaration line | No | No | Yes |
| Read before its declaration | Returns undefined | ReferenceError | ReferenceError |
A simple habit covers almost every case: reach for const first, switch to let the moment a value genuinely has to change, such as a counter inside one of the JavaScript loops, and keep var for reading old code rather than writing new code.
Variable Scope and Hoisting in JavaScript
Scope decides which parts of a script can see a variable. A var declaration belongs to the function that contains it, so it escapes any if block or for block inside that function. A let or const declaration belongs to the pair of braces it sits in and disappears outside them.
function demo() { if (true) { var wide = "visible throughout demo()"; let narrow = "visible only inside these braces"; } console.log(wide); console.log(narrow); }
The first console.log prints its string. The second throws a ReferenceError, because narrow no longer exists once the if block ends.
Hoisting is the second half of the story. JavaScript registers every declaration in a scope before it runs a single line of that scope. A var name is registered and set to undefined, so reading it early is legal but useless. A let or const name is registered without a value, and the gap between the top of the block and the declaration line is called the temporal dead zone.
console.log(a); var a = 1; console.log(b); let b = 2;
The first line prints undefined. The third line stops with “Cannot access ‘b’ before initialization” — the error that makes let safer than var, because it points at the real mistake instead of hiding it.
Common Errors When Declaring JavaScript Variables
Five messages account for most of the console output beginners see while learning variables. Each one names a specific cause, so the fix is usually a single line.
| Console message | Cause | Fix |
|---|---|---|
| SyntaxError: Identifier ‘x’ has already been declared | let or const used twice for the same name in one block | Reuse the existing variable, or rename the second one |
| TypeError: Assignment to constant variable | A const was given a new value | Declare it with let if the value has to change |
| ReferenceError: Cannot access ‘x’ before initialization | A let or const was read inside the temporal dead zone | Move the read below the declaration line |
| ReferenceError: x is not defined | The name was never declared, or it was misspelt | Declare it, or correct the spelling and the letter case |
| undefined appears where a value was expected | The variable was declared but never assigned | Assign a value before the first read |
Adding “use strict” to the top of a file turns the silent version of the fourth case — assigning to a name that was never declared — into a visible error, which is why it belongs in every new script. The same variable rules carry over unchanged to arrays, objects, and server-side code written for Node.js.
