JavaScript operators you don't know

Source: Internet
Author: User
Tags logical operators

Operators are not unfamiliar to everyone, as long as the usual writing code will be used frequently. It may be that everyone is only concerned about their use of the layer is still on the surface only know its usage, but operators have some little-known skills, understand that will let you master the principle of operators and operators of the artifice and solve some of the surface questions

First look at some interview questions, please small partners in line with the principle of not to try to write down and four questions of the running results

//1console.log(‘kaivon‘ && (2+1));console.log(![] || ‘你好,siri‘);//2{    let a=10,b=20;    const fn=()=>(a++,b++,10);    console.log(a,b,fn());    let c=fn();     console.log(a,b,c);}//3for(var i=0,j=0,k;i<6,j<10;i++,j++){    k=i+j;}console.log(k);//4{    let a=1;    let b=a++;    console.log(a,b);    let c=1;    let d=++c;    console.log(c,d);}

For the interview question, I was in the first refusal, the heart is collapsed. Always think of these questions no meaning ah, really in the development of the time who will go to do the problem, and will not encounter such a boring thing, why use this kind of things to interview? Do you think the interviewer came here to pretend to be a force? See us not to answer, a face disdain to despise us? In turn, the interviewer and we have no grievances, the front-end why difficult front-end? However, these things actually make sense, from your answers to these questions you can see that your basic knowledge is comprehensive and you can judge your technical ability.

The above questions contain three operators, logical operators, comma operators, increment decrement operators, and I'll describe these three operators separately.

Logical operator AND operator:&&
  • And it means that at least two data (or expressions) can be used to sign around each one. And will turn the results of both sides into Boolean values.
  • If the value on the left is true, returns the value to the right. Returns the left value if the value on the left is false (the result on the right is not computed)
  • The whole result is true only if the results of both sides are true (for judgment)
  • And the operator can appear multiple, sequentially in order from left to right, and then return with false results. Return the last result if both are true
console.log(‘kaivon‘ && (2+1)); //3

When the operator is encountered, the result && is returned to the left and then to a Boolean, the left is a string, and the result of the conversion to a kaivon Boolean value is true , therefore, && the result of the right side of the operator. The right side is an expression and evaluates to 3, so the entire result is 3.

console.log(![] && ‘你好,siri‘);  //false

The expression on the left is the result of turning an empty array into a Boolean (the algorithm of the object to the basic data type private messages I want to video) and reverse. An empty array turns into a Boolean result true , and the inverse result is false . The left side of the result is false returned directly, and will not ignore the right side of the content, so directly return to the left side of the resultfalse

let n=1;n-1 && (n+=5);console.log(n);     //1 左侧为假,所以不会执行右侧的结果,n不会加5const fn=()=>console.log(‘函数被调用了‘);n==1 && fn();

The first console.log result is 1, indicating n+=5 that the expression is not executed. Because the && expression on the left side of the operator evaluates to a Boolean value of 0, false it returns the result directly to the left and does not go to the right expression, so the value of n does not change.
The second console.log prints out the contents, stating that the && right-hand expression of the operator is executed, because the value of n does not change or 1, so the expression on the left runs as a result, true and according to the rule returns the results to the right, so the calling function is executedfn

console.log(true && ‘kaivon‘ && (2-2) && 4 && ‘陈学辉‘ && true);   //0 返回2-2的结果console.log(true && ‘kaivon‘ && [] && 4 && ‘陈学辉‘);   //陈学辉

According to the last rule above, it is easy to get the result of the above calculation. Operations are executed from left to right, and once the result of an expression is encountered, false execution stops and the entire expression returns the result of the operation. If all the results of the expression are, then the result of the true last expression

Or operator: | |
  • Or, you need at least two data (or expressions) to sign around each one. And will turn the results of both sides into Boolean values.
  • If the value on the left is true, the value to the left is returned (the result on the right is not computed). Returns the value to the right if the left value is False
  • If one side of the result is true, the whole result is true (for judgment)
  • Or an operator can appear more than one, sequentially in the left-to-right order, and then returned with a true result. Return the last result if both are false
let n=1;n-1 || (n+=5);console.log(n);     //6

||The operator to the left of the expression operation results in a 0-turn boolean value false , according to the rules listed above will return the results of the right expression execution, so will be executed n+=5 , the result of the final n is 6

console.log(false || ‘‘ || (2-2) || 4 || ‘陈学辉‘ || true);    //4console.log(false || ‘‘ || ![] || 0 || undefined);      //undefined

According to the above rules it is also easy to know the result of the operation, the || operator left the result of the operation false will be executed on the right side of the expression, until true the result of the evaluation of the expression will stop, and return this value. If none of the expressions are returned true , the result of the last expression is taken

Or the purpose of the operator:

