A variable is a “named storage” for data. We can use variables to store goodies, visitors, and other data.
To create a variable in JavaScript, use the let keyword.
let message;
message = 'Hello!';
alert(message);
To be concise, we can combine the variable declaration and assignment into a single line
let message = 'Hello!'; // define the variable and assign the value
alert(message); // Hello!
We can also declare multiple variables in one line
let user = 'John', age = 25, message = 'Hello';
// or
let user = 'John';
let age = 25;
let message = 'Hello';
In JavaScript, there are three ways to declare variables. var, let, and const. Each has different properties and scopes, and understanding their differences is important for writing efficient and error-free code.
var (Oldest)
var x = 10;
var x = 20; // No error, x is now 20
function test() {
if (true) {
var x = 10; // function-scoped
}
console.log(x); // x is accessible here, prints 10
}
test();
let (ES6)
let y = 10;
// let y = 20; // Error: y has already been declared
y = 20; // This works, y is now 20
function test() {
if (true) {
let y = 10; // block-scoped
}
console.log(y); // Error: y is not defined
}
test();
const (ES6)
const z = 10;
// z = 20; // Error: Assignment to constant variable.
const arr = [1, 2, 3];
arr.push(4); // This works: [1, 2, 3, 4]
function test() {
const z = 10;
// z = 20; // Error: z cannot be reassigned
}
test();
There are two limitations on variable names in JavaScript
let userName;
let test123;
When the name contains multiple words, camelCase is commonly used. That is words go one after another, each word except first starting with a capital letter - myVeryLongName.
What’s interesting – the dollar sign '$' and the underscore '_' can also be used in names. They are regular symbols, just like letters, without any special meaning.
let $ = 1; // declared a variable with the name "$"
let _ = 2; // and now a variable with the name "_"
alert($ + _); // 3