Question _ JavaScript tips

Source: Internet
Author: User
An identifier refers to a symbol defined in javascript. An identifier may consist of uppercase/lowercase letters, numbers, underscores, and dollar symbols in any order, but it cannot start with a number, it cannot be a reserved keyword in javascript. Note that javascript is case sensitive. JS has variable improvement. This design is actually inferior, or a side effect of language implementation. It allows variables to be accessed without being declared, or the declaration is used later. Beginners are confused about this, and even many veterans who have been using JS for many years are confused. However, after ES6 is added with let/const, the variable Hoisting does not exist.

1. variables are not declared and directly used

function test() {  alert(notDefined);}test(); // ?

It is natural to report an error.

2. Variable Declaration at the end

function test() {  alert(declaredButNotAssigned); // undefined  var declaredButNotAssigned;}test();

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

3. Variable Declaration at the end and assign a value to the variable

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

The result is the same as that of result 2. Obviously, it does not output 1 because the value is assigned.

Second and Third, variables are upgraded (Hoisting ).

Variable escalation: in the specified scope, the code sequence indicates that the variables are first used and then declared, but the "accessibility" of the runtime variables is elevated to the top of the current scope, its value is undefined and there is no "availability ".

Here we emphasize "code order" and "running order" because most of the code we write is executed sequentially, that is, the "Code Order" and "running order" are consistent. This is also in line with the human brain's thinking process. For example, programmers with C language experience

#include 
 
  int main() {  int x = 1;  printf("%d, ", x); // 1}
 

Two sentences of code: declare integer x before output. The code sequence is the same as the running sequence, that is, the code runs normally.

If the order is reversed

#include 
 
  int main() {  printf("%d, ", x); // error  int x = 1;}
 

At this time, compilation fails. But it can be written in JS in turn. See section 2 and section 3.

Therefore, programmers who have experience in C Language know that variables must be declared and used first, otherwise an error will be reported. In JS, there is a variable increase phenomenon. You can use it first and then declare it. C's experience will become confusing in JS.

4. Variable escalation also exists in function expressions

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

However, it is impossible to use this func.

Function test () {alert (func); // undefined func (); // report an exception var func = function () {};} test ();

If func is undefined, an exception is reported when func is called. The following statements about accessibility and availability are mentioned in the above definition.

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

Availability: func (). If an exception is reported, func cannot be called normally, indicating no availability.

II, III, and IV are variables declared using var. Function declarations in JS will also be upgraded, but this "variable" is special, it is a function type (can be used as a function, method, or constructor ). Its name (identifier) is also promoted to the top of the current scope.

5. The function declaration name will also be upgraded to the top of the current scope

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

We can see that the declaration of f1 is at the end of the Code, f1 is used before, alert (f1) and f1 () are executed normally, indicating that both accessibility and availability are available.

As mentioned above, Hoisting is useless. It is a poor language design. A good habit is to "declare it first and then use it ". This feature will also appear in Interview Questions of many large companies.

Question 1:

// Write the following code execution result var a = 1; function fn () {if (! A) {var a = 2;} alert ();//?} Fn ();

Question 2:

// Write the running result var a = 1; function fn () {a = 2; return; function a () {}} fn (); alert (); //?

But all of this ends with the arrival of let/const of ES6. Except for global variables, let/const is used in ES. After var is replaced with let, the variable upgrading will no longer exist.

Function test () {alert (declaredButNotAssigned1); // reports the exception alert (abnormal); // reports the exception alert (func); // reports the exception let declaredButNotAssigned1; let declaredButNotAssigned2 = true; let func = function () {};} test ();

This forces programmers to develop good habits. variables need to be "declared before use"; otherwise, an error is reported.

The following is an excerpt from MDN's description that let does not have variable elevation.

The Code is as follows:


In ECMAScript 6, let does not hoist the variable to the top of the block. if you reference a variable in a block before the let declaration for that variable is encountered, this results in a ReferenceError, because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed.

After variables are declared with let, typeof is no longer secure.

if (condition) {  alert(typeof num); // Error!  let num = 100;} 

In the past, typeof = 'undefined' can be used to determine whether a lib is introduced, such as jQuery.

// Determine whether jQuery has introduced if (typeof $! = 'Undefined') {// do something }...

JQuery is not introduced, and $ is not declared. This statement does not return an error and affects the execution of the following code. However, if it is declared by let, an error is reported.

The above is all the content of this article. I hope you will like it.

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.