Featured

Getting to Know JavaScript Variables

To solve a problem with an algorithm, it is in most cases necessary to store certain information temporarily. This is done via variables. These are nothing more than mutable (variable) caches where you store values to access them at a later time.

 

Defining Variables

To be able to use variables, you need to perform two steps. First, you need to create the variable. This process is generally referred to as variable declaration. To declare a variable in JavaScript, you can use the var keyword, followed by the variable name, as shown in this listing.

 

var firstName;

var lastName;

 

As an alternative, it’s possible since ES2015 to use the let keyword for defining variables, which is the recommended method, as shown here.

 

let firstName;

let lastName;

 

Both of these source code variants each define two variables: one named firstName and one named lastName. You don’t need to understand the exact difference between var and let at this point. For now, just keep in mind that you should use the keyword let if the corresponding JavaScript runtime environment (or the browser) supports it.

 

Strict Mode

JavaScript has many quirks and features, some of which lead to errors that are hard to find within an application. To prevent this, strict mode was introduced with ES5. This mode ensures that these potentially error-prone features cannot be used within a script. So strict mode ultimately leads to the use of a somewhat "cleaned up" version of JavaScript (i.e., a subset of JavaScript).

 

You can activate strict mode either for the entire script or specifically for individual functions. In the first case, you include the statement 'use strict'; at the beginning of the script (as shown in the listing below); in the second case, you include it in the first line of the corresponding function.

 

'use strict';

let firstName;

let lastName;

 

Initializing Variables

After declaring a variable, you can assign an actual value to it. This is also referred to as value assignment or variable initialization. It looks like the example here.

 

firstName = 'John';

lastName = 'Doe';

 

By using the equals sign (=), you assign a concrete value to a variable. In JavaScript, the equals sign is the assignment operator. It doesn’t represent two expressions that are equal in value as you would expect from the field of mathematics. In the above code listing, this operator is used to assign the value John to the firstName variable and the value Doe to the lastName variable.

 

Variables without Value

If a variable hasn’t yet been assigned a value, it is not yet defined and accordingly has the value undefined.

 

The two steps of variable declaration and variable initialization can be conveniently combined into a single statement, as shown in this listing.

 

let firstName = 'John';

let lastName = 'Doe';

 

In addition, you have the possibility to declare and initialize several variables within a single statement:

 

let firstName='John', lastName='Doe';

 

Here, the two variables firstName and lastName are declared and initialized. In practice, however, the individual variables are often distributed over several lines for better readability:

 

let firstName = 'John',    // This creates one variable ...

lastName = 'Doe';          // ... and this creates another one.

 

Declaration of Variables since ES2015

A best practice for declaring variables is as follows: use let for declaring variables for which the value can change at runtime (counter variables are a classic example). For all "variables" for which the value doesn’t change, use const instead. In other words, define these "variables" as constants. However, you should avoid using var to declare variables.

  • Use var only in examples where it is required by the version of the runtime environment used.
  • Use let for real variables—that is, variables for which the value changes within the code example shown.
  • Use const for all other variables, which are actually constants. 

Keywords represent an important part of the syntax of a programming language and, in the case of JavaScript, ensure that the interpreter knows what to do. In the case of var, let, and const, the interpreter knows that a variable is to be created and that the appropriate amount of space must be reserved for it.

 

Tip: Avoid declaring new variables without specifying let or const. Otherwise you may unintentionally overwrite already existing global variables with the same name. Strict mode will produce an error if you do try to do this, by the way.

 

Updating Variable Values

As mentioned earlier, after variables have been assigned a value, they can be assigned a new value. The listing below demonstrates an example. In this case, the variable x is first assigned the value 4711, then the value 5.

 

let x = 4711;

console.log(x);    // Output: 4711

x = 5;

console.log(x);    // Output: 5

 

Using Valid Variable Names

You are relatively free in the choice of names for variables, but there are a few restrictions that you must observe. If you don’t, an error will occur when you run your program.

Keywords

First, there are some reserved keywords that are part of the language and serve as identifiers for the interpreter, such as the var and let keywords introduced earlier. If you were to use one of these keywords as a variable name, the interpreter would get confused and report an error accordingly.

 

In addition, there are other keywords in JavaScript that you can use to define certain things. The table below shows an overview of reserved keywords in JavaScript. Although not all of them are functional in the current version of JavaScript—but they are reserved for later versions of the language—you still must not use any of these keywords as variables.

 

Keyword Description
async Used to indicate asynchronous functions
await Used to wait for the results of asynchronous functions
break Used to cancel multiway branches and loops
case Used to define individual program branches in a multiway branch
class Used to define classes
catch Used to intercept 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 standard program branch for multiway branches
delete Used to delete object properties
do Used to define tail-controlled loops
enum Reserved keywords; no function assigned yet
export Used in connection with modules
extends Used to define subclasses or superclasses
finally Used to define default 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 keywords
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 Reserved keyword; no function assigned yet
protected Reserved keyword; no function assigned yet
public Reserved keyword; no function assigned yet
return Used to define a 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 multiway 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 Reserved keyword; no function assigned yet
while Used to define head-controlled loops
with Reserved keyword; should not be used and is not allowed in strict mode
yield Used for generator functions

Variable Names Already Assigned

While you cannot use keywords as variable names for syntactical reasons, there are also names that you could use but should not. We’re referring to names that are already assigned to existing global standard variables.

 

The relevant standard variables essentially depend on the runtime environment: browsers define global standard variables that are different from those defined by a server-side runtime like Node.js. While browsers have predefined variables like alert, document, or window, Node.js has predefined variables such as process, module, and exports.

 

