| Script tag |
<script> /* JavaScript code */ </script> (code in same file)<script src="myScript.js"></script> (code in external file)
|
|---|---|
| Variable declaration |
var myVariable; // declares variable scope var myVariable = 42; // combines declaration and initialization |
| Arithmetic |
+ - * / |
| Shortcuts |
+= -= *= /= ++ -- |
| Relations |
== != < <= > >= |
| Logic |
&& (and) || (or) ! (not)
true false
|
| Math object |
Math.PI Math.E Math.sqrt(x) Math.pow(x,y) (xy)Math.cos(t) Math.acos(x) Math.exp(x) (ex)Math.sin(t) Math.asin(x) Math.log(x) (natural log)Math.tan(t) Math.atan(x) Math.atan2(y,x) (angle to point x,y)Math.max(x,y) Math.min(x,y) Math.abs(x) (absolute value)Math.round(x) Math.floor(x) Math.ceil(x) (round normally, down, or up)Math.random() (pseudo-random number between 0 and 1)
|
| Control structures |
if (balance <= 0) {
color = "red";
} else {
color = "black";
}
while (t < 10) {
doStuff();
t += dt;
}
for (i=0; i<100; i++) {
total += i*i;
}
|
| Function declaration |
function hypotenuse(a, b) {
return Math.sqrt(a*a + b*b);
}
|
| Arrays |
planets = ["Mercury", "Venus", "Earth", "Mars"];
thirdPlanet = planets[2]; // numbering starts at 0
planetCount = planets.length; // 4
planets.push("Jupiter"); // append an element
planets.sort(); // put into alphabetical order
x = new Array(N); // create array of N elements, 0 to N-1
|
| Objects |
particle = {name:"electron", mass:9.1e-31, charge:1.6e-19};
eOverM = particle.charge / particle.mass;
|
| Formatting numbers |
myString = Number(Math.PI).toFixed(2); // "3.14" |
| HTML event attributes |
onclick = "myFunction();" (use for buttons, links)onchange = "myFunction();" (use for sliders, etc.)
|
| HTML element access |
id = "myElement" (in HTML opening tag)var myElement = document.getElementById("myElement"); (in JavaScript)
|
| Modifying content |
myElement.innerHTML = "New content"; myElement.innerHTML += "Added content"; myButton.value = "New button text"; |
| Modifying style |
myElement.style.color = "red";myElement.style.backgroundColor = "#ffff80";myElement.style.display = "none"; (hide an element completely)myElement.style.display = "block"; (unhide a block element)myElement.style.display = "inline"; (unhide an inline element)
|
| Measuring time |
theTime = (new Date()).getTime(); // time since 1970 in ms |
| Delayed execution |
window.setTimeout(myFunction, 10); // call myFunction in 10 ms |
| Debugging |
console.log("myVariable = " + myVariable);
|