Imagine you are building a profile page. The name "Sam" appears in the heading, in the greeting and on the member card. One day that name has to change to "Alex". If you type "Sam" in all three places, you have to find each one and change it by hand. It is easier to store the name once in a box, put a label on the box, and let each place just use the label. When the name changes, you change what is in the box only once.
In JavaScript, that labelled box is called a variable: a named container that holds a value, so you can use that value again later by its name. The label on the box is the variable's name. What is in the box is its value. A value is the data itself: text like "Budi" or a number like 17.
Making a variable: keyword, name, =, value
This code makes two variables, then prints what they hold:
let name = "Budi";
const age = 17;
console.log(name); // Budi
console.log(age); // 17
Look at the first line:
letis a keyword: a word with a special meaning in JavaScript.letmeans "make a new variable". Making a variable is also called declaring it.nameis the variable's name. You can choose any name, but after that you must write it exactly the same way every time:name, notNameorNAME.=means "put this in". The sign is not:, and it does not mean "equals" as it does in maths."Budi"is the value. Text goes inside quote marks and is stored exactly as you typed it, capital letters included. A number has no quote marks:17is a number,"17"is text.;marks the end of the instruction.
The second line uses const, another keyword that makes a variable. The next section explains how it differs from let. console.log(name) prints what the variable name holds: Budi. The // Budi after it is a comment: JavaScript ignores the text after //. Here the comment only shows what is printed.
Rules for variable names. You choose the name yourself, as long as you follow these rules:
- It holds letters, digits,
_and$, but it cannot start with a digit:name2is fine,2nameis an error. - No spaces and no
-. For two words, join them and start the second word with a capital letter:firstName, notfirst nameorfirst-name. This style is called camelCase. - Keywords such as
let,constandifcannot be names. - Capital and small letters are not the same:
nameandNameare two different variables.
Changing what it holds: let allows it, const refuses
This code tries to change what two variables hold: score, made with let, and pi, made with const.
let score = 0;
score = 100;
console.log(score); // 100
const pi = 3.14;
pi = 3.15; // TypeError: Assignment to constant variable.
score = 100;changes whatscoreholds (this is called reassigning). The line has nolet, becausescorealready exists. You write the keyword only once, when you make the variable.- If you declare the same name again, for example
let score = 100;underlet score = 0;, JavaScript refuses with the errorIdentifier 'score' has already been declared. An identifier is a name, so the error says the namescoreis taken. None of the code runs at all, not even the lines above it. const(short for constant, something that stays the same) locks the variable: you cannot replace what it holds. The last line tries to givepia new value, so the result is an error namedTypeError.
Here is how to choose: use const when the value will never be replaced, and let when it will (a score, a total, a count). var is the old way to make a variable, from the time before let and const existed. Modern code avoids it. One note: if a const variable holds an object (a group of several values), the contents of the object can still change. The Objects lesson explains this.
Swapping two variables
You want to swap what a and b hold. If you write a = b right away, the value of b overwrites the old value of a, and there is no way to get it back. So first keep the old value of a in a helper variable, usually named temp (short for temporary):
let a = 5;
let b = 10;
let temp = a; // temp = 5
a = b; // a = 10
b = temp; // b = 5
let temp = a;copies the value ofa, which is 5, intotemp. Only this line useslet, becausetempis a new variable.a = b;puts the value ofbintoa. Nowaandbboth hold 10, but the 5 is still safe intemp.b = temp;puts the 5 fromtempintob. Done:aholds 10,bholds 5.
⚠️ The usual mistakes when writing a variable
- Using
:or leaving out=.let name : "Budi"andlet name "Budi"are both errors. The right form islet name = "Budi";. - Putting a number in quote marks.
const age = "17"holds text, not a number. Write17without quote marks. - Writing
letorconstagain to change a value. Writinglet temp = 10;orconst a = 10;for a variable that already exists causes an error. To change the value, just writetemp = 10;. - Forgetting the variable's name.
const = 17has no name, so you cannot use the value later. JavaScript refuses this code with an error. - Making a variable without
letorconst. In a plain script,newScore = 5;quietly makes a global variable (one that all of your code can see). In a module (see the Modules lesson), the same line is an error:ReferenceError: newScore is not defined. Always writeletorconstwhen you make a variable.
TL;DR: A variable is a named container for a value (data such as text or a number). It looks like let name = "Budi";: keyword (a special word such as let), name, =, then the value. Text goes inside quote marks, numbers have none. To change what a variable holds, just write name = "Alex"; without let, because a name can be declared (made) only once. The keyword is let or const: a const variable refuses a new value (a TypeError), a let variable accepts one. var is an old keyword that modern code avoids. To swap a and b, use a helper variable temp: keep the value of a in temp, put the value of b into a, then put the value from temp into b.
⚡ Keyword, name, =, value
Write:
let name = "Budi";
const age = 17;
console.log(name); // Budi
Meaning: A variable is a named container that holds a value, such as text or a number. let and const are keywords (words with a special meaning in JavaScript) that make a new variable, name is the variable's name, and = means "put this in". The value comes after =. Text goes inside quote marks, numbers have none: 17 is a number, "17" is text. The text after // is a comment, which JavaScript ignores.
⚡ let can change, const refuses
Write:
let score = 0;
score = 100;
const pi = 3.14;
pi = 3.15;
Guess first: what happens on the line pi = 3.15;?
A TypeError. A variable made with const can't be given a new value.
Meaning: To change what a variable holds, just write score = 100;, without let. A name can be declared (made with let or const) only once. Use const when the value will never be replaced, let when it will.
⚡ Swap with temp
Write:
let temp = a;
a = b;
b = temp;
Guess first: why not just write a = b?
Because the old value of a is lost as soon as the value of b overwrites it, and there is no way to get it back.
Meaning: These three lines swap what a and b hold. Both variables were made earlier. First keep the value of a in a helper variable, temp (short for temporary). Then overwrite a with the value of b, and put the value from temp into b.