function fn(text){    text=text || ‘kaivon‘;  //用户给了参数,取用户给的值;用户没有给参数,取默认值    console.log(text);}fn();           //kaivon    用户没有传参数,就会用默认的‘kaivon‘fn(‘陈学辉‘);  //陈学辉   用户有传参数,就会用传的参数

This form of the above code is ES5 writes the main object-oriented form, which is used to process the parameters. If the user passes the parameter, it takes the user's arguments, and if the user does not have the parameter, the default is taken. Guaranteed function always has parameters, no error

Comma operator
  • Put multiple expressions in a single statement, execute each expression in left-to-right order, and return the result of the last expression (perform multiple operations in a single statement)
  • The lowest priority, the last to operate the comma
  • Both sides of the comma operator cannot be statements (Assignment statements)
console.log(1,2,3);     //1 2 3 console.log((1,2,3));   //3     

console.logis a function, and the comma inside it indicates the meaning of the parameter separation, not the comma operator. To become an operator, the parentheses are added, the parentheses become the expression, and the expression must require a value, so the comma inside becomes the operator

let a=10,b=(a++,20,30);console.log(a,b);   //11 30

The first comma in the first line of code is: You can declare multiple variables in a single row, reducing the number of let keywords. The second one is placed in parentheses, and the parentheses are followed by an expression. Or that sentence, the expression must produce a value, this time the comma is an operator, the last one will be assigned to the variable, that is, 30.

The following is a detailed analysis of an interview question, and then a deep understanding of the comma operator

for(var i=0,j=0,k;i<6,j<10;i++,j++){    k=i+j;}console.log(k); //18

Many small partners would say that the value of K should not be 14? The value of I go to 5 do not stop, J value went to 9 no also stopped, that add up should be 14 Ah! Why is 18, this unscientific AH!!!

To understand this, you need to combine the three statements of the For loop with the action of the comma operator to understand

  1. The first statement of the For Loop var i=0,j=0,k is to initialize a number of variables, where the comma is the same as the comma in the first statement of the previous code block, to declare multiple variables in one line
  2. The second statement of the For loop i&lt;6,j&lt;10 acts as a loop range, note that there can only be one condition for the loop range, not both less than 5 and less than 8, so here the comma is the real comma operator, it can only take a value, take the last onej&lt;10
  3. For the third statement of the For Loop i++,j++ , the comma of the statement is an operator that executes multiple statements in a row, but the statement does not need to have a return value, only the statement executes the line
  4. In summary, this for cycle represents: Declare three variables, the condition range is j&lt;10 , and I and J each walk once to add. When the value of J is 9, it is no longer added, and the value of I will be added to 9. It has no limit to the unlimited add, but J has no infinite range. So the value of I is followed by J, to get the resulti+j=18

Another function of the comma operator: Swapping values of two variables
Declare two variables that require some way to exchange the values of two variables, what method would you use?

let a=10;let b=20;//问:如何让a与b的值进行交换

There is a dumb way to do this with an intermediate variable, and the code is as follows:

let a=10;let b=20;let c;c=a;a=b;b=c;console.log(a,b);   //20 10

Using the comma operator, the code is as follows:

let a=10;let b=20;a=[b][b=a,0];console.log(a,b);   //20 10

You can see that the use of the comma operator is quite easy to implement, but the code seems to be laborious to read, and is analyzed as follows:

a=[b][b=a,0];   //这条代码的两个中括号表示,前面为数组,后面为下标。在数组中取某一个数据并赋值给aa=[20][b=10,0]  //分别把a与b的值套进去,注意第二个中括号里的b=a,这么写是把a的值赋给b,所以只能套a的值/* * 重点看第二个中括号里的代码,此时这个中括号的作用为下标,所以里面必需产生一个值,那里面的逗号就是运算符了 * 根据逗号运算符的作用,先执行两个表达式,把b的值改成10,再返回最后表达式的值0 * 所以这个中括号牛比的地方有两个,第一个是把b的值改成了10,第二个是整体返回0。也就变成了下面*/a=[20][0]   //这不表示把第0个数据的值(20)赋给a

So, the comma operator with a clever is the Qiao his mother to open the door, Qiao home ~

Increment decrement operator
  • Both can be placed in front of the operand, or can be placed behind the operand
  • Regardless of where they are placed, it is an expression, and the expression will definitely return a value
  • They both have implicit type-to-digital functions

First, verify that the expression has a value, either before or after it is placed

let a=3;console.log(a++);   //3console.log(++a);   //5
After self-increment, post-decrement
  • The result of the expression is the value after the data goes directly to the number
  • The data result is a value of plus 1 or minus 1.
let a=[‘20‘];console.log(a++);   //20    表达式结果为a转数字后的值console.log(a);     //21    数据本身变成了+1后的值let b=‘20‘;console.log(b--);   //20    表达式结果为b转数字后的值console.log(b);     //19    数据本身变成了-1后的值
Former self-increment, pre-decrement
  • The expression, like the result of the data, adds 1 or minus 1 to the data.
let a=[‘20‘];console.log(++a);   //21    表达式结果为a转数字后并加1的值console.log(a);     //21    数据本身也为a转数字后并加1的值let b=‘20‘;console.log(--b);   //19    表达式结果为a转数字后并减1的值console.log(b);     //19    数据本身也为a转数字后并减1的值
Two ways to compare
  • The difference between the two formulations is that the result of the expression is different. The results of the data are written in front and written in the same way
  • If you want to use the result of an expression, see who's in front
    1. The data is in front, and the result is the value of the data
    2. The symbol is in front, the result is the value of data +1 or data-1
{    let a=1;    let b=a++;    console.log(a,b);   //2 1}{    let a=1;    let b=++a;    console.log(a,b);   //2 2}

By contrast, the value of A is 2 (the value of a+1), either in front + + or after + +. But the value of B (the value of the expression) can be seen who is in front, a in front of the value of a, + + in front of the a+1 to take the value of

Good summary! Good summary! Good summary! Important reminder to call three times!

JavaScript operators you don't know

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: 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.