Free beginner tutorial

JavaScript Variables and Data Types

Variables give names to values so your JavaScript code can use and update data. Modern JavaScript mainly uses const and let to declare variables.

Use const for values you will not reassign

const siteName = "HTMLCSSCODING";
const pageCount = 4;

A const binding cannot be reassigned. If it refers to an object or array, the binding stays the same even though the object's contents may still be changed.

Use let for values that change

let score = 0;
score = score + 1;

let allows reassignment. Both let and const are block-scoped, which helps keep variables limited to the part of the code where they are needed.

Common JavaScript value types

  • String: Text, such as "hello".
  • Number: Numeric values, such as 42.
  • Boolean: true or false.
  • Array: An ordered list, such as ["HTML", "CSS"].
  • Object: A group of named properties, such as { title: "Home" }.

Read a value’s type

JavaScript values have types such as string, number, and Boolean. The typeof operator can help inspect a value:

typeof "hello"; // "string"
typeof 42;      // "number"
typeof false;   // "boolean"

An unassigned variable has the value undefined. Use null when your code deliberately represents an empty or missing value. Both are different from an empty string such as "" or the number zero.

Build text with a template string

Use backticks to insert a variable into a string with ${...}. This is often easier to read than joining several strings with the + operator.

const firstName = "Ada";
const greeting = `Hello, ${firstName}!`;

JavaScript variable questions

When should I use const and when should I use let?

Start with const when the variable will keep the same binding. Use let when your code needs to assign it a new value later.

What is the difference between null and undefined?

undefined commonly means no value has been assigned. null is an explicit value your code can use to represent no object or no selection.

Use descriptive names such as totalPrice instead of short names such as x. Avoid var in new code unless you need to work with older JavaScript patterns.