Menu
Variables
“Naming values so you can use them later.”
A variable is a name that points to a value. You give a value a name once, then use the name instead of repeating the value.
Declaring a variable#
Most languages have a keyword for creating a variable:Older JavaScript uses var. It ignores block scope, which is one reason let and const were added.
1let count = 0; // can change later
2const name = "Amin"; // can't be reassigned
3
4count = count + 1;
5console.log(name, count); // Amin 1
Note
In JavaScript, prefer const and only use let when the value really changes.
Types#
The type of a value decides what you can do with it. Some languages check types before running the code:
1package main
2
3func main() {
4 var age int = 30
5 age = "thirty" // compile error: cannot use "thirty" (untyped string) as int
6}Scope#
A variable only exists inside the block where it’s declared. That’s its scope:
1def area(r):
2 pi = 3.14159
3 return pi * r * r
4
5print(area(2))
6print(pi) # NameError: name 'pi' is not definedWarning
Reusing the same name in an inner block shadows the outer variable. That’s legal but a common source of bugs.
Answer these 3 questions to commit this byte to your learning path.
Reset. This byte isn't committed any more. Answer the questions again to commit it.
$ git commit -m "learn(basics): Variables"
[main a1fbd8c] learn(basics): Variables
1 byte changed, 3 insertions(+)
See it on your path Already committed . Try the questions again any time, it won't undo anything. To uncommit it and start over: