Variables
In most cases, in order to solve a problem with an algorithm, certain information should be temporarily stored. These are variable caches in which values can be stored and accessed at a later point in time.
1. Define variables
Two steps are necessary to create a variable:
1. The variable must be created, this is called variable declaration. To create a variable in JavaScript, the keyword var can be used, followed by the name of the variable:
var firstName
var lastName
Note
- Since ES2015 it is possible to use the keyword let for the definition of variables, this variant should also be preferred. var should only be used if the runtime environment (e.g. browser) only supports var.
- let is appropriate where a restricted block scope is appropriate, var indicates that the scope of a variable extends over the entire function (If you have no experience with JS, you don't need to understand it yet).
let firstName
let lastName
After the variable has been declared, a concrete value can be assigned to it, this is called variable initialization or value assignment:
let firstName = 'Rick';
let lastName = 'Sample';
Complete Code - Examples/Part_1/main.js
The equal sign assigns a concrete value to the variable. The = is the so-called assignment operator in JS, and in JavaScript does not stand for two expressions with the same value, as in mathematics. Here, the variables fistName have been assigned the value Rick and lastName the value Sample.
The two steps of variable declaration and variable initialization can be combined into one instruction:
let firstName = 'Rick';
let lastName = 'Sample';
It is also possible to declare and initialize several variables directly within a single instruction:
let firstName = 'Rick', lastName = 'Sample';
For better readability, however, the individual variables are often distributed over several lines:
let firstName = 'Rick',
lastName = 'Sample';
Variables can also be assigned a new value after they have been assigned a value:
Complete Code - Examples/Part_2/main.js
let x = 420;
console.log(x); // output: 420
x = 42;
console.log(x); // output: 42
You should avoid declaring new variables without specifying let or const. Otherwise, existing global variables with the same name may be overwritten unintentionally.
Variables without a value
If a variable has not yet been assigned a value, it is not defined and then has the value undefined.
2. Define constants
With variables it is possible to change the value at any time, i.e. it is possible to overwrite them at any time. A "variable" whose value cannot be overwritten is referred to as a constant in programming. In JavaScript, the keyword const is used to define constants. A constant is defined as follows:
const MAXIMUM = 4000;
Constants are written entirely in capital letters, which is the common convention for naming constants. If there are several words, they are separated by an underscore _ , e.g. MAXIMUM_AGE. If an attempt is made to overwrite a constant, either an error is output or the instruction is ignored (this depends on the runtime environment):
Complete Code - Examples/Part_3/main.js
const MAXIMUM = 4000;
MAXIMUM = 4200; // potential runtime error
console.log(MAXIMUM); // output: 4000
Declaration of variables since ES2015
When declaring variables, the best practice is to use let for the declaration of variables whose value can change at runtime (e.g. counter variables). For all "variables" (constants) whose value does not change, const is used. The use of var for the declaration of variables should be avoided (only necessary if an outdated runtime environment/browser is used).
3. Valid variable names
There are almost no limits to the choice of variable names, except for a few restrictions, namely the reserved keywords. If you use a keyword as a variable, an error will occur when the program is executed. However, you should note that variable names should be chosen carefully so that the code remains readable, e.g. for "first name" you should use fname instead of a.
Keywords
In the case of JavaScript, keywords ensure that the interpreter knows what it should do. In the case of var, let and const, the interpreter knows that a variable is to be created and that it must reserve memory space accordingly. There are even more reserved keywords than var, let and const. All these keywords are part of the language and serve as identifiers for the interpreter.
This table shows an overview of the reserved keywords in JavaScript that may not be used as variable names:
Keyword | Description |
---|---|
async | Used to mark asynchronous functions |
await | Used to wait for the result of asynchronous functions |
break | Used to cancel multiple branches and loops |
case | Used to define individual program branches in a multiple branch |
class | Used to define classes |
catch | Used to catch errors |
const | Used to define constants |
continue | Used to cancel loop iterations |
debugger | Used to define breakpoints in the program |
default | Used to define a default program branch for multiple branches |
delete | Used to delete object properties |
do | Used to define foot-controlled loops |
else | Used to define an alternative program branch when branching |
enum | Reserved keyword, no function assigned yet |
export | Used in connection with modules |
extends | Used to define subclasses or superclasses |
finally | Used to define standard behavior when handling errors |
for | Used to define counting loops |
function | Used to define functions |
if | Used to define conditional statements and branches |
implements | Reserved keyword |
import | Used in connection with modules |
in | Checks whether an object contains a property or a method |
interface | Reserved keyword |
instanceof | Checks whether an object is an instance of a prototype |
let | Used to define variables |
new | Used to create object instances |
package | Reserved keyword, no function assigned yet |
private | These members are only accessible within the class that instantiated the object |
protected | This allows a little more access than private members but a lot less than the public |
public | These members of the class and available to everyone that can access the (owner) class instance |
return | Used to define the return value of a function |
static | Used to define static properties and methods |
super | Used to access the superclass from a (sub)class |
switch | Used to define multiple branches |
this | Used to access an object within the object itself |
throw | Used to throw an error |
try | Used to define a code block in which errors can occur |
typeof | Determines the type of a variable |
var | Used to define variables |
void | Used in JavaScript to evaluate an expression that does not return a value |
while | Used to define head-controlled loops |
with | The statement extends the scope chain for a statement. The use of the with statement is not recommended, as it can lead to confusing errors and compatibility problems, makes optimization impossible and is prohibited in strict mode |
yield | Used with generator functions |
Not all keywords in JavaScript have a function in the current version, but some are reserved for later versions of the language, but these must not be used as variable names.
Already assigned variable names
As keywords cannot be used as variable names for syntactical reasons, there are also names that can be used but should not be used. These are names that have already been assigned to existing global standard variables.
Which standard variables these are depends on the runtime environment: Browsers define different global standard variables (e.g. alert, document, window) than server-side runtime environments such as Node.js (e.g.: exports, module, process). If one of these already assigned words is used for the definition of a variable, this can have unintended consequences and lead to errors in the program.
A list of the variable names already assigned can be found here:
- in browser runtime environment MDN Web Docs
- in Node.js Node.js - Docs
Allowed characters
In JavaScript, only certain characters may be used within variable names:
- a variable name may only begin with a letter, the dollar sign $ or an underscore _
- a variable name may not begin with a number
- a variable name may contain letters, dollar signs and underscores, but not other characters such as periods . or hyphens -
Examples of invalid and valid variable names:
let 1stName = 'John'; // invalid, as it begins with a number
let first%Name = 'John'; // invalid because special character not allowed
let first-name = 'John'; // invalid because it contains a hyphen
let first_name = 'John'; // valid
let _firstName = 'John'; // valid
let $firstName = 'John'; // valid
Upper and lower case
Variable names should also be case-sensitive, because name, Name and namE are different variable names. If variables can only be distinguished from each other by their spelling, the code can quickly become confusing, so it is best to use meaningful names.
CamelCase notation
In principle, upper and lower case letters can be used when assigning variable names, the only important thing is that it should be consistent. A generally accepted spelling is the Lower-CamelCase notation, where the variable name begins with a lower case letter and if the variable name is made up of several words, each additional word begins with a capital letter, e.g. firstName.
Examples:
const defaultValue = 1234;
const firstName = 'John';
const lastName = 'Doe';
const isAdmin = true;
const isUserLoggedIn = true;
There is also the Upper-CamelCase notation, where the first letter is capitalized. However, this variant is more commonly used for class names (object-oriented programming = OOP).
Meaningful names
When naming variables, use meaningful names, this helps to understand the code later or so that others are also able to understand the code.
Examples:
let fn = 'John'; // less meaningful variable name
let ln = 'Doe'; // less meaningful variable name
let uc = true; // less meaningful variable name
let firstName = 'John'; // meaningful variable name
let lastName = 'Doe'; // meaningful variable name
let userConfiguration = true; // meaningful variable name
Related links: