JavaScript Objects

Objects

collection of key value pairs

{}

Literal Objects

aka, Anonymous object

aka, Hash Table

aka, Associative Array

aka, Dictionary

// wrapped in open and closing curly braces
var basic_syntax = {};

// keys seperates value pairs separated by colons
var user = { name : "Jon" };

// keys can have special characters
var student = { "first & last name" : "Finn Human" };

// key value pairs are separated by commas
var color = {
  red : 0,
  green : 0x33,
  blue : 0xFF,
  getRGB : function(){
    return (this.red << 16) + (this.green << 8) + this.blue
  }
};

Accessing Object Properties

// access the "green" property of the "color" object
// using dot notation
color.green    // 51


// as an associative array using array accessor square brackets 
color["green"] // 51


var propertyName = "green";
color[propertyName]  // 51

Assigning values to properties

var person = {};

person.name = "Ray";

console.log( person ); // { name: "Ray" }
var person = {
    name: "Ray"
};

Why?

Object may have been passed to you

function isLiving(human) {
    human.isLiving = true;

    return human;
}

var person = { name: "Ray" };

var updatedPerson = isLiving(person);

console.log( updatedPerson ); // { name: "Ray", isLiving: true }


Objects

By vic_lee

Objects

Data Types, Control, Loops

  • 346