JavaScript BasicsCore· 40 min read

Variables: let, const & var

Variables are labelled boxes that store data. Learn to create them the modern way.

What you will learn

  • Declare variables with let and const
  • Know when to use each
  • Name variables well

Storing data

A variable stores a value under a name so you can use it later. Modern JavaScript uses two keywords: let (value can change) and const (value stays constant).

let can change, const cannot
<script>
  let score = 10;       // can change later
  const name = "Asha";  // cannot be reassigned

  score = 20;           // OK — let allows this
  document.write(name + " scored " + score);
</script>
Live preview

Reading it line by line: let score = 10 makes a box named score holding 10. const name = "Asha" makes a sealed box holding the text "Asha". The line score = 20 refills the score box with a new value — allowed, because it was made with let. Finally we join the name and the new score with + and write the sentence to the page.

Note: Output: Asha scored 20 (score shows 20, not 10, because we changed it. If we had tried name = "Ravi" the browser would throw an error, because const values cannot be reassigned.)

let vs const

KeywordUse whenCan reassign?
constThe value should not change (default choice)No
letThe value will change (counters, totals)Yes
varOld style — avoid in new codeYes

Tip: Best practice: reach for const by default. Only use let when you know the value needs to change. Avoid the old varlet/const are safer.

Naming rules

  • Use camelCase: firstName, totalPrice.
  • Start with a letter, $ or _ — not a number.
  • Make names descriptive: age not a.
  • Names are case-sensitive: score and Score differ.

Q. Which keyword should you use by default for a value that will not change?

Answer: const is the default for values that should not be reassigned. Use let only when the value must change.

✍️ Practice

  1. Create a const for your name and a let for your age, then print a sentence using both.
  2. Try reassigning a const and read the error in the console.

🏠 Homework

  1. Declare five well-named variables about yourself (name, city, age, hobby, isStudent) and print them.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →