JS Cheatsheet

Some of the syntax here is specific to the Processing JS framework

Arrays

var friends = ["Jane","John",12];

for (var i = 0; i < friends.length; i++){
    text(friends[i],20, 20 + 20*i);
}

friends[0] = "James"    // updating array value

friends.push("Jane")    // appending to an array
friends.pop(); // removing the last item in the array

Functions

var nameImprover = function(name,adj) {
    return 'Col ' + name + ' Mc' + adj + ' pants';
};

var newName = nameImprover("Pamela", "foxy");
console.log("I'm saved output ", newName);

Defaulting arguments

var nameImprover = function(name,adj) {
    if(adj === undefined) {adj = "Fancy";}
    return 'Col ' + name + ' Mc' + adj + ' pants';
};

var newName = nameImprover("Pamela", "foxy");
console.log("I'm saved output ", newName);

Argument keyword

var addMany = function() {
    console.log(arguments);
    var sum = 0;
    for (var i =0; i < arguments.length; i ++) {
        sum += arguments[i];
    }
    return sum;
}

addMany(1,2,3,52);

Objects

var Winston = {
    age: 19,
    eyes: "black",
    likes: ["programming","being programmed"],
    isCool: true
    birthplace: {    // objects can have nested objects
        city: "Mountain View",
        state: "California"
    }
};

Retrieving Object Values

text("Winston is " + winston.age + " years old", 10, 70);
text("Winston was born in " + winston.birthplace.city + ", " + winston.birthplace.state, 10, 110);

Updating Object Values

winston.age = 20;
winston[1234] = "hello";
winston["middle name"] = "winny";

Deleting Object Properties

delete Winston.age;

Sample code snippet
Code sample of storing objects in arrays

Object Orientated Programming

var Winston = function(nickname, age, x, y){
    this.nickname = nickname;
    this.age = age + " years old";
    this.x = x;
    this.y = y;
}

Making new objects

var winstonTeen = new Winston("Winsteen", 19, 20, 20);
var winstonAdult = new Winston("WinsAdult", 30, 40, 40);

Adding new method to object

Winston.prototype.draw = function() {
    fill(255,0,0);
    var img = getImage("creatures/Winston");
    image(img, this.x, this.y);
    var txt = this.nickname + " , " + this.age;
    text(txt, this.x+20, this.y-10);
};

Calling the method

winstonTeen.draw();
winstonAdult.draw();

Common Patterns

Objects in an array

var positions = [
    {x: 200, y: 100},
    {x: 200, y: 200},
    {x: 200, y: 300}
];

for (var i = 0; i < positions.length; i++) {
    var position = positions[i];
    ellipse(position.x, position.y, 100, 100);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s