Skip to content

Instantly share code, notes, and snippets.

@avantgardnerio
Last active November 9, 2015 10:31
Show Gist options
  • Save avantgardnerio/8841ac249234c80fdcae to your computer and use it in GitHub Desktop.
Save avantgardnerio/8841ac249234c80fdcae to your computer and use it in GitHub Desktop.
JavaScript cheat sheet
// Fantastic guide: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types
// ------------------ literals ----------------------
var integer = 7;
var float = 7.7;
var str1 = "Hello world!";
var str2 = 'Hello world!';
var object = {};
var array = ["a", "b"];
// ------------------ functions ------------------
// Named function
function add(a,b) {
return a + b;
}
// Anonymous function
var multiply = function(a,b) {
return a * b;
}
// Anonymous function passed as a parameter to another function
window.requestAnimationFrame(function (timestamp) {
console.log("Anonymous function called! " + timestamp);
});
// Named function passed as a parameter to another function
function render(timestamp) {
console.log("Anonymous function called! " + timestamp);
}
window.requestAnimationFrame(render);
// Anonymous function copied onto "onload" property of image object
var img = new Image();
img.onload = function(event) {
console.log(event);
}
img.src = "http://www.drodd.com/images12/happy-face15.jpg";
// ------------------ objects -----------------------
// Empty object literal
var empty = {};
// Object literal with properties
var person = {
firstName: "Brent",
lastName: "Gardner"
};
// Build object (equivalent to above literal)
var person = new Object();
person.firstName = "Brent";
person.lastName = "Gardner";
// Object propery accessors (equivalent to above literal)
var person = new Object();
person["firstName"] = "Brent";
person["lastName"] = "Gardner";
// ------------------- iteration ---------------------
// Iterate by 1
for(var i = 0; i < 10; i++) {
console.log(i);
}
// While loop iterate by 1 (equivalent to above)
var i = 0;
while(i < 10) {
console.log(i++);
}
// Iterate over array
var ar = ["a", "b", "c"];
for(var i = 0; i < ar.length; i++) {
var item = ar[i];
console.log(item);
}
// Iterate over keys in an object
var person = {
firstName: "Brent",
lastName: "Gardner"
};
for(var key : person) {
var value = person[key];
console.log(key + "=" + value); // output: firstName="Brent" lastName="Gardner"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment