_javascript techniques for identifier elevation problems in JavaScript

Source: Internet
Author: User
Tags js function declaration

JS exists variable elevation, this design is actually inferior, or a language implementation of a side effect. It allows a variable to be accessed without declaring it, or declaring it to be used before. Novice for this is very confusing, and even many of the use of JS years veteran is also more puzzled. But after ES6 joins the Let/const, the variable hoisting does not exist.

One, the variable is not declared, direct use

function test () {
  alert (notdefined);
}
Test (); // ?

It's natural to complain.

Two. Variable declaration at the end

function test () {
  alert (declaredbutnotassigned);//undefined
  var declaredbutnotassigned;
}
Test ();

Output undefined, the result is better than the previous example, there is no error, the code can run, but the variable value may not be expected by the programmer.

Third, the variable declaration at the end, while assigning values to the variable

function test () {
  alert (declaredandassigned);//undefined
  var declaredandassigned = 1;
}
Test ();

The result is the same as two, and obviously, it's not going to output 1 because of the assignment.

Two or three has occurred variable elevation (hoisting), a simple definition

Variable elevation: In the specified scope, the variable is declared in code order, but the "accessibility" of the run-time variable is elevated to the top of the current scope with a value of undefined and no availability.

The emphasis here is on "code order" and "order of operation" because most of the time we write code that is sequential, that is, "code order" and "run order" are consistent. This also conforms to the human brain's thinking process. Like a programmer with a C language experience.

#include <stdio.h>
int main () {
  int x = 1;
  printf ("%d,", x); 1
}

Two lines of code, the first declaration of integer x, and then output. Code order and run order are consistent, that is, normal operation.

If the order is reversed

#include <stdio.h>
int main () {
  printf ("%d,", x); Error
  int x = 1;
}

At this point, the compilation can not pass. But JS can be written in turn, see two or three.

Therefore, the Class C language experience programmers, are very clear that variables need to be declared before use, or will be an error. And to the JS, there are variables to promote the phenomenon, you can first use after the declaration, C's experience to use JS confusion will appear.

Four, the function expression also exists the variable ascension

function test () {
  alert (func);//undefined
  var func = function () {};
}
Test ();

But if you want to use this func, it's not possible.

function test () {
  alert (func);//undefined
  func ();//Report Exception
  var func = function () {};
}
Test ();

The result func is undefined, and the call to Func will report an exception. In the definition above, accessibility and availability are referred to as the following statements.

Accessibility: Alert (func), output undefined, can run, can access Func.

Availability: Func (), reporting an exception, cannot call Func normally, indicating no availability.

Two, three or four is the use of VAR declaration variables, JS function declaration will also exist to promote, but this "variable" is more special, it is a function type (can be used as functions, methods or constructors). Its name (identifier) is also elevated to the top of the current scope.

The name of the function declaration is also promoted to the top of the current scope

function test () {
  alert (F1);//function
  F1 ();//"called"
  function F1 () {
    alert (' called ');
  }
}
Test ();

We see that the declaration F1 at the very end of the code, F1 used before, alert (F1) and F1 () are performed properly, indicating accessibility and availability.

As mentioned earlier, variable elevation (hoisting) is useless, belonging to the poor design of the language, good habits or "first declared after use." This feature will also appear in many big company questions

Question 1:

Write out the following code run result
var a = 1;
function fn () {
  if (!a) {
    var a = 2;
  }
  alert (a); // ?
}
FN ();

Question 2:

Write out the following code run result
var a = 1;
function fn () {
  a = 2;
  return;
  function A () {}
}
fn ();
alert (a); // ?

But all this with the arrival of ES6 Let/const came to an end, ES in addition to the global variables, other uses Let/const,var replace into let the variable ascension ceased to exist.

function test () {
  alert (declaredButNotAssigned1);//Report Exception
  alert (DECLAREDBUTNOTASSIGNED2);//Report Abnormal
  Alert (func); Report abnormal let
 
  declaredButNotAssigned1;
  Let DeclaredButNotAssigned2 = true;
  Let Func = function () {};
}
Test ();

This forces the programmer to develop good habits, the variable needs to "declare before use", or the error.

The following is an excerpt from MDN's description of let not occurrence of variable elevation

Copy Code code as follows:

In ECMAScript 6, let does not hoist the variable to the "top" of the block. If you are reference a variable in a blocks before the let declaration for that variable are encountered, this results in a Refe Renceerror, because the variable is in a "temporal dead zone" from the "the" of the "the", "the until is process Ed.

typeof is no longer secure when you declare a variable with let

if (condition) {
  alert (typeof num);//error!
  Let num = +;
}
 

Previously can use typeof = = ' undefined ', to determine whether the introduction of a lib, such as jquery

Determine if jquery introduced
if (typeof $!== ' undefined ') {
  //do something
} ...

jquery is not introduced, $ no declaration, this sentence will not be an error to affect the following code execution, but if the LET statement will be an error.

The above mentioned is the entire content of this article, I hope you can enjoy.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.