Pitfalls during JavaScript interviews: comma, colon, and parentheses

Source: Internet
Author: User

Pitfalls during JavaScript interviews: comma, colon, and parentheses

After reading the knowledge about javaScript data types and expressions and operators, I thought I could try a little on the JavaScript pen question. I didn't expect that I once died of commas, colons, and parentheses, let's take a look at these symbols.

 

Comma

The common usage of comma is to reduce the number of var values when declaring some variables consecutively.

 

 

Var a = 1,

B = 2,

C = 3;

Method parameters are separated by commas (,), and object attributes are separated by commas (,).

 

'''Function fbn (name, title) {} var person = {name: "Byron", age: "24 "}; '''however, we will also encounter such a problem as a comma in the value assignment expression.

 

1

Var a = (1, 2, 3 );

In the expression and operator, we mentioned that the comma operator corresponds to this situation. In this case, the expression calculation result is the last subexpression result, that is, 3. Never misunderstand that the previous subexpression will not be executed. Every subexpression will be executed, but the "return value" is the result of the last expression.

 

 

Var a, B;

A = (B = 1, 2 );

Console. log (a); // 2

Console. log (B); // 1

Colon

? : Operator

 

Var p = gender? 'Male': female;

Object literal

 

 

Var obj = {

Name: "Byron ",

Age: 24

};

Switch statement

 

 

Switch (t ){

Case 1:

Console. log ('xxx ');

Break;

Case 2:

Console. log ('ooo ');

Break;

}

I believe this is a well-known usage, so we can have a question.

 

1

X: y: z: 1, 2, 3;

Will the above operation report an error? What is the result of no error? Many of you will be surprised to see this for the first time. I think it will be wrong, but the result is 3. Let's see why.

 

In fact, the colon has a role: declare label. The statements in JavaScript can have a label prefix. We call it a mark statement. break or continue can be used with the Mark statement to control the process. If the tag already exists, an error occurs. The preceding statements can be translated as follows:

 

 

X:

Y:

Z: 1, 2, 3

In this way, we can understand why the result is 3 based on the comma. Many optimization suggestions do not advocate the use of tags. Do you think of The goto in C language and use the tag control process, it makes the program quite difficult to understand.

 

Var x = 1;

Foo :{

X = 2;

Break foo;

X = 3;

}

Console. log (x );

Braces

Object Direct Volume Declaration

 

 

Var obj = {

Name: "Byron ",

Age: 24

};

The entire statement uses the value assignment statement. the right value contains ten expressions and an object is constructed using a direct quantity.

 

Function declaration or function quantity

 

 

Function fn1 (){

//....

} <Br>

Var fn2 = function (){

//...

};

I believe this usage is not closed.

 

Organize compound statements

 

 

With (obj ){

//...

}

For (){

//...

}

If (){

//...

} Else {

//...

}

The braces do not bring block-level scope

Those familiar with JavaScript must have been familiar with this point. Although braces can organize complicated statements, they refer to the same "Block", with even provides similar functions, unfortunately, JavaScript only has function scope and no block scope. The following method in JavaScript declares global variables. This small knowledge point often leads a hero to bid.

 

Declare variables outside function (whether or not var is used)

Variables are not declared using var in a function.

Directly assigned to the window attribute

 

Var a = 2;

Function fn (){

B = 3;

Window. c = 4;

}

Except for the remaining three types of local variables within the function range, we have mentioned in many JavaScript norms that it is precisely because they do not have block scopes to declare variables as early as possible.

 

 

Function fn (n ){

If (n> 1 ){

Var a = n;

} Else {

Var B = n;

}

Console. log ();

}

Such code has syntax errors in many languages, because the if and else braces have block scopes, And the variables a and B are in their corresponding block scopes, And the access fails when the blocks are out. But in JavaScript, there is no block scope, so we declare the variable console in if and else. log can still be accessed. This is indeed a poor design. To reduce the possibility of errors, we should try to declare the variables in advance.

 

Many written examination questions are designed for this knowledge.

 

 

{A: 1 };

Var x = {a: 1 };

{A: 1, B: 2 };

Var y = {a: 1, B: 2 };

Are you surprised to find it? Let's analyze it.

 

{A: 1} JavaScript has the legendary "Statement priority", that is, when braces can be understood as both a composite statement block and a direct volume of objects, javaScript will understand it as a compound statement quickly. {A: 1} is actually a: 1. Do you know why the returned value is 1 when you think about the role of the colon.

 

Var x = {a: 1} when {a: 1} appears as the right value, it is obviously not a statement, but a direct quantitative expression, therefore, braces are treated as the object's direct amount syntax, and the result is an object.

 

