A variable is a named box that holds a value. You put something in the box, give the box a label, and later you can look inside, use the value, or (sometimes) replace it.
Modern JavaScript gives you two keywords for creating variables – let and const – plus an older one, var, that you will still see in existing code.
Declaring with let
Use let for a value that will change over time.
let balance = 500;
console.log(balance);
balance = balance - 120; // bought airtime
console.log(balance);500 380
The first line declares the variable and assigns it a starting value. Later lines update it with =. Notice we do not write let again when changing the value – the box already exists.
Declaring with const
Use const (short for constant) for a value that should never be reassigned.
const VAT_RATE = 0.16;
const shopName = "Mama Mboga Fresh";
console.log(shopName);
console.log(1000 * VAT_RATE);Mama Mboga Fresh 160
If you try to give a const a new value, JavaScript stops with an error:
const city = "Nairobi";
city = "Mombasa"; // TypeError: Assignment to constant variable.
A const must also get its value straight away: const x; on its own is a syntax error.
const. Only switch to let when you find you really need to reassign it. Code with fewer changing values is easier to understand and has fewer bugs.The old var keyword
Before 2015, var was the only way to declare variables. It still works, but it has surprising behaviour:
varignores block boundaries such asifandforblocks (it is function-scoped).- You can declare the same
vartwice without any warning. - A
varcan be used before its declaration line (it is "hoisted"), givingundefinedinstead of an error.
if (true) {
var a = "I escape the block";
let b = "I stay inside";
}
console.log(a);
console.log(typeof b);I escape the block undefined
a leaked out of the if block, but b did not exist outside it (typeof reports "undefined" for unknown names instead of crashing). This is why modern code uses let and const.
var for new code. Learn to recognise it, then leave it to history.Block scope
A block is any code between { and }. Variables declared with let or const live only inside the block where they were created. This keeps names from clashing across different parts of a program.
const message = "outside";
{
const message = "inside";
console.log(message);
}
console.log(message);inside outside
Naming rules
Variable names (also called identifiers) must follow a few rules:
- They may contain letters, digits,
_and$. - They must not start with a digit:
2ndPlaceis invalid,place2is fine. - They are case sensitive:
totalandTotalare different. - They cannot be reserved words like
let,if,classorreturn.
By convention, JavaScript developers use camelCase: start lowercase and capitalise each following word, as in customerName or mpesaReceiptNumber. Constants that never change, like configuration values, are often written in UPPER_SNAKE_CASE.
Choose names that describe the value. deliveryFee tells the reader far more than df or x.
Declaring several variables
You can declare several variables in one statement, separated by commas, though one per line is usually clearer.
let firstName = "Otieno", lastName = "Ouma", age = 24;
console.log(firstName, lastName, age);Otieno Ouma 24
Variables without a value
A variable declared with let but not assigned holds the special value undefined.
let customer;
console.log(customer);
customer = "Achieng";
console.log(customer);undefined Achieng
You will learn more about undefined and its cousin null in Data Types.
Declare a variable that can change later, and one that never will.
score = 0;
maxScore = 100;Write the variable name customer phone number in camelCase.
let = "0712345678";Lowercase first word, capitalise the start of each later word.
SKOPE