If you use one of these predefined words to define a new variable, this can have unintended consequences and lead to errors in the program. The following code demonstrates this using the console object. In this case, a variable named console is defined and assigned the value 4711. The subsequent attempt to call the log() method on the console object fails.

 

const number = 22;       // Define variable

console.log(number);     // Output: 22

const console = 4711;    // Define variable

console.log(number);     // TypeError: console.log is not a function

 

If you use one of these words as a variable name, you should at least be aware of the side effects this may have. In the previous example, it is obvious and the error is easy to find. But the visibility of variables also plays a role. For now, remember this: if possible, you should avoid using predefined variable names for your own variables. A selection of predefined variable names in browser runtime environments is shown in table below. A detailed listing can be found on the internet. See an overview of the global objects under Node.js here.

 

Predefined Table Names
alert closed frames open
blur document location screen
close focus navigator window

Allowed Characters

Regardless of keywords and predefined variable names, you may use only certain characters within variable names, including letters and numbers, and you can't start a variable name with a number.

 

For full details on the characters allowed, see the blog posts for ECMAScript 5 and for ECMAScript 2015. But for starters, it’s sufficient to follow these rules:

  • A variable name may only start with a letter, the dollar sign ($), or an underscore (_).
  • A variable name must not start with a number.
  • A variable name may contain letters, numbers, dollar signs, and underscores, but no other characters, like periods or hyphens.

This listing provides a few examples of valid and invalid variable names.

 

const 2ndName = 'James';         // invalid because it starts with a number

const first%Name = 'John';       // invalid because it contains special characters

const first-name = 'John';       // invalid because it contains a hyphen

const first_name = 'John';       // valid

const _firstName = 'John';       // valid

const $firstName = 'John';       // valid 

Case Sensitivity

You should also note that variable names are case-sensitive. For example, name, Name, and nAme each represent different variables, as illustrated in this listing.

 

const name = 'John';     // This is a different variable ...

const Name = 'James';    // ... from this variable ...

const nAme = 'Peter';    // ... and this variable.

 

In practice, however, you should avoid distinguishing variables only by their case. It is too likely that this will lead to confusion in your program.

CamelCase Spelling

You can use both uppercase and lowercase letters when assigning variable names. The only important thing is that you do it consistently. A generally accepted notation, for example, is the lowerCamelCase notation, where the variable name starts with a lowercase letter and then, if the name is composed of several words, each of the other words starts with an uppercase letter. The resulting variable name then resembles the form of camel humps. This listing shows some examples.

 

const defaultValue = 2345;

const firstName = 'John';

const lastName = 'Doe';

const isAdmin = true;

const userIsNotLoggedIn = true;

lowerCamelCase and UpperCamelCase Notation

The lowerCamelCase notation is commonly and frequently used for variable names by developers.

 

In addition to the lowerCamelCase notation, there is also the UpperCamelCase notation. The only difference is that the first letter is uppercase instead of lowercase. However, the UpperCamelCase notation is not used for variable names, but for class names.

Meaningful Names

Last but not least, we advise you to choose variables names that are as meaningful as possible so that you can tell the purpose of the variable from the name alone (i.e., without having to look at the surrounding code). For example, a name like uc is less meaningful than the name userConfiguration, and a name like x4 is less meaningful than the name xCoordinate4. The listing below shows some examples of meaningful and less meaningful variable names.

 

// not very meaningful variable names

const fn = 'John ';

const ln = 'Doe ';

// meaningful variable names

const firstName = 'John ';

const lastName = 'Doe ';

Why Naming Matters

Use meaningful names when naming variables. This helps you and others who take a look at your source code to understand the code faster. Regarding the space it takes for these names, you don’t have to pay attention to the length of variable names because it’s possible to minify source code for productive use with special tools (called minifiers).

English Variable Names

In software development, it is common practice to name variables in English: on the one hand, English is often the common language in international teams, and on the other hand, it is the language with the fewest special characters.

 

Defining Constants

You have learned that you can change the value of variables any time; you can overwrite variables with a new value. Sometimes, however, you want to prevent this; that is, you actually need something like a variable, the value of which cannot be overwritten. These variables are called constants in programming because they are not variable but constant: once assigned, the value of a constant remains the same.

 

In JavaScript, there is a const keyword for defining constants. Accordingly, a constant is defined as shown in this listing.

 

const MAXIMUM = 5000;

 

Here, you can also see a common convention for naming constants: as a rule, these are written completely in uppercase. If the name consists of several words, separate them with an underscore (e.g., MAXIMUM_AGE).

 

If you try to overwrite a constant, as in this listing, it depends on the runtime environment whether the corresponding statement is silently ignored or an error is thrown.

 

const MAXIMUM = 5000;

MAXIMUM = 4711;             // potential runtime error

console.log(MAXIMUM);       // Output: 5000

 

Editor’s note: This post has been adapted from a section of the book JavaScript: The Comprehensive Guide by Philip Ackermann. Philip is the CTO of Cedalo GmbH and the author of several reference books and technical articles on Java, JavaScript, and web development. His focus is on the design and development of Node.js projects in the areas of Industry 4.0 and Internet of Things.

 

This post was originally published 5/2025.

Recommendation

JavaScript
JavaScript

Begin your JavaScript journey with this comprehensive, hands-on guide. You’ll learn everything there is to know about professional JavaScript programming, from core language concepts to essential client-side tasks. Build dynamic web applications with step-by-step instructions and expand your knowledge by exploring server-side development and mobile development. Work with advanced language features, write clean and efficient code, and much more!

Learn More
Rheinwerk Computing
by Rheinwerk Computing

Rheinwerk Computing is an imprint of Rheinwerk Publishing and publishes books by leading experts in the fields of programming, administration, security, analytics, and more.

Comments