Selected JavaScript Syntax

Part of HTML5 and CSS3 All-in-One For Dummies Cheat Sheet

JavaScript is an important language for programming, game development, and desktop applications. Following are the most commonly used JavaScript syntax elements, including commands for manipulating variables, controlling program flow, and managing functions.

Function Description
alert(“message”); Creates a pop-up dialog containing a message.
var myVar = 0; Creates a variable with given starting value. Type is
determined dynamically.
stringVar = prompt(“message”) Sends a dialog box message to user, retrieves text input from
user and stores it in stringVar.
stringVar.length Returns the length (in characters) of stringVar.
stringVar.toUpperCase(), stringVar.toLowerCase() Converts stringVar to upper- or lowercase.
stringVar.substring() Returns a specified subset of stringVar.
stringVar.indexOf() Returns location of a substring in stringVar (or -1).
parseInt() Convert string to int.
parseFloat() Convert string to float.
toString() Convert any variable to string.
eval() Evaluate string as JavaScript code.
Math.ceil() Convert any number to integer by rounding up.
Math.floor() Convert any number to integer by rounding down.
Math.round() Convert any number to integer by standard rounding
algorithm.
Math.random() Return random float between 0 and 1.
if (condition){

// content

} else {

// more content

} // end if

Executes content only if condition is true.

Optional else clause occurs if condition is false.

} else if (condition) { Add another condition to an if statement.
switch (expression)

case: value;

//code

break;

default:

//code

}

Compare expression against one or more values. If expression is
equal to value, run corresponding code.

Default clause catches any uncaught values.

for(i = 0; i < count; i++)

//code

} // end for

Repeat code i times.
while (condition){

//code

} // end while

Repeat code as long as condition is true.
function fnName(parameters) {

//code

} // end function

Define a function named fnName and send it parameters. All code
inside function will execute when the function is called.
myElement = document.getElementById(“name”); Get an element from the page with the specified ID and copy a
reference to that element to the variable myElement.
document.onkeydown = keyListener When a key is pressed, a function called keyListener is
automatically activated.
document.onmousemove = mouseListener When the mouse is moved, a function called mouseListener is
automatically activated.
setInterval(function, ms); Run function each ms milliseconds.