Updated date:

JavaScript Variable Declaration and Initialization

I'm a software developer with a great interest in data analysis and statistics.

javascript-variable-declaration-and-initialization

Why Do We Use Variables?

A variable is one of the most important concepts in programming. Variables in JavaScript and in programming languages in general are a means to store and keep track of information in an application. For example, we need variables to keep track of a player’s score in a game. If we store a value in a data structure we call it a variable.

This is still in the application code and in memory. We can also write data to files and databases for later retrieval, but that is another topic.

Variables and State

Without variables, it is difficult to impossible to store things, keep track of a history or do complex manipulations and computations. In programming, we often describe this as programs having some form of internal state. In that sense, a variable holds a value and this variable or wide set of variables is that state. The value itself is more ephemeral.

The box or container analogy

It is said that variables are like boxes or containers. We can take an empty box then fill it with anything we want. Although this is a possible way to look at it, it can also give the wrong impression. Different variables can ‘have’ or hold the same value, or more precise, point to the same value.

In this sense, the box analogy can be somewhat misleading, since the value is not really inside that ‘box’. Two or more variables can point to that same value in memory, not just an identical value or copy. It’s probably best to presume that a variable points to a certain value and will give us the value when we ask for it.

Creating A Variable

Declaring a Variable Without Initializing

We start with the JavaScript syntax for creating variables. We can use the let keyword. We use the let keyword when variables are mutable. That means we can change or set the value later on in the program. When the value of the variable will never change, when it stays constant, we use the keyword const. These keywords are available since ECMAScript 6 standard.

Before ES6 there was the var keyword, but this one has some problems were we don't go in this article. When possible avoid the var keyword, but you'll see it in older programs.

We follow it with a whitespace and a name for our variable. Next, we can decide to assign it an initial value or leave it unassigned. Declaration without initialization:

let score;

We can still assign the value later on.

Variable Declaration and Initialization

We initialize our variable by assigning it a value. We can use a literal value, another variable(s) or the result of some computation or expression. Don’t forget a semicolon at the end of the expression. Declaration with initialization:

let score = 5;

or

Recommended for You

const pi = 3.14;

The let keyword is only used for the declaration part. If we want to initialize or change a value of our variables after the declaration, just assign (equals symbol “=”) the value without using the keyword var before the variable name score = 10;.

With the const keyword declaration and initialization always need to happen together, because a const cannot be changed afterwards.

let firstScore;
firstScore // results in undefined
   
let secondScore;
secondScore = 1000;
secondScore // evaluates 1000
   
let thirdScore = 1200;
thirdScore // 1200
   
let otherVariable = 1600;
let fourthScore = otherVariable;
fourthScore // 1600
   
let fifthScore = 3000;
fifthScore = fifthScore + 1000;
fifthScore // 4000
   
let lastScore = 10 * 9 + 5;
lastScore // 95

const maxScore = 1500;
maxScore // 1500

const maxScore = 1500;
maxScore = 2000 // error you can't change a constant value

Declaring Multiple Variables

We can declare multiple variables on one line separating the names by commas and ending the statement with a semicolon. We can also do declaration and initialization on one line. Start with let keyword and then the variable name with the assignment of value. Continue with a comma and the next variable name with a value assignment. End the series with a semicolon.

Beware of the risk of forgetting a comma between the variables. See our next part on the var keyword and global vs local variables.

// declaration on one line
let firstScore, secondScore;
   
// declaration and initialization on one line
let thirdScore = 4444, fourthScore = 1666;
   
// Multiple lines but still in one statement
let fifthScore = 1111,
    sixthScore = 3333,
    lastScore = 7777;

Declaration With or Without let Keyword

If we assign a value directly to a variable without using the let keyword JavaScript will not complain if you are not using strict mode ES6. What it will do is look for a variable with that name to which it can assign the value. Presuming it could have been declared somewhere before or up the scope chain.

If we are just assigning a new value to an existing variable then this can be what we want. If we wanted a new variable then this can mess things up. We could be changing the value of a var we use somewhere else. This could cause unexpected behavior all over the program.

If the variable is not found up or higher in the scope hierarchy a new variable will be created in the global scope. This new global scoped variable will be assigned the value. Best practice for us is using the let keyword for doing declaration + assignment, else we have to be cautious in what we do.

In a basic coding example you’ll not notice a difference in a development console. Everything still acts as you would expect. Prefer using the let keyword and local scope and ECMAScript 6 strict mode.

score = 500;
let lastScore = 2950;
score // evaluates 500
lastScore //evaluaties 2950

Variable Names JavaScript

We need to consider valid names for variables in JavaScript and good practices.

  • Cannot start with a digit or solely consist of digits
  • Cannot be a JavaScript reserved keyword such as (let, const, var, for, which, etc.). Find the list here.
  • Cannot contain punctuation or special characters besides _ and $
  • The $ is sometimes used for starting variable names in JavaScript (convention)
  • The _ is sometimes used for starting variable names to denote it is private (convention)
  • Good practice and convention are using camel-case, every word inside the variable name starts with a capitalization except the first word. Example : myFirstNameAndLastName
  • Good practice to use descriptive names, especially when they are used in the larger scope. Using a short value such as “i” for a counter in a for loop is common, but using these variables in larger parts can make programs difficult to read. For example use bankAccountNumber instead of bn.
// most commonly encountered
const bankAccountNumber = 12378998989;
let scenario2 = 'the second scenario';
   
// used to denote private variables, that only should be accessed from inside an object
const _myFirstName = 'Mike';
   
// seen this mostly used with jQuery when the variable refers to an object from the DOM
let $startButton = $("#startButton");

Declaration and Initialization

A small recap on declaration vs initialization, the basics for beginners. Before we use a variable, we should declare it. We use the let keyword, a valid variable name and semicolon ; for declaration without initialization. Multiple declarations in one statement are separated by a comma.

let entries;
let message;
let title, description;

We can do declaration and initialization at once by assigning a value right after declaration with the equals sign = followed by the value or an expression that will result in a value.

let lastScore = 1200;
let title = "This is an awesome title";

If we just declare a variable without assigning an initial value, the value of the variable will be undefined.

let entries;
console.log(entries); // undefined

© 2019 Sam Shepards

Related Articles