1.6 Variables
JavaScript variables are containers for storing data values.
In this example,
x
, y
, and z
are variables. Variables are declared with the let
keyword.let x = 5; let y = 6; let z = 11;
For the example above, you can expect:
x
stores the value 5.
y
stores the value 6.
z
stores the value 11.
Before 2015, using the
var
keyboard was the only way to declare a JavaScript variable.The 2015 version of JavaScript (ES6 - ECMAScript 2015) allows the use of the
const
keyword to define a variable that cannot be reassigned, and the let
keyword to define a variable with restricted scope.
This is why this course will not be using var
, but will be using let
and const
. Identifiers
All JavaScript variables must be identified with unique names. These unique names are called identifiers.
Identifiers can be short names (
x
and y
) or more descriptive names (age
, sum
, totalVolume
).The general rules for constructing names for variables (unique identifiers) are:
- Names can contain letters, digits, underscores, and dollar signs.
- Names must begin with a letter.
- Names can also begin with $ and _ (but we will not use it in this tutorial).
- Names are case sensitive (y and Y are different variables).
- Reserved words (like JavaScript keywords) cannot be used as names.
Remember that JavaScript identifiers (names) must begin with:
- A letter (A-Z or a-z)
- A dollar sign ($)
- Or an underscore (_)
Since JavaScript treats a dollar sign as letter, identifiers containing
$
are valid variable names:let $$$ = "Hello World"; let $ = 2; let $myMoney = 5;
Using the dollar sign is not very common in JavaScript, but professional programmers often use it as an alias for the main function in a JavaScript library.
In the JavaScript library jQuery, for instance, the main function
$
is used to select HTML elements. In jQuery $("p")
; means "select all p elements".Since JavaScript treats underscore as a letter, identifiers containing
_
are valid variable names:let _lastName = "Johnson"; let _x = 2; let _100 = 5;
Practice
You can add practice problems here if you want. Follow the format below.
Previous Section
1.5 Data TypesNext Section
1.7 Short Look Into What Functions AreCopyright © 2021 Code 4 Tomorrow. All rights reserved.
The code in this course is licensed under the MIT License.
If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.