Skip to content

Instantly share code, notes, and snippets.

@louisrli
Last active April 29, 2021 19:08
Show Gist options
  • Save louisrli/8e073f43f83c60256026ad04cc16d391 to your computer and use it in GitHub Desktop.
Save louisrli/8e073f43f83c60256026ad04cc16d391 to your computer and use it in GitHub Desktop.
Object discussion questions

Object Discussion Questions

There is some coding in this discussion. Feel free to write them in a REPL or in the comments below.

  1. How is an object different from an array?
  2. How does const work with objects?
  3. Explain the difference between bracket syntax and dot syntax. Give an example of something that works with bracket syntax but not dot syntax. Give an example of something that works with dot syntax but not bracket syntax.
  4. What are computed properties? Write an example code.
  5. What is the difference between Object.keys and Object.entries? Write example code using both of them.
  6. How do we get only the values of an object?
@louisrli
Copy link
Author

  1. Array is an ordered collection of data. Objects are unordered (though you can still look inside). Objects have key-value pairs and can hold more complex data (e.g., for a car, you can add more specific characteristics).

  2. You can still change what is inside an object with const.

const obj = {
  foo: "bar"
}

// Works
obj.foo = "baz";

// Throws an error.
obj = {};
  1. Bracket syntax.

In one way, you can use quotation marks with all the characters or you can use variables to access properties.

myObj['foo']

// This is useful because you can calculate keys on the fly by using a variable.
// As opposed to dot notation, where you have to write it into the code, it cannot be based on a variable.
const aVariable = 'foo';
myObject[aVariable]

For dot notation, you can only use dollar sign, underscore, letters, numbers, etc.

// doesn't work
myObj.f-e 

// allowed
myObj['f-e'] 

myObj.foo

// Only works if foo is a variable defined, e.g., by const or let
myObject[foo]

// How is this different?
myObject['foo']

// Does this work?
myObject.'foo'
const myPropertyName = 'c'

const myObject = {
  a: 1,
  b: 2,
  [myPropertyName]: 3
} 

console.log(myObject.c) // prints 3
  1. Object.keys returns an array of keys. Object.entries returns an array of keys and values.
let user = {
 name: "John",
 age: 30
};

Object.keys(user) === ["name", "age"] 
Object.entries(user) === [ ["name","John"], ["age",30] ]
  1. Object.values

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment