Home >Web Front-end >JS Tutorial >JavaScript Variables: let vs const vs var
In this post, we’ll explore what variables are, how to declare them, and how they work in JavaScript.
A variable is a way to store a value in JavaScript so we can use it later. Think of a variable like a labeled box where you can keep things and retrieve them when needed.
For example, instead of writing "John" multiple times in your code, you can store it in a variable and use it anywhere.
JavaScript provides three ways to declare variables:
let name = "John"; console.log(name);
Output:
John
Here, we:
const PI = 3.1416; console.log(PI);
Output:
3.1416
var age = 25; console.log(age);
Output:
25
With let, you can change a variable’s value, but with const, you cannot.
let city = "New York"; console.log(city); // Output: New York city = "Los Angeles"; // Changing the value console.log(city); // Output: Los Angeles
const country = "USA"; console.log(country); country = "Canada"; // ❌ This will cause an error console.log(country);
Error: Uncaught TypeError: Assignment to constant variable.
When naming variables, follow these rules:
✔️ Can contain letters, numbers, $, and _
✔️ Must start with a letter, $, or _ (not a number)
✔️ Case-sensitive (name and Name are different)
✔️ Cannot be a reserved keyword (like let, console, function, etc.)
let name = "John"; console.log(name);
John
Try this in your script.js file:
const PI = 3.1416; console.log(PI);
Expected Output:
3.1416
Now that we understand how variables work, the next step is to explore data types in JavaScript—including numbers, strings, booleans, and more!
Stay tuned for the next post! ?
? Use let when you expect the value to change.
? Use const when the value should stay the same.
? Avoid var unless you specifically need it.
Follow me on LinkedIn - Ridoy Hasan
Visit my website - Ridoyweb
*Visit my agency website *- webention digital
The above is the detailed content of JavaScript Variables: let vs const vs var. For more information, please follow other related articles on the PHP Chinese website!