Cost Check Now
Programming·JavaScript

How to declare a variable in JavaScript (2026)

Verified from sources

Quick Answer

In JavaScript, you declare a variable with let, const, or var, followed by a name and optionally a value. In modern code, use let for values that may change and const for values that should not be reassigned; avoid var unless you are working with older code.

Overview

Declaring a variable in JavaScript means creating a named place to store data so your code can use it later. The basic pattern is a keyword, a variable name, and, if needed, an initial value. For example, let count = 0; creates a variable you can change later, while const siteName = 'Cost Check Now'; creates one you should not reassign. JavaScript also has var, but it behaves differently because it is function-scoped rather than block-scoped, which can lead to bugs in modern code. The most practical approach is to choose the declaration keyword first, then pick a clear name, then assign a sensible starting value if your code needs one straight away. This matters because the keyword affects how widely the variable can be used, whether it can be reassigned, and how easy your code is to maintain. You can declare variables in a browser console, a script file, or a Node.js environment, and the syntax is the same. If you are learning or writing new code, focus on let and const. They make your intent clearer and reduce common mistakes involving scope and accidental reassignment.

Who this is for

Beginners learning JavaScript, students, and developers who want a quick refresher on modern variable declaration.

What you’ll need

  • A text editor or code editor
  • A JavaScript runtime such as a web browser console or Node.js
  • Basic understanding of JavaScript syntax

Before you start

Make sure you are using JavaScript in a place where you can run it, such as a browser developer console or a .js file linked to a web page or run with Node.js. If you are following modern JavaScript practice, plan to use let and const rather than var unless you specifically need to understand older code.

Step-by-step

  1. 1

    Choose the right declaration keyword

    Decide whether the variable should use const, let, or var. Use const if the variable should not be reassigned after it is created. Use let if the value may change later. Use var mainly when reading or maintaining older JavaScript code.

    Why: The keyword controls scope and reassignment behaviour. Choosing the right one prevents bugs and makes your code easier to understand.

  2. 2

    Pick a clear variable name

    Write a name that starts with a letter, underscore, or dollar sign, and continue with letters, digits, underscores, or dollar signs. Use descriptive names such as userName or totalPrice rather than vague names like x unless the variable is genuinely short-lived and obvious.

    Why: A valid, meaningful name avoids syntax errors and makes your code easier to read and maintain.

  3. 3

    Declare the variable

    Write the declaration using the keyword followed by the name, such as let score; or const apiUrl = '...';. If you use const, provide a value when you declare it.

    Why: This is the actual creation of the variable. With const, an initial value is required, so getting this right avoids immediate errors.

  4. 4

    Assign an initial value if needed

    Add = followed by the value you want to store, for example let age = 30; or let isReady = false;. If you declare with let and do not assign a value yet, the variable starts as undefined.

    Why: An initial value makes the variable usable straight away and can prevent confusion about whether it has been set.

  5. 5

    Use the variable within the correct scope

    Access the variable only where it is in scope. Variables declared with let and const exist only inside the block where they are declared, such as inside a function or an if statement block. var is function-scoped instead.

    Why: Scope determines where your variable can be used. Respecting scope prevents reference errors and accidental clashes with other variables.

  6. 6

    Reassign only when the keyword allows it

    If you declared the variable with let, you can later write a new value such as score = 10;. If you declared it with const, do not try to reassign it. Note that const prevents reassignment of the variable itself, but if it holds an object or array, the contents may still be mutable unless you take extra steps.

    Why: Understanding reassignment rules helps you avoid runtime errors and makes your intent explicit.

Why this works

JavaScript stores values in variables by binding a name to a value in memory. The declaration keyword tells the JavaScript engine how that binding should behave, especially in relation to scope and reassignment.

Common mistakes to avoid

  • Using var in new code without understanding its function scope and hoisting behaviour
  • Trying to reassign a variable declared with const
  • Using a variable before it is declared with let or const
  • Choosing unclear names that make the code hard to follow
  • Assuming const makes an object or array completely immutable

