Definite Assignment
Learn to handle variable use and definition, including errors and definite assignment assertion syntax.
Introduction to definite assignment
Variables in JavaScript are defined by using the var
keyword. Unfortunately, the
JavaScript runtime is very lenient on where these definitions occur and will allow
a variable to be used before it has been defined.
Consider the following JavaScript code:
// This line logs the value of the variable "aValue" to the console, before it has been definedconsole.log("aValue = " + aValue);// This line declares the variable "aValue" and assigns it the value of 1var aValue = 1;// This line logs the value of the variable "aValue" to the console, after it has been defined and assigned a valueconsole.log("aValue = " + aValue);
We start the code by logging the value of a variable named aValue
to the console. Note, however, that we only declare the aValue
variable on line 5 of the above code snippet.
As we can see from this output, the value of the aValue
variable before it had been declared is undefined
. This can obviously lead to unwanted behavior, and any good JavaScript programmer will check that a variable is not undefined
before attempting to use ...