Faster, Higher, Stronger

Operators in JavaScript

Operators are the symbols used to work with variables. Operators in JavaScript, as in PHP, can involve mathematics, changes to strings, and comparison and logcal operations (and, or, etc.).

1. Arithmetic Operators

Operator Description Example
+ Addition J+12
Subtraction j-22
* Multiplication j*7
/ Division j/3.13
% Modulus (division remainder) j%6
++ Increment ++j
–– Decrement – –j
(There should be no space between the two “–”, here I place a space between the two “–” just for the purpose to show them more clearly.)

2. Assignment Operators

j = j % 7

Operator Example Equivalent to
= j=99 j = 99
+= j+=2 j = j + 2
+= j+=’string’ j = j + ‘string’
-= j-=12 j = j – 12
*= j*=2 j = j * 2
/= j/=6 j = j / 6
%= j%=7

3. Comparison Operators

Operator Description Example
== Is equal to j==42
!= Is not equal to j!=17
> Is greater than j>0
< Is less than j<100
>= Is greater than or euqal to j>=23
<= Is less than or equal to j<=13
=== Is equal to (and of the same type) j===56
!== Is not euqal to (and of the same type) j!==’1′

4. Logical Operators

Operator Description Example
&& And j == 1 && k == 2
|| Or j < 100 || j > 0
! Not ! (j role=”strong”>== k)

5. Variable Incrementing and Decrementing

Operator What it does Note
x++, ++x Adds one to x (same as x = + 1) While both x++ and ==X add one to x, they are not identical. The former increments x after the assignment is complete, and the later before. For example, if x is 5, y=x++ results in y set to 5 and x set to 6, while y=++x results in both x and y set to 6. The operator – – (minus sign) works similarly.
x– –, – –x Subtracts one from x (same as x = x -1)

6. String Concatenation

JavaScript handles string concatenation slightly differently from PHP. Instead of the . (peirod) opperator, it uses the plus sign (+), like this:

document.write("You have " + messages + "messages.")

Assuming that the variable messages is set to the value 3, the output from this line of code will be:

You have 3 messages.

Just as you can add a value to a numeric variable with the += operator, you can also append one string to another the same say:

name = "James"
name += " Dean"

7. Escaping Characters

Character Meaning
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Tab
\’ Single quote (or apostrophe)
\” Double quote
\\ Backslash
\XXX An octal number between 000 and 377 that represents the Latin-1 character equivalent (such as \251 for the © symbol)
\xXX A hexadecimal number between 00 and FF that represents the Latin-1 character equivalent (such as \xA9 for the © symbol)
\uXXXX A hexadecimal number between 0000 and FFFF that represents the Unicode character equivalent (such as \u00A9 for the © symbol)
赞(0) 打赏
转载需注明来源并给出来源页链接:峰间的云 » Operators in JavaScript

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址