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)
Author: Yakima
关于作者:楠溪江人,出生于1991年,目前坐标上海。读书时代跳过级、保过送,工作后转过行。2013年本科毕业于北药。看书、码字、敲代码、打羽毛球是我花时间的爱好。曾在某上市药企任国际药品注册岗,现在某高新企业任前端管理岗。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据