Lesson 2 of 12

JavaScript Variables and Data Types

Programs need to remember things: a user’s name, the number of items in a cart, whether someone is logged in. A variable is a named container for a value. You give it a name once, and from then on you can read or change the value by using that name.

In the previous lesson you already used const without much explanation. Now let us look at it properly, along with the data types a variable can hold.

Declaring variables with let and const

Modern JavaScript has two keywords for creating variables:

  • const – for a value that will not be reassigned. Use it by default.
  • let – for a value that will change later, such as a counter or a running total.

Why prefer const? When you read code and see const, you know that name will always point to the same value. Fewer moving parts means fewer bugs. Switch to let only when you genuinely need to reassign.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>let and const</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 16px; line-height: 1.5; }
  </style>
</head>
<body>
  <p id="line1"></p>
  <p id="line2"></p>

  <script>
const city = 'Coimbatore';   // will not change
let visitors = 10;           // will change

visitors = visitors + 5;     // reassigning a let is allowed
// city = 'Salem';           // remove the // and run: TypeError!

document.getElementById('line1').textContent = 'City: ' + city;
document.getElementById('line2').textContent = 'Visitors today: ' + visitors;
  </script>
</body>
</html>

Try removing the // in front of city = 'Salem';. The script stops with a TypeError because a const cannot be reassigned. Errors like this are helpful: they catch mistakes early.

What about var?

You will meet var in older code and tutorials. It was the only option before 2015. It still works, but it behaves in confusing ways: a var is not limited to the block (the { }) where it is declared, the same name can be declared twice without any warning, and it can be used before its declaration line (it is “hoisted” with the value undefined). let and const fix all three problems, so treat var as legacy and do not use it in new code.

Naming rules and conventions

  • Names can contain letters, digits, _ and $, but cannot start with a digit: price2 is fine, 2price is not.
  • Names are case-sensitive, and reserved words such as let, if or function cannot be used.
  • Use camelCase for multi-word names: firstName, totalAmount, isLoggedIn.
  • Choose descriptive names. deliveryCharge tells the next reader far more than dc or x.

Data types

Every value in JavaScript has a type. The type decides what you can do with the value – you can multiply numbers, but multiplying two names makes no sense. JavaScript has seven primitive types and one structural type, object.

TypeExampleUsed for
String'Kochi', "Hello"Text
Number42, 3.14, -7Whole numbers and decimals (one type for both)
Booleantrue, falseYes/no flags
UndefinedundefinedA variable that has no value yet
NullnullAn intentional “no value”
BigInt9007199254740993nVery large whole numbers
SymbolSymbol('id')Unique keys (advanced)
Object{ name: 'Asha' }, [1, 2, 3]Collections of values – arrays and objects

As a beginner you will mostly use these data types: strings, numbers, booleans, and later arrays and objects, which have their own lessons: Arrays and Objects.

Checking a type with typeof

JavaScript is dynamically typed: you never declare a type, and the same let variable can hold a number now and a string later. To find out what a value is, use the typeof operator. The example also introduces template literals – strings wrapped in backticks that can include values with ${ }. They make output much easier to write, and you will see them in every lesson from now on.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>typeof</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 16px; line-height: 1.5; }
  </style>
</head>
<body>
  <pre id="out"></pre>

  <script>
const product = 'Filter coffee';
const price = 35;
const inStock = true;
let discount;            // declared but no value
const coupon = null;

document.getElementById('out').textContent =
  `product  → ${typeof product}
price    → ${typeof price}
inStock  → ${typeof inStock}
discount → ${typeof discount}
coupon   → ${typeof coupon}   (a famous old quirk!)`;
  </script>
</body>
</html>

Tip: typeof null returns "object". This is a bug from the very first version of JavaScript that can never be fixed without breaking old websites. To check for null, compare directly: value === null.

Numbers and strings: a common trap

Values read from form fields are always strings, even when the user types digits. Adding '5' + 2 gives '52', not 7, because + joins strings. Convert first with Number(). Also be aware that decimals are stored in binary, so 0.1 + 0.2 is 0.30000000000000004. For money, work in whole paise or round the result with toFixed(2) when displaying it.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Conversion</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 16px; line-height: 1.5; }
  </style>
</head>
<body>
  <pre id="out"></pre>

  <script>
const qtyFromForm = '5';               // text, as a form gives it
const wrong = qtyFromForm + 2;         // joins: '52'
const right = Number(qtyFromForm) + 2; // adds: 7
const bill = 0.1 + 0.2;

document.getElementById('out').textContent =
  `Without conversion: ${wrong}
With Number():      ${right}
0.1 + 0.2 =         ${bill}
Rounded:            ${bill.toFixed(2)}`;
  </script>
</body>
</html>

Watch out: Forgetting to declare a variable (writing total = 10 with no let or const) silently creates a global variable in old-style scripts. In modules and strict mode it throws an error instead. Always declare your variables.

Next, you will combine these values using JavaScript Operators.

Further reading

Key takeaways

  • A variable is a named container for a value.
  • Use const by default and let when the value must be reassigned; var is legacy.
  • Use camelCase, descriptive names; names are case-sensitive.
  • Main types: string, number, boolean, undefined, null, bigint, symbol and object.
  • typeof tells you a value's type; typeof null is "object" because of an old bug.
  • Form values are strings – convert with Number() before doing maths.

Quick quiz

Check what you learned – pick an answer.

1. Which keyword should you use for a value that will never be reassigned?

2. What is the result of '5' + 2 in JavaScript?

3. What does typeof true return?

Practice exercise

Create constants for a product name (string), its price (number) and whether it is available (boolean). Display all three values and their types on the page in a pre element, one per line, using a template literal.

Show a hint

Use typeof inside ${ } placeholders, and write the line breaks directly inside the backticks.

Show the solution
<pre id="out"></pre>
<script>
  const item = 'Mysore Pak';
  const cost = 250;
  const available = false;

  document.getElementById('out').textContent =
    `${item} (${typeof item})
${cost} (${typeof cost})
${available} (${typeof available})`;
</script>

Progress is saved in this browser only.