Javascript Basics for Non-Developer Types pt. 4/5

Part 1 of 5, part 2 of 5, part 3 of 5.

Part 3 explained for loops, arrays, while loops, switch statements, and logical operators.


Think of objects like a keychain, having an name (var something = {}) and a bunch of keys with values (properties). Properties are separated by commas.

var myObject = { key: value, key: value, key: value };

There are two ways to create them: object literal notation as shown above, and object constructor, shown below using the keyword new:

var myObj = new Object();

Then add keys and values like, myObj.jello: "jiggly";

There are also two ways to access them. Dot notation accessed through global variable in the example here:

var globalName = ObjectName.PropertyName

And bracket notation:

var globalName = ObjectName["PropertyName"]

Specific Constructors

To create an object with multiple properties at one time, constructors can be set up like so:

function Icecream(topping, scoops) { this.topping = topping; this.scoops = scoops; this.brand = "Ben & Jerrys"; }

Note, this can be used as a placeholder and works with any object. Also, this.brand has already been defined as "Ben & Jerrys" meaning each new ice-cream will inherit that value for brand. To create new ice-creams: 🍦🍦🍦

var chocolate = new Icecream("marshmallows", 4);

var vanilla = new Icecream("sprinkles", 7);


Just as an object can have properties, it can also have actions, referred to as methods. They are called just like functions:


Constructors & Methods

Combining the two, here is a method dinnerTonight within a constructor:

function Pasta(noodle, sauce) { this.noodle = noodle; this.sauce = sauce; this.dinnerTonight = function() { console.log("We are having " + this.sauce + this.noodle); } };

Make the pasta objects: 🍝🍝🍝

pasta1 = new Pasta("spaghetti", "marinara");

pasta2 = new Pasta("orecchiette", "pesto");

Print it out:

console.log(pasta1.dinnerTonight + pasta2.dinnerTonight);

Read on to Part 5.