If you have 4 apples and buy 27 more, how many apples do you have ? Take a second and write your answer in your text editor. What’s your answer ?
Both answers are correct, but the second method is better because it lets JavaScript do the calculation. However,
without context 4 + 27
doesn’t tell us we’re talking about apples.
A better approach is to use variables to give meaning to the numbers:
Using variables like initialApples
and applesBought
makes the code more meaningful. The process of replacing 4
with initialApples
is called declaring variables.
Declaring variables
Declaring variables in JavaScript uses the syntax:
The key parts are the variableName
, value
, =
sign, and the const
keyword. Variable names must be one word, start
with a letter, and not be a reserved keyword.
In JavaScript, =
means assignment, not equality. For example:
this assigns the value 4 to initialApples
.
Evaluate expressions
To evaluate expressions before assignment, JavaScript substitutes variables and evaluates the expression, like:
Use const
for variables that should not change and let
for those that can. Avoid using var
.
Notes:
- Variables hold a value.
- Variables can hold primitives and objects.
- The
=
sign means assignment (not equality). - Use camelCase for variable names and avoid reserved keywords.
- Prefer
const
overlet
. - Don’t use
var
anymore.