Objects: the basics Flashcards
How can empty objects be created?
const new = new Object() const new = {}
How can we check if a key exists in an object?
key in object
How keys ordered in an object if we loop over them using for (const key in object)?
- integers are sorted in ascending order
- non-integers are sorted in creation order
How are objects assigned and copied?
- by reference in contrast to primitive values which are assigned and copied by value
How does garbage collection happen in JS?
- automatically based on reachability
- garbage collector of JS engine monitors values which are not accessible or usable somehow
What are methods?
- functions stored in object properties
What is special about “this” in JS?
- value of “this” is defined at run-time
- “this” has no value until the function is called
- arrow functions have no “this” -> if accessed inside an arrow function, it looks in the outer scope
How can the optional chaining operator ?. be used?
- obj?.prop -> returns prop if existent, undefined otherwise
- obj?.[prop]
- obj.method?.() -> call obj.method(), returns undefined
How can Symbols be used in JS?
- symbol represent a unique identifier
- can created by passing a description
let id1 = Symbol(“id”)
let id2 = Symbol(“id”)
Two use cases:
1. “Hidden” object properties to hide something into objects that we need, but others should not
E.g. object returned by external library, which has an id property and we want to also use an id property
2. System symbols used by JS, e.g. Symbol.toPrimitive
How are objects converted to primitives?
Conversion algorithm:
- Call objSymbol.toPrimitive if exists
- Otherwise if hint is “string”
- > try obj.toString() or obj.valueOf() - Otherwise if hint is “number” or “default”
- > try obj.valueOf() or obj.toString()