Menu

Variables

“Naming values so you can use them later.”

View .md

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.

variables.jsjs
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:

main.gogo
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:

python
1def area(r):
2    pi = 3.14159
3    return pi * r * r
4
5print(area(2))
6print(pi)  # NameError: name 'pi' is not defined

Warning

Reusing the same name in an inner block shadows the outer variable. That’s legal but a common source of bugs.

Byte check

0/3

Answer these 3 questions to commit this byte to your learning path.

  1. In JavaScript, which keyword do you use for a name that will never be reassigned?
  2. In the Python example, what does print(pi) outside area() do?
  3. In Go, var age int = 30 then age = "thirty" gives…
Search posts and bytes

Optional account

Keep your progress everywhere

Everything on AminBytes is free to read, with or without an account. Sign in only if you want your commits, streak and merged topics saved, on every device.

or

We keep only your name, avatar and which bytes you finished, and you can delete it all anytime. Privacy