Professional Documents
Culture Documents
Variables
Variables
Most of the time, a JavaScript application needs to work with information. Here are
two examples:
1. An online shop - the information might include goods being sold and a
shopping cart.
2. A chat application - gthe information might include users, messages, and
much more.
A VARIABLE:
A variable is a "named storage" for data. We can use variables to store goodies,
visitors, and other data.
To create a variable in JavaScript, there are three keywords that we can use:
1. const
2. let
3. var
CONST:
The const keyword will be used in most cases as it means that the value of that
variable cannot be changed/modified later in the code.
LET:
The let keyword can be used, but should only be used in the case that a value of a
certain variable needs to be manipulated later in the code. More examples of when
you can use the let keyword include loops and temporary variables that will be
changed either by user input or by later code within the program.
VAR:
The var keyword is hardly ever used anymore as let and const provide almost all of
the necessary functionality that var offers. The var keyword was used in older
scripts before the implementation of ES6 (or ES2022) and is considered the "old-
school" version of let.
VARIABLE NAMING:
CASE MATTERS:
Reserved names-
There is a list of reserved words, which cannot be used as variable names because
they are used by the language itself.
For example, let, class, return, and function are reserved.
Normally, we need to define a variable before using it. But in the old times, it
was technically possible to
create a variable by a mere assignment of the value without usign "let". This still
works now if we don't
put "use strict" in our scripts to maintain compatibility with old scripts.
It is bad practice not to use the "use strict" phrase because errors that would be
caught in strict mode will either be ignored or go unnoticed by the JavaScript
code.
CONSTANTS:
Variables declared using the const keyword are called "constants". They cannot be
reassigned. An attempt to do so would cause an error.
When a programmer is sure that a variable will never change, they can declare it
with const to guarantee and
clearly communicate that fact to everyone.
UPPERCASE CONSTANTS:
Such constants are named using capital letters and underscores. For example:
const COLOR_RED = "#f00";
const COLOR_GREEN = "#0F0";
const COLOR_BLUE = "#00F";
const COLOR_ORANGE = "#FF7F00";
Benefits:
NOTE: Capital constants should only be used as aliases for "hard-coded" values.