JavaScript operators--conditions, commas, assignments, (), and void operators

Source: Internet
Author: User
Tags arithmetic operators bitwise operators logical operators

Previous words

There are 46 operators in JavaScript, in addition to the arithmetic operators, relational operators, bitwise operators, and logical operators already described earlier, there are many operators. This article describes the conditional, comma, assignment, (), and void operators

Conditional operators

The conditional operator is the only ternary operator (three operands) in JavaScript, sometimes called the ' ternary operator '. Usually this operator is written as '?: ', which is often not abbreviated in code because the operator has three operands, the first operand in '? ' Before, the second operand in the '? ' and ': ', a third operand after ': '

Variable = boolean_expression? True_value:false_value;

Essentially, this is based on the result of boolean_expression evaluation, deciding what value to assign to the variable variable. If the evaluation result is true, assign a value true_value to the variable variable, or assign a value to the variable variable if the evaluation result is false false_value

The operand of the conditional operator can be any type, the first operand as a Boolean value, and if it is true, the second operand is computed and the result of its calculation is returned. Otherwise, if the first operand is a false value, then the third operand is computed and the result of its calculation is returned. The second and third operands always calculate one of them and cannot be executed simultaneously

In fact, using the IF statement will also bring the same effect, '?: ' operator just provides a shorthand form. Here is a typical scenario of '?: ' that determines whether a variable has a definition (and has a meaningful truth value), uses it if it is defined, and uses a default if no definition is used:

greeting = ' Hello ' + (username? Username: ' There ');

This is equivalent to the code below using the IF statement, but obviously the above code is more concise:

greeting = ' Hello '; if (username)    Greeting + = Username;else    Greeting + = ' there ';

Ternary conditional expressions have the same effect as if...else statements, but they have a significant difference, If...else is a statement, no return value, and a ternary conditional expression is an expression with a return value. Therefore, in situations where return values are required, only ternary conditional expressions can be used instead of If...else

Console.log (true?) ' T ': ' F ');

In the above code, the parameter of the Console.log method must be an expression, then only ternary conditional expressions can be used

Comma operator

The comma operator is a two-tuple operator whose operands can be of any type. It first calculates the left operand, calculates the right operand, and finally returns the value of the right operand, with the comma operator to perform multiple operations in a single statement

i = 0,j = 1,k = 2;//The result of the calculation is 2, and it is basically equivalent to the following code i = 0; j = 1; K = 2;

The comma operator is often used to declare multiple variables

var iNum1 = 1, INum = 2, iNum3 = 3;

The most common scenario for a comma operator is in a for loop, which typically has multiple loop variables:

The first comma in the For loop is part of the VAR statement//The second comma is the comma operator//It puts two expressions (i++ and j--) in a statement for (Var i=0, j=10;i<j;i++,j--) {Console.log (i+j) ;}

The comma operator can also be used to assign values, and the comma operator always returns the last item in the expression when used for assignment

var num = (1,2,3,4,5); Console.log (num);//5

[note] Removing parentheses will cause an error.

Assignment operators

The simple assignment operator is represented by the equal sign ' = ', which assigns the value to the right of the equal sign to the variable or property on the left side of the equals sign

i = o;o.x = 1;

The ' = ' operator expects its left operand to be an lvalue: A variable or an object property (or array element). Its right-hand operand can be any value of any type. The value of an assignment expression is the value of the right-hand operand

Although assignment expressions are usually very simple, there are times when you still see some complex expressions that contain assignment expressions. For example, you can put assignment and relationship operators in an expression, like this:

(a=b) = = 0

If you do this, you should be aware of the difference between the ' = ' and ' = = ' operators. ' = ' has a very low priority, usually when the value of an assignment statement is used in a longer expression, parentheses are required to ensure the correct sequence of operations

The binding of an assignment operator is right-to-left, that is, if more than one assignment operator appears in an expression, the order of operations is right-to-left. Therefore, you can assign values to multiple variables in the following ways:

i = j = k = 0;//Initializes three variables to 0

JavaScript also provides 11 compound assignment operators, all of which perform the specified operation first, and then return the resulting value to the left variable

[note] The purpose of designing these operators is to simplify the assignment and use them without any performance improvement

Total + = sales_tax;//equivalent to total = Total + Sales_Tax;
Operator      Example        equivalent to + =         a+=b       a=a+b-=         a-=b       a=a-b*=         a*=b       a=a*b/=         a/=b a=a/b%= A%=b       a=a%b<<=        a<<=b      a=a<<b>>=        a>>=b      a=a>>b> >>=       a>>>=b     a=a>>>b&=         a&=b       a=a&b|=         a|=b       a=a|b ^=         a^=b       a=a^b

In most cases, the expression is:

A op= b

Here op represents an operator, and the expression is equivalent to the following expression

A = a op b

In the first row, expression a evaluates once, and in the second row, the expression a evaluates two times and is not equivalent only if a contains expressions with side effects (such as function calls and assignment actions).

data[i++]*=2;data[i++] = data[i++]*2;

Parentheses operator

The parentheses operator is used in two ways: if the expression is placed in parentheses, the function is evaluated, and if followed by the function, the function is called

Put the expression in parentheses and return the value of the expression

Console.log ((1));  1console.log ((' a ')); ' A ' Console.log ((1+2)); 3

Placing the object in parentheses returns the value of the object, which is the object itself

var o = {P:1};console.log ((o));//Object {p:1}

Putting the function in parentheses returns the function itself. If the parentheses immediately follow the function, it means that the function is called, that is, the function is evaluated

function f () {return 1;} Console.log ((f));//function f () {return 1;} Console.log (f ()); 1

Since the function of the parentheses is to evaluate, if the statement is placed in parentheses, it will be an error, because the statement does not return a value

Console.log (var a = 1);//syntaxerror:unexpected Token Varconsole.log ((var a = 1);//syntaxerror:unexpected token var

void operator

Void is a unary operator that appears before the operand, can be of any type, the operand is evaluated as usual, but ignores the result of the calculation and returns undefined. Because void ignores the value of the operand, void is used to make the program more semantic when the operand has side effects

Console.log (void 0); Undefinedconsole.log (void (0)); Undefined

"Action One" alternative undefined

Since undefined is not a keyword, it is rewritten in the Ie8-browser and is rewritten in the scope of the higher function, so you can replace the undefined with void.

var undefined = 10;console.log (undefined),//ie8-browser is 10, and the browser under the high version is undefined
function T () {    var undefined = ten;    Console.log (undefined);} Console.log (t ());//all browsers are 10

"Function two" client URL

This operator is most commonly used in client url--javascript:url, where expressions with side effects can be written in URLs, while void allows the browser to not display the results of the expression. For example, the void operator is often used in <a> tags in html code

<a href= "Javascript:void window.open (); > Open a new Window </a>

"Action three" block default events

The way to block default events is to give the event a return value of false

General wording <a href= "http://example.com" onclick= "f (); return false;" > Text </a>

Use the void operator to replace the above notation

<a href= "Javascript:void (f ())" > Text </a>

JavaScript operators--conditions, commas, assignments, (), and void operators

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.