Pitfalls during JavaScript interviews-commas, colons, and parentheses

Source: Internet
Author: User

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. The common usage of comma is to reduce the number of var a = 1, B = 2, c = 3 when declaring some variables consecutively. We use commas to separate method parameters, object Attributes are also separated by commas (,) ''' function fbn (name, title) {} var person = {name: "Byron", age: "24 "}; ''' however, we also encounter this problem. The comma 1var a = (1, 2, 3) appears in the value assignment expression ); 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); // 2console. 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 1x: y: z: 1, 2, 3; will the above calculation report an error? What is the result of no error? Many of you are surprised to see this for the first time. I think there will be errors, but the result is 3. Let's see why the colon has a role: declare label, and the statement in JavaScript can have a label prefix, we call it a mark statement. break or continue can be used in combination with the Mark statement to control the process. If the tag already exists, an error occurs. The preceding statement can be translated into x: y: z: 1, 2, and 3 so that 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, which makes the program quite difficult to understand. Var x = 1; foo: {x = 2; break foo; x = 3;} console. log (x); the braces object directly declares var obj = {name: "Byron", age: 24}. The entire statement uses the value assignment statement. the right value contains ten expressions, construct an object function declaration using a direct volume or directly measure function fn1 (){//....} <br> var fn2 = function (){//...}; I believe this usage is not closed. What are the organizational compound statements with (obj ){//...} for (){//...} if (){//...} else {//...} those who are not familiar with JavaScript in block-level scopes are certainly familiar with this point. Although braces can organize complicated statements, they mean the same block ", with even provides similar functions, but unfortunately JavaScript only has function scopes and no block scopes. The following method in JavaScript declares global variables. This small knowledge point often leads the hero to bid and use declaration variables outside the function (whether or not var is used). In the function, instead of declaring variables using var, the variables are directly assigned to the window property var a = 2; function fn () {B = 3; window. c = 4;} except for the remaining three types of local variables in the function range, it is mentioned in many JavaScript specifications, the variable should be declared as early as possible because it does not have the block scope function fn (n) {if (n> 1) {var a = n;} else {var B = n;} console. such code has syntax errors in many languages, because if and else braces have block scopes, and variables a and B are in their own block scopes, when a block is generated, the access fails. 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 test questions are about {a: 1}; var x = {a: 1 };{ a: 1, B: 2 }; var y = {a: 1, B: 2}; are you surprised to try it yourself? Let's analyze {a: 1} JavaScript's legendary "statement first ", that is, when braces can be understood as compound statement blocks or objects directly, JavaScript will understand them as compound statements 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]; {: 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 useless, but it serves as the statement separator. {foo: [, 3]} [0] can be interpreted as {foo: [, 3]}; [0]; therefore, the returned value is [0], and {a: 1} + 2 is changed to {a: 1}; + 2,! Why is the difference between 2 + {a: 1? In this case, the addition operator causes the plus sign to combine on the left. {} is parsed as an expression (the expression must be added together). According to the knowledge object in the data type, {: 1} converts to NaN parentheses. In JavaScript, parentheses have several usage function declaration or call expression parameter table. This is easy to understand. When defining a function, enclose the parameters in parentheses and separate them with commas, the same is true when calling function fn (name, age ){//...} fn ('byron ', 24); var f = new fn ('byron', 24) the Condition Statement is composed of some keywords. The parentheses in the common if, switch, and while statements are the if (a> 0) {//...} used for this condition ){//...} 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) x 3; I believe there is no need to explain it. Many students think parentheses The mandatory expression operation function is actually one-sided understanding. This only changes the operator priority and generates the result after the new syntax tree. When a simple json string is converted into an object, json2 cannot be used because of browser compatibility, so it will be processed with eval, 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}. The comma operator mentioned above 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, which is what we want. Call the function expression immediately. Let's look back at our so-called immediate function execution. There are two methods (function () {}) (); (function () {}());! Function () {} (); I searched a lot of information and finally saw a reliable explanation. To sum up, first we need to clarify the differences between function expressions and function declarations, the definition in the ECMAScript specification is rather vague: function declaration must contain Identifier (the name of a function that is commonly used), while function expressions can omit this Identifier: function declaration: function Name (parameter: OPTIONAL) {function body} function expression: function name (optional) (parameter: OPTIONAL) {function body} In fact, the commonly used differentiation method is based on context, if function fn () {} appears as the right value (to the right of the value assignment expression), it is the expression. Otherwise, it is the function declaration. There are several seemingly unconventional ways to note new function fn () {}; // expression, because in the new expression (function (){}()); // expression. In the grouping operator, we can understand the second method, that is, using the grouping operator to change the syntax tree. The third method is actually to use the principle behind the unary operator and the expression. We can also write the + function () {} ()-function (){}()~ Function () {}() knows that the cloud of the sky has even written so many functions () {}(); (function (){})(); [function () {}()]; ////////////////////////////////~ Function (){}();! Function () {} (); + function () {} ();-function (){}(); /// // delete function () {} (); typeof function () {} (); void 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 are relatively simple symbols. Generally, there are several semantics * array-related. We know that arrays can be directly instantiated using brackets var a = [1, 2, 3]; * It is also common to obtain object property values. var a = [1, 2, 3]; var B = {name: 'byron'}; a [2]; B ['name']; read several interesting small questions [1, 2, 3, 4, 5] [0 .. toString. length]; // 0. equivalent to 0.0 'foo '. split ('') + [];

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.