Skip to content

Instantly share code, notes, and snippets.

@acidtone
Last active March 23, 2021 16:30
Show Gist options
  • Save acidtone/8464c40543bb499925c59d8c481d626e to your computer and use it in GitHub Desktop.
Save acidtone/8464c40543bb499925c59d8c481d626e to your computer and use it in GitHub Desktop.
Objects: Getting started

Javascript Objects: Getting started

Prerequisites

Learning Objectives

  1. Initialize an array using literal syntax {}:

    const fighter = {
      name: "Gus",
      strength: 8,
      intelligence: 3,
      money: null,
      equipment: ['sword', 'shield', 'teddy bear'],
      greet: function(){
        return `My name is ${this.name}. Prepare to hug!`
      }
    };
  2. Find a property value using dot notation.

    // Gus
    const characterName = fighter.name;
  3. Reassign a property value:

    // quest completed
    fighter.money = 'lots';
  4. Add a new property to and object:

    // found cursed object
    fighter.weaknesses = ['peanuts','witty banter'];
    • Bonus: Add an array item to a property value.

      // Add cursed object to backpack
      fighter.equipment[fighter.equipment.length] = 'Cursed Peanut of Akronis';
  5. Invoke a method:

    // meets creepy stranger on the road
    console.log(fighter.greet());

Key Takeaways

  • Object properties are considered unordered, whereas arrays are ordered.
  • Inside a method, the this keyword usually references the containing object (unless it doesn't).
  • Arrays and objects can be nested inside each other.
  • Objects are named with nouns, methods (aka. functions) are named with verbs.
// Create an object literal using curly braces {}
const fighter = {
name: "Gus",
strength: 8,
intelligence: 3,
money: null,
equipment: ['sword', 'shield', 'teddy bear'],
greet: function(){
return `My name is ${this.name}. Prepare to hug!`
}
};
console.log(`Character Profile: ${fighter}`);
// Retrieve a property value by key using dot notation
const characterName = fighter.name;
console.log(`Character name: ${characterName}`);
// Reassign a property value
fighter.money = 'lots';
console.log(`How much money? ${fighter.money.toUpperCase()}!`);
// Add new property
fighter.weaknesses = ['peanuts','witty banter'];
console.log(`Character weaknesses: ${fighter.weaknesses}!`);
// Bonus
fighter.equipment[fighter.equipment.length] = 'Cursed Peanut of Akronis';
console.log(`New equipment: ${fighter.equipment[fighter.equipment.length-1]}!`);
// Invoke a method
console.log(fighter.greet());
// Log updated fighter profile
console.log(`New Profile: ${fighter}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment