JavaScript
John Ryan B. Lorca Instructor I
What is JavaScript?
A client-side scripting language used to create interactive or animated content for the Internet, such as games or advanced financial applications
Variables
To declare a variable, you code:
var variable_name = value;
Output Statement
To display constant strings and variables:
On page
document.write(Hello World!); document.write(var_name);
On Message box
alert(Hello World!); alert(var_name);
String Concatenation
Symbol: plus (+) sign Usage Example:
var i = 5; alert (i + : Aloha!);
Arithmetic Operators
Addition var x = 5, y = 10, sum = 0; sum = x + y; Subtraction var x = 5, y = 10, diff = 0; diff = x - y;
Arithmetic Operators
Multiplication var x = 5, y = 10, prod = 0; prod = x * y; Division var x = 5, y = 10, quo = 0; quo = x / y;
Increment and Decrement
var++
var i = 0; i++; //is the same as i = i + 1 alert(++i); //output: 2, but i is 1
var-var i = 2; i--; //is the same as i = i - 1 alert(--i); //output: 0, but i is 1
8
Ternary Operators
Equal to Less than or equal to Greater than or equal to Not equal to == <= >= !=
Logical Operators
Used in making decisions (conjunction of ternary statements) Follows the truth table concept Symbols:
AND OR -> -> && ||
10
If Statement: Structure
if (<condition>) { <statements>; }
11
if Statement: Example
Example: if (x > 5) { alert(Hello!); }
12
if-else Statement: Structure
if (<condition>) { <statements>; } else { <statements>; }
13
if-else Statement: Example
if x > 5) { alert(Hello!); } else { alert(Goodbye!); }
14
if-else if Statement: Structure
if (<condition) { <statements>; } else if (<condition>) { <statements>; }
15
if-else if Statement: Example
if (x > 5) { alert(Hello!); } else if (x <= 5 && x > 0) { alert(Goodbye!); }
16
if-else if-else Statement: Structure
if (<condition) { <statements>; } else if (<condition>) { <statements>; } else { <statements>; }
17
if-else if-else Statement: Example
if (x > 5) { alert(Hello!); } else if (x <= 5 && x > 0) { alert(Goodbye!); } else { alert(Whatever!); }
18
switch Statement: Structure
switch (<variable_or_ternary_statement>) { case <value_or_ternary_statement>: <statements>; break; ... case default: <statements>; break; }
19
switch Statement: Example
switch (x) { case 5: alert(Hello!); break; case default: alert(Goodbye!); break; }
20
For Loop: Structure
for (<init>; <cond>; <counter>) { <statements>; }
21
For Loop: Example
for (var i = 1; i <= 5; i++) { alert (i + : Hello!); }
22
while Loop: Structure
while (<condition>) { <statements>; }
23
while Loop: Example
var i = 1; while (i <= 5) { alert(i + : Hello!); i++; }
24
do-while Loop: Structure
do { <statements>; } while (<condition>);
25
do-while Loop: Example
var i = 1; do { alert(i + : Hello!); i++; } while (i <= 5);
26