Objects: the basics Flashcards

1
Q

How can empty objects be created?

A
const new = new Object()
const new = {}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How can we check if a key exists in an object?

A

key in object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How keys ordered in an object if we loop over them using for (const key in object)?

A
  • integers are sorted in ascending order

- non-integers are sorted in creation order

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How are objects assigned and copied?

A
  • by reference in contrast to primitive values which are assigned and copied by value
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How does garbage collection happen in JS?

A
  • automatically based on reachability

- garbage collector of JS engine monitors values which are not accessible or usable somehow

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are methods?

A
  • functions stored in object properties
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is special about “this” in JS?

A
  • 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How can the optional chaining operator ?. be used?

A
  • obj?.prop -> returns prop if existent, undefined otherwise
  • obj?.[prop]
  • obj.method?.() -> call obj.method(), returns undefined
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How can Symbols be used in JS?

A
  • 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How are objects converted to primitives?

A

Conversion algorithm:

  1. Call objSymbol.toPrimitive if exists
  2. Otherwise if hint is “string”
    - > try obj.toString() or obj.valueOf()
  3. Otherwise if hint is “number” or “default”
    - > try obj.valueOf() or obj.toString()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly