---
description: Variables are used to store values (name = &quot;John&quot;) or expressions (sum = x + y). Before using a variable, you first need to declare it. You have to use the keyword var to declare a variable
title: "JavaScript Variable: Declare, Assign a Value with Example"
image: https://www.guru99.com/images/javascript-variables-declare-assign.png
---

[Skip to content](#main)

**⚡ 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.

Read More

![Declaring a JavaScript variable and assigning a value to it](https://www.guru99.com/images/javascript-variables-declare-assign.png)

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](https://www.guru99.com/introduction-to-javascript.html).

## 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](https://www.guru99.com/how-to-use-conditional-statements-in-javascript.html).

## 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](https://www.guru99.com/how-to-use-loops-in-javascript.html), and keep var for reading old code rather than writing new code.

**Don't Miss:**

- [JavaScript Define & Call Functions with Example](https://www.guru99.com/learn-functions-in-javascript-in-5-minutes.html)
- [Cookies in JavaScript: Set, Get & Delete Example](https://www.guru99.com/cookies-in-javascript-ultimate-guide.html)
- [Execute JavaScript Online](https://www.guru99.com/execute-javascript-online.html)
- [Difference Between =, ==, and === in JavaScript \[Examples\]](https://www.guru99.com/difference-equality-strict-operator-javascript.html "Difference Between =, ==, and === in JavaScript [Examples]")

## 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](https://www.guru99.com/learn-arrays-in-javascript.html), [objects](https://www.guru99.com/learn-object-oriented-javascript.html), and server-side code written for [Node.js](https://www.guru99.com/node-js-tutorial.html).

## FAQs

🔢 What data types can a JavaScript variable hold?

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.

🚫 What happens if a value is assigned without declaring the variable first?

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.

🆚 What is the difference between undefined and null in a variable?

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”.

➕ Why does adding a number to a string return text?

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.

🧊 Can the contents of a const object be changed?

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.

🤖 How does AI help write JavaScript variable declarations?

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.

🚀 Can GitHub Copilot suggest better variable names?

Often, yes. [Copilot](https://github.com/features/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.

🧪 How do you inspect a variable while debugging?

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.

This code is editable. Click Run to Execute  

#### Summarize this post with:

ChatGPTPerplexityGrokGoogle AI

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.**

##### Sign up for the newsletter

Subscribe for Free

You have successfully subscribed.  
Please check your inbox.

![AI-Newsletter]() Chosen by over **350,000+** professionals

[Scroll to topScroll to top](#wrapper) Scroll to top

×

Toggle Menu Close

Search for:

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/javascript-variables-declare-assign.png","url":"https://www.guru99.com/images/javascript-variables-declare-assign.png","width":"700","height":"250","caption":"JavaScript Variables - Declare &amp; Assign","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/using-variables-in-javascript.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/javascript","name":"JavaScript"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/using-variables-in-javascript.html","name":"JavaScript Variable: Declare, Assign a Value with Example"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/using-variables-in-javascript.html#webpage","url":"https://www.guru99.com/using-variables-in-javascript.html","name":"JavaScript Variable: Declare, Assign a Value with Example","dateModified":"2026-07-30T12:06:53+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/javascript-variables-declare-assign.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/using-variables-in-javascript.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/james","name":"James Hartman","description":"I am James Hartman, a seasoned professional in Oracle Certified Java Professional tutorials, specializing in crafting comprehensive guides to help you excel in your Java certification journey.","url":"https://www.guru99.com/author/james","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/james-hartman-author-v2-120x120.png","url":"https://www.guru99.com/images/james-hartman-author-v2-120x120.png","caption":"James Hartman","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"JavaScript","headline":"JavaScript Variable: Declare, Assign a Value with Example","description":"Variables are used to store values (name = &quot;John&quot;) or expressions (sum = x + y). Before using a variable, you first need to declare it. You have to use the keyword var to declare a variable","keywords":"javascript, java","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/james","name":"James Hartman"},"dateModified":"2026-07-30T12:06:53+05:30","image":{"@id":"https://www.guru99.com/images/javascript-variables-declare-assign.png"},"copyrightYear":"2026","name":"JavaScript Variable: Declare, Assign a Value with Example","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What data types can a JavaScript variable hold?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"What happens if a value is assigned without declaring the variable first?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"What is the difference between undefined and null in a variable?","acceptedAnswer":{"@type":"Answer","text":"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\"."}},{"@type":"Question","name":"Why does adding a number to a string return text?","acceptedAnswer":{"@type":"Answer","text":"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\" \u2212 1 correctly returns 2."}},{"@type":"Question","name":"Can the contents of a const object be changed?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"How does AI help write JavaScript variable declarations?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"Can GitHub Copilot suggest better variable names?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"How do you inspect a variable while debugging?","acceptedAnswer":{"@type":"Answer","text":"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."}}]}],"@id":"https://www.guru99.com/using-variables-in-javascript.html#schema-1155638","isPartOf":{"@id":"https://www.guru99.com/using-variables-in-javascript.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/using-variables-in-javascript.html#webpage"}}]}
```
