JavaScript Comments
Single Line Comment
Single line comments start with //.
Any text between // and the end of the line will be ignored by JavaScript (will not
be executed).
This example uses a single-line comment before each code line:
Example
// Change heading:
document.getElementById("myH").innerHTML = "My First
Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first
paragraph.";
Multiline Comment
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
This example uses a multi-line comment (a comment block) to explain the code:
Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First
Page";
document.getElementById("myP").innerHTML = "My first
paragraph.";
JavaScript Variables
Variables are containers for storing data values. All variables are declared by var
keyword not need to define data type. After the declaration, the variable has no
value. (Technically it has the value of undefined). To assign a value to the variable,
use the equal sign:
All JavaScript variables must be identified with unique names. These unique
names are called identifiers. Identifiers can be short names (like x and y) or more
descriptive names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
Names can contain letters, digits, underscores, and dollar signs.
Names must begin with a letter
Names can also begin with $ and _ (but we will not use it in this tutorial)
Names are case sensitive (y and Y are different variables)
Reserved words (like JavaScript keywords) cannot be used as names
JavaScript Operators
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic on numbers:
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Remainder)
++ Increment
-- Decrement
JavaScript Assignment Operators
Assignment operators assign values to JavaScript variables.
Operator Example Same As
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
JavaScript Comparison Operators
Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator syntax (condition?expr1:exper2)
JavaScript Bitwise Operators
Bit operators work on 32 bits numbers.
Any numeric operand in the operation is converted into a 32 bit number. The
result is converted back to a JavaScript number.
Operator Description Example Same as Result Decimal
& AND 5&1 0101 & 0001 0001 1
| OR 5|1 0101 | 0001 0101 5
~ NOT ~5 ~0101 1010 10
^ XOR 5^1 0101 ^ 0001 0100 4
JavaScript Logical Operators
Operator Description
&& logical and
|| logical or
! logical not
JavaScript String Operators
The + operator can also be used to add (concatenate) strings.