Troubleshooting

You see a ReferenceError saying a variable is not defined

Check that you declared the variable before using it and that you are using it within the correct scope.

You see an error when changing a const variable

Change the declaration to let if the value needs to be reassigned, or stop reassigning it if it should stay fixed.

A variable inside an if block cannot be used outside it

Move the declaration to a wider scope if needed, or keep the logic inside the block where the variable exists.

Your code behaves oddly with var in loops or conditionals

Replace var with let where appropriate so the variable is block-scoped and behaves more predictably in modern code.

Compare your options

const

Best for: Values that should not be reassigned

Pros: Clear intent; block-scoped; helps prevent accidental reassignment

Cons: Must be initialised when declared; cannot be reassigned later

let

Best for: Values that will change

Pros: Block-scoped; suitable for counters, form input, and state that updates

Cons: Can be reassigned, so careless changes are still possible

var

Best for: Maintaining older JavaScript code

Pros: Works in legacy codebases

Cons: Function-scoped rather than block-scoped; more prone to confusion from hoisting and redeclaration

Alternatives

  • Store fixed values directly without a variable when they are used only once
  • Use object properties or array elements when grouping related values makes more sense than separate variables

Pro tips

  • Prefer const by default, then switch to let only when reassignment is genuinely needed
  • Use camelCase for variable names in typical JavaScript style, such as totalCost or userEmail
  • Keep variable scope as narrow as possible to reduce accidental misuse
  • If a value may be missing at first, initialise it deliberately so the code's state is clear

Safety notes

  • Do not paste unknown JavaScript into a browser console on a live account or sensitive website, as it can run with your current permissions
  • Be careful when testing code that modifies files, browser storage, or remote data

What this guide does not cover: This guide covers basic variable declaration and practical usage. It does not go deeply into hoisting, temporal dead zone behaviour, immutability techniques, TypeScript typing, or advanced scoping patterns.

Cost considerations

You can learn and practise variable declaration using free tools such as a browser console or community edition code editor. Paid tools are optional rather than necessary for this task.

Frequently asked questions

What is the difference between declaring and assigning a variable?+

Declaring creates the variable name. Assigning gives it a value. You can do both at once, as in let name = 'Sam';.

Should I use let or const?+

Use const when you do not intend to reassign the variable. Use let when the value will change later.

Can I declare a variable without giving it a value?+

Yes, with let or var you can write let item; and assign a value later. const requires an initial value at declaration.

Why is var discouraged in modern JavaScript?+

var is function-scoped and has hoisting behaviour that can make code harder to reason about. let and const are block-scoped and usually safer for modern code.

Does const make arrays and objects unchangeable?+

No. const stops you reassigning the variable to a different array or object, but it does not automatically freeze the contents.

Sources & references

Guidance on this page is traced to documented sources. Last checked 24 September 2026.

  • MDN Web Docs: let · industry

    Supports syntax and behaviour of let, including block scope and declaration rules.

  • MDN Web Docs: const · industry

    Supports syntax and behaviour of const, including required initialisation and no reassignment.

  • MDN Web Docs: var · industry

    Supports syntax and legacy behaviour of var, including function scope.

The core syntax for declaring variables in JavaScript is stable, though style recommendations can evolve.

Related guides

Legal Disclaimer: The information provided on Cost Check Now is for general informational and educational purposes only. It does not constitute financial, legal, professional, or any other form of advice. Cost Check Now makes no representations or warranties of any kind, express or implied, about the completeness, accuracy, reliability, suitability, or availability of any information, products, services, or related graphics contained on this website. Any reliance you place on such information is strictly at your own risk. In no event will Cost Check Now, its owners, operators, contributors, or affiliates be liable for any loss or damage including without limitation, indirect or consequential loss or damage, or any loss or damage whatsoever arising from loss of data or profits arising out of, or in connection with, the use of this website. Always seek independent professional advice before making financial or purchasing decisions.