{A: 1, B: 2}; after reading the above, it is simple. It can be translated as: a: 1, B: 2 combined with commas and colons. The result seems obvious, that's 2. However, an error is reported. Why? The comma operator must be followed by an expression, and the tag statement contains ten label statement statements. Therefore, an error is returned.

 

After learning about this knowledge, let's try a few more questions (see the answer on the console, don't try alert)

 

{Foo: [1, 2, 3]} [0];

{A: 1} + 2;

2 + {a: 1 };

I don't know if my friends have done the right thing. The core of these questions is the same. Although braces seem to have no effect, they play the role of statement separator, {foo: [1, 2, 3]} [0] can be understood

 

 

{Foo: [1, 2, 3]};

[0];

Therefore, the returned value is [0], and {a: 1} + 2 is changed

 

 

{A: 1 };

+ 2

But! Why is the difference between 2 + {a: 1? As a result of the addition operator, the plus sign is left-bound, and {} is parsed as an expression (the expression must be added). The knowledge object {a: 1} in the data type is converted to NaN.

 

Parentheses

Parentheses are used in JavaScript.

 

Function declaration or call expression parameter table

 

This is easy to understand. When defining a function, we need to enclose its parameters in parentheses and separate them with commas (,). The same is true for calls.

 

 

Function fn (name, age ){

//...

}

Fn ('byron ', 24 );

Var f = new fn ('byron ', 24)

Condition Statement consisting of some keywords

 

The parentheses in our common if, switch, and while are used for this purpose.

 

 

If (a> 0 ){

//...

}

While (I <len ){

//...

}

For (var I = 0; I <len; I ++ ){

//...

}

Grouping operators can only contain expressions, which can change the operator priority and discard some possible syntax trees. The most common

 

 

Var x = () 1 + 2) * 3;

I believe there is no need to explain more. Many colleagues think that parentheses have the function of forcing expression operations. In fact, this is a one-sided understanding. This only changes the operator priority and generates the result after a new syntax tree.

When a simple json string is converted into an object, because of browser compatibility, the JSON object cannot be used, and json2 is too lazy to be introduced, so it will be processed with eval (), probably written in this way.

 

 

Var jsonStr = ...;

Var jsonObj = eval ('+ jsonStr + ')');

Many students asked why we should add parentheses? The json string "{a: 1, B: 2}" is interpreted as a statement, that is, the legendary label statement, the syntax tree is like this.

 

{

A: 1,

B: 2

}

 

As mentioned above, the comma operator cannot be next to the label statement, so an error is reported. The grouping operator can only contain expressions after brackets are added, so {} becomes the direct amount syntax, this is what we want.

 

Function expression called now

Let's look back at our so-called immediate function execution. There are generally two ways to write

 

(Function (){})();

(Function (){}());

! Function (){}();

After searching a lot of information, I finally saw a reliable explanation. To sum up, first we need to figure out the difference between the function expression and the function declaration. The definition in the ECMAScript specification is rather vague:

The function declaration must contain an Identifier (the name of a function that is commonly used), while the function expression can omit this Identifier:

 

Function declaration:

 

Function Name (parameter: OPTIONAL) {function body}

 

Function expression:

 

Function Name (optional) (parameter: OPTIONAL) {function body}

 

In fact, our common differentiation method is based on the context. If function fn () {} appears as the right value (the right side of the value assignment expression), it is the expression; otherwise, it is the function declaration. There are several seemingly unconventional methods that need attention.

 

New function fn () {}; // expression, because in the new expression

(Function () {} (); // expression, in the grouping Operator

In this way, we can understand the second method, that is, using the grouping operator to change the syntax tree. Similarly, the third method uses the principle behind the unary operator and the expression. We can also write

 

 

+ Function (){}()

-Function (){}()

~ Function (){}()

Zhihu has even written so much on the cloud of Changtian.

 

 

(Function (){}());

(Function (){})();

[Function () {}()];

////////////////////////////////

~ Function (){}();

! Function (){}();

+ Function (){}();

-Function (){}();

////////////////////////////////

Delete function (){}();

Typeof function (){}();

Void function (){}();

New function (){}();

New function (){};

/////////////////////////////////

Var f = function (){}();

/////////////////////////////////

1, function (){}();

1 ^ function (){}();

1> function (){}();

So we should call immediate function execution a function expression called immediately!

 

Brackets

Brackets are relatively the simplest symbols. Generally, there are several types of semantics.

 

* Array-related

 

We know that arrays can be directly instantiated using brackets.

 

 

Var a = [1, 2, 3];

* Get Object Property Values

 

This is also a common usage.

 

 

Var a = [1, 2, 3];

Var B = {name: 'byron '};

A [2];

B ['name'];

Look at some interesting small questions

 

 

[0.0, 5] [0 .. toString. length]; // 0. equivalent

'Foo'. split ('') + [];

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.