Javascript Basics
Printer Friendly Page
Declare variables
[var is lower case]
var cust;
var balance;
Declare on one line.
var cust, balance;
Declare and assign values together.
var balance = 456.30;
var price = 250.00;
var totdue = price * .06;
String variables can be enclosed with single or double quotes.
var cust = "Smith, John";
OR
var cust = 'Smith, John';
Relational Operators
- less than<
- less than or equal to<=
- greater than>
- greater than or equal to>=
- equal==
- not equal (!=)
Arithmetic Operators
- ADD +
- SUBTRACT-
- MULTIPY *
- DIVIDE /
- MODULO %
- INCREMENT++
- DECREMENT--
Escape Sequences
If a string contains a quote, it will be confused as the end of the line.
var CustomerName = 'Mary O'Grady';
You need to tell JavaScript which quotes are part of the name.
For this you use
ESCAPE SEQUENCES which are backslashes in front of the characters.
var CustomerName = 'Mary O \'Grady';
- Backspace \b
- Form feed\f
- New line\n
- Carriage return \r
- Single quote \'
- Double quote \"
- Single backlash \\
Here is an example of an escape sequence to start a new line.
"Please start a new line\nafter this word.";
Which will appear as
Please start a new line
after this word.
Assignment Operators
| Operator |
Example |
Process |
Description |
| = |
a=b |
a=b |
Assign |
| += |
a+=b |
a=(a+b) |
Add value then assign |
| -= |
a-=b |
a=(a-b) |
Subtract value then assign |
| *= |
a*=b |
a=(a*b) |
Multiply value then assign |
| /= |
a/=b |
a=(a/b) |
Divide value then assign |
| %= |
a%=b |
a=(a%b) |
Modulus value then assign |
if (expression) do this;
var totalnum = 5;
if (totalnum > 0) alert ("The number is " + totalnum; )
OR
var totalnum = 5;
if (totalnum > 0)
{
alert ("The number is " + totalnum; )
}
if (expression) do this ; else do this ;
var totalnum = 5;
var bool;
if (totalnum > 0)
{
bool == true;
}
else
{
bool == false;
}
if (expression) do this ; else if (expression) do this ;
var totalnum = 5;
var bool;
if (totalnum > 0)
{
bool == true;
}
else if (totalnum < 0)
{
bool == false;
}
else
{
alert('The amount is 0')
}
Javascript in HTML
<script type="text/javascript">