Declaring and Using Variables

JavaScript Syntax Handout

Declaring and Using Variables

Variables in JavaScript do not have a fixed type like in Java. Because of this, you do not have to specify the type when creating a variable. Instead you will use the keyword var.

var a = 10;
var b = 20;
var c = a + b;

If Statements

If statements are exactly the same as in Java.

if (someBooleanFunction()) {
    return 1;

While Loops

While loops are the same as well.

while (someCondition()) {
    sum += 1;

For Loops

For loops are almost exactly the same, except for the counter variable.

// Finds the sum of numbers 0 through 10, inclusive
var sum = 0;
for (var i = 0; i <= 10; i++) {
    sum += i;


Notice where you are used to seeing private void, you will use the keyword function. Notice that the parameters do not have the type specified.

function someFunction (a, b) {
    return a === b;


All operators are the same, except the comparison (==). The comparison operator in Java is == (two equal signs), while the comparison in JavaScript is ===.

a === b; // a equals b
a !== b; // a does not equal b

Event Listeners

object.event = function(e) { 
    // your code  

Common Events