Ad space (banner)
🟨JavaScript Lessons
Lesson 2 / 69

Creating Variables

In this lesson you'll learn how to declare variables in JavaScript from scratch, understand the difference between let and const, and become able to use them correctly in your own code. This is written for anyone who searched "JavaScript variables tutorial" and landed here, so we'll start from the basics.

A variable is like a "box" that holds a value under a name. In JavaScript you declare a variable with let or const. let variableName = value; creates a variable whose value can be changed later, while const variableName = value; creates a variable whose assigned value can never be changed (a constant). A good beginner rule of thumb is "use let for values that might change, const for values that won't" — and in real projects, the recommended style is to "start with const, and only switch to let when you actually need to reassign."

The sample code declares two variables, let name and const age, and displays them with console.log(). Joining strings with + ("Hello, " + name + "!") is the basic technique for combining several strings and variable values into one message. Note that when a numeric variable (age) is concatenated with a string, it's automatically converted to a string — this becomes useful later when you combine variables with conditionals and loops.

A common stumbling block for beginners is reassigning a variable declared with const and getting an "Assignment to constant variable" error. This happens because you're trying to overwrite a variable you promised not to change — once you understand the cause, it's nothing to fear. Other common pitfalls include using a variable before it's declared, or declaring the same variable name twice with let, both of which cause errors.

In real development, all kinds of information — a user's input, data fetched from an API — first gets stored in a variable before it's processed. Values reused in multiple places on screen, like the logged-in user's name or the total price of items in a cart, are typically managed as variables. How you declare and name variables directly affects how readable and maintainable your code is, which is why it's taken seriously even in code review.

Naming matters too: choosing a name like userName or totalPrice that hints at its contents, rather than a single letter like n, is strongly encouraged in real-world code. Clear variable names make a huge difference in how quickly someone (including future you) can understand the code later.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)