Variables and Value Assignments
Computers can not only compute numbers, but also remember a lot of information. Variables are the computer's agents to store information. They act like containers that can hold values including numbers, strings and other types of data.
Simply put, a variable is a name that refers to a value, it is a "storage" for data.
Rules for a variable name in JavaScript
The name must contain only letters, digits, symbols
_
and$
The first character must not be a digit
Variable names are case sensitive, so
a
andA
are two different variables.Reserved words cannot be used as names
For instance, these are valid variable names: x
, _stuff
, my_name
, yourName
.
Variables should be defined (or declared) before they are used.
To create a variable in JavaScript, we need to use the let
keyword to declare it.
let num123;
let aVeryLongName;
Assignment
Giving a variable a value is called assigning value, which is done in an assignment statement.
In JavaScript, the equal sign =
is an "assignment" operator, not an "equal to" operator. This is different from algebra.
Now we can put some data into a variable by using the assignment operator =
:
let x;
x = 1058;
After declaration, we put the variable on the left side of the equal sign, on the right side is the value you want the variable to be assigned to, such as a number or a string. We can access it using the variable name. Let's display it in the console window:
console.log(x);
the variable content is showed in the console:
1058
we can also merge the variable declaration and assignment into a single line:
let x = 1058;
CodeCraft Visual
Let's use CodeCraft to demo some value assignments:
// variable declaration and simple value assignments
let a = 10;
let b = 4;
// build columns of height a(box_blue: 2), height b(box_orange: 10)
column_m(1, -20, a, 2); // blue, height 10
column_m(3, -20, b, 10); // orange, height 4
// use expression to assign values,
let c = 2 + 3;
column_m(5, -20, c, 6); // green, height 5
// assign sum of (a+b+c) to variable 'total'
let total = a + b + c;
column_m(7, -20, total, 13); // red, height total=10+4+2+3=19
Reassigning values to variables
When the value of a variable is changed, the old data is removed from the variable and replaced with the new data.
We can declare two variables and copy data from one into the other.
// a series of assignments
let f, d;
f = 3;
d = f;
f = 6;
// display the results as columns with height of f and d.
column_m(16,-20, f, 78); // white column height f (3 or 6? correct: 6)
column_m(18, -20, d, 1); // black column height d (3 or 6? correct: 3)
As we continue the lesson, you'll see JS has many other types of data. We can assign them to variables just like strings or integers.