Try the JavaScript Course for Free!

Declaration Hoisting in JavaScript- Tutorial

/ / JavaScript, Latest
Declaration Hoisting in JavaScript- Tutorial: A picture summarizing the main points of the lesson on declaration hoisting in JavaScript.

Declaration Hoisting in JavaScript: Overview

            JavaScript always moves declarations to the top of the current script or function. These are also called the “scope.” The term for this default behavior is “hoisting.” When using JavaScript declarations, it is important to note that a variable can be used before it has been declared. This happens because JavaScript hoists the declaration to the top of the function or script. In other words, it reads declarations first and will then assign any declared values to the declaration.

            Because of declaration hoisting in JavaScript, it is good practice to ALWAYS DECLARE YOUR VARIABLES AT THE TOP OF EVERY SCOPE. This will limit the number of bugs or errors your code may have and decrease confusion in trying to fix bugs or errors.

Declaration Hoisting in JavaScript- Tutorial: A picture summarizing the main points of the lesson on declaration hoisting in JavaScript.

Declaration Hoisting in JavaScript- Tutorial: A picture summarizing the main points of the lesson on declaration hoisting in JavaScript.
Example 1: var x; // Declares variable “x”
x = 5; // Assigns a value of 5 to “x”elem = document.getElementById(“test”); // Sets rule to find an element (elem)
elem.innerHTML = x;            // Sets the rule to display “x” in the element (elem)
Result: This examples shows the variable “x” with a declared value of 5 at the beginning of the code. The result will be 5.
Example 2: x = 5; // Assigns a value of 5 to “x”elem = document.getElementById(“test”); // Sets rule to find an element (elem)
elem.innerHTML = x;            // Sets the rule to display “x” in the element (elem)

var x; // Declares variable “x”

Result: This example shows the assignation of the value of 5 for “x” at the beginning of the code, but does not declare the variable “x” until the last step in the code. This will display the same result, 5, as the first example because the variable was “hoisted” to the top of the function and used before the assigning of the value.

Declaration Hoisting in JavaScript: Syntax Example

  1. Type: var a;

Where “a” is the name of the variable you wish to declare.

Declaration Hoisting in JavaScript: Video Lesson

            The following video lesson, titled “Declarations,” discusses declaration hoisting in JavaScript. This video lesson is from our complete Introductory JavaScript training, titled “Mastering JavaScript Made Easy v.1.0.”

TOP
Sale! $49 All-Access 0 Days 15 Hours 44 Minutes 10 Seconds      $199 $49 Entire Library!
See Deal