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.

  • 🔘 Declaration: The keyword var, let, or const creates the name before any line of code reads or writes it.
  • ☑️ Assignment: A single equals sign copies a value into the variable, either on the declaration line or later.
  • Naming: Names begin with a letter, dollar sign, or underscore, and uppercase and lowercase letters count as different.
  • 🧪 Modern keywords: const suits values that never change, let suits values that do, and var survives mainly in legacy scripts.
  • 🛠️ Scope: let and const stay inside their enclosing braces, while var reaches the whole surrounding function.
  • 📌 Common faults: Reassigning a const, reading a let too early, or omitting the keyword each raise a distinct error.

Declaring a JavaScript variable and assigning a value to it

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:

  1. The first character must be a letter, a dollar sign, or an underscore — never a digit.
  2. After the first character, letters, digits, dollar signs, and underscores are all allowed.
  3. Spaces are not allowed, which is why a two-word idea is joined as studentName rather than left as two words.
  4. 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.

FAQs

Any of them. JavaScript is dynamically typed, so one variable may hold a number, then a string, then an object. The declaration reserves a name, not a type. Use typeof to check what a variable holds at any moment.

JavaScript creates an implicit global variable, which other code can overwrite by accident. Adding “use strict” at the top of the file turns the same line into a ReferenceError, so the mistake appears immediately instead of spreading silently.

undefined means the variable was declared but never given a value. null is a value you assign on purpose to mean “nothing here”. Both are falsy, yet typeof undefined returns “undefined” while typeof null returns “object”.

The plus operator joins text whenever either side is a string, so 22 + “3” produces “223”. Convert first with Number() or parseInt() when arithmetic is intended. Subtraction has no text meaning, so “3” − 1 correctly returns 2.

Yes. const locks the binding, not the value, so properties of a const object and elements of a const array can still change. Reassigning the variable itself throws a TypeError. Use Object.freeze() when the contents must stay fixed.

AI assistants built into modern editors propose a keyword and a descriptive name from the surrounding context, flag a var that should be const, and rename every usage in one step. Treat each suggestion as a draft and confirm the scope is correct.

Often, yes. Copilot reads nearby code and offers names matching the surrounding style, which helps replace placeholders such as x or temp. Review every name, because a fluent suggestion can still describe the wrong thing.

console.log() prints the current value to the browser console. For a closer look, set a breakpoint in the Sources panel of DevTools and hover the name, or add it to the Watch list, to read the value at that exact line.

Summarize this post with: