Object Knowledge 2 Flashcards

1
Q

What is logged to console?
let [apple, orange] = [1, 2];
console.log(apple);
console.log(orange);

A

1

2

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

What is alerted?
let [firstName, surname] = “John Smith”.split(‘ ‘);
alert(firstName);
alert(surname);

A

John

Smith

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

What is Destructuring assignment?

Does it mutate?

A

Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.

No, it does not destruct. Should probably be called “unpacking syntax”.

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

What is alerted?
let [firstName, , title] = [“Julius”, “Caesar”, “Consul”, “of the Roman Republic”];

alert( title );

A

// Consul

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

Unpack this array into separate variables

[1, 2]

A

let [apple, orange] = [1, 2];

console. log(apple); // 1
console. log(orange); // 2

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

Unpack only the first and third array items into variables:

[“Julius”, “Caesar”, “Consul”, “of the Roman Republic”]

A

let [firstName, , title] = [“Julius”, “Caesar”, “Consul”, “of the Roman Republic”];

alert( title );

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

Destructuring assignment works with any iterable
t or f

let [one, two, three] = new Set([1, 2, 3]);

A

True

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

What is alerted?

let user = {};
[user.name, user.surname] = "John Smith".split(' ');

alert(user.name);
alert(user.surname);

A
// John
// Smith
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Do a for… of loop over an object (3 ways)

A
  1. Operate the for of loop on Object.entries array
  2. Operator the for of loop on Object.entries array and destruct the entries
  3. Add an iterator
1.
With Object.entries
let anObject = {
  one: 1,
  two: 2,
  three: 3
}
for (entries of Object.entries(anObject)) {
  console.log(entries[0]);
  console.log(entries[1]);
}
one
1
two
2
three
3
2.
With Destructuring assignment and Object.entries
let user = {
  name: "John",
  age: 30
};
// loop over keys-and-values
for (let [key, value] of Object.entries(user)) {
  alert(`${key}:${value}`); // name:John, then age:30
}
3.
let anObject = {
  'one': 1,
  'two': 4,
  'three': 6435634,
  [Symbol.iterator]() {
    return {
      counter: 0,
      arrayObj: Object.entries(anObject),
      next() {
        if (this.counter > this.arrayObj.length - 1) {
          return {done: true};
        }
        return {done: false, value: this.arrayObj[this.counter++][1]}
      }
    }
  }       
}

for (value of anObject) {
console.log(value);
}

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

Swap the variable values:

[guest, admin]
let guest = "Jane";
let admin = "Pete";
(make guest = "Pete", admin = "Jane"
A

[guest, admin] = [admin, guest];

Can do more than 2 at a time.

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

What is alerted?
let [name1, name2] = [“Julius”, “Caesar”, “Consul”, “of the Roman Republic”];

alert(name1);
alert(name2);

vs

let [name1, ,name2] = [“Julius”, “Caesar”, “Consul”, “of the Roman Republic”];

alert(name1);
alert(name2);

A
// Julius
// Caesar
// Julius
// Consul
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What happens with this destructuring assignment?

let [name1, name2, …rest] = [“Julius”, “Caesar”, “Consul”, “of the Roman Republic”];

A

Adds the remaining items into an array alled rest
// rest is array of items, starting from the 3rd one
alert(rest[0]); // Consul
alert(rest[1]); // of the Roman Republic
alert(rest.length); // 2

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

Deconstruct an array.

Assign the first 2 items to variables. Add the remaining items into an array

A

let [name1, name2, …rest] = [“Julius”, “Caesar”, “Consul”, “of the Roman Republic”];

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

What is alerted?
let [firstName, surname] = [];

alert(firstName);
alert(surname);

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

setup default values for a destructuring assignment on an array
Setup a default prompt for restructuring assignment on an array

A

let [name = “Guest”, surname = “Anonymous”] = [“Julius”];

alert(name); // Julius (from array)
alert(surname); // Anonymous (default used)

Can be more complicated"
// runs only prompt for surname
let [name = prompt('name?'), surname = prompt('surname?')] = ["Julius"];

alert(name); // Julius (from array)
alert(surname); // whatever prompt gets

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

Destructure an object (make new variables from object properties in one step);
Does the order matter?

A

let {var1, var2} = {var1:…, var2:…}
The order doesn’t matter
But the variable names have to be the same because objects are not iterable.

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

Destructure an object and change the variable names

A
let options = {
  title: "Menu",
  width: 100,
  height: 200
};
// { sourceProperty: targetVariable }
let {width: w, height: h, title} = options;
// width -> w
// height -> h
// title -> title

alert(title); // Menu
alert(w); // 100
alert(h); // 200

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

Have default values when destructuring an object

Have default values when destructuring an array

A
let options = {
  title: "Menu"
};

let {width = 100, height = 200, title} = options;

alert(title); // Menu
alert(width); // 100
alert(height); // 200

let anArray = [1, 2];
let [ appl, pea, purp = 3] = anArray;
console.log(purp);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q
What happens with:
let options = {
  title: "Menu"
};

let {width = prompt(“width?”), title = prompt(“title?”)} = options;

alert(title);
alert(width);

A

Only the prompt for width comes though

// Menu
// (whatever the result of prompt is)
20
Q

Have a default value and change the variable name when destructuring an object

A
let options = {
  title: "Menu"
};

let {width: w = 100, height: h = 200, title} = options;

alert(title); // Menu
alert(w); // 100
alert(h); // 200

21
Q

Destructure remaining object values into an array

A
let options = {
  title: "Menu",
  height: 200,
  width: 100
};
// title = property named title
// rest = object with the rest of properties
let {title, ...rest} = options;

// now title=”Menu”, rest={height: 200, width: 100}
alert(rest.height); // 200
alert(rest.width); // 100

22
Q

Destructure an object or array into existing variables? (no ‘let’ expression)

A

let title, width, height;

// okay now
({title, width, height} = {title: "Menu", width: 200, height: 100});

alert( title ); // Menu

If you don’t put it in (), it assumes it’s a code block and breaks.

23
Q

Destructure a nested array or object

A
let options = {
  size: {
    width: 100,
    height: 200
  },
  items: ["Cake", "Donut"],
  extra: true
};

// destructuring assignment split in multiple lines for clarity
let {
size: { // put size here
width,
height
},
items: [item1, item2], // assign items here
title = “Menu” // not present in the object (default value is used)
} = options;

alert(title);  // Menu
alert(width);  // 100
alert(height); // 200
alert(item1);  // Cake
alert(item2);  // Donut
24
Q

What is a great benefit of using destructured objects as function parameters? (2 things)

A

Don’t have to remember the order of inputs into a function
Don’t have to input ‘undefined’ when you want the default value

let options = {
title: “My menu”,
items: [“Item1”, “Item2”]
};

// ...and it immediately expands it to variables
function showMenu({title = "Untitled", width = 200, height = 100, items = []}) {
  // title, items – taken from options,
  // width, height – defaults used
  alert( `${title} ${width} ${height}` ); // My Menu 200 100
  alert( items ); // Item1, Item2
}

showMenu(options);

25
Q

Create a function that destructures an object for it’s arguments

A

let options = {
title: “My menu”,
items: [“Item1”, “Item2”]
};

function showMenu({title = "Untitled", width = 200, height = 100, items = []}) {
  alert( `${title} ${width} ${height}` ); // My Menu 200 100
  alert( items ); // Item1, Item2
}

showMenu(options);

26
Q
  1. Destruct a nested object

2. Create a function that destructures a nested object for it’s arguments

A
1.
let myObj = {
  one: { 
    two: 22,
  },
}

let {one: {two: apple}} = myObj;

console.log(apple);

2.
let options = {
  title: "My menu",
  items: ["Item1", "Item2"]
};
function showMenu({
  title = "Untitled",
  width: w = 100,  // width goes to w
  height: h = 200, // height goes to h
  items: [item1, item2] // items first element goes to item1, second to item2
}) {
  alert( `${title} ${w} ${h}` ); // My Menu 100 200
  alert( item1 ); // Item1
  alert( item2 ); // Item2
}

showMenu(options);

function({
  incomingProperty: varName = defaultValue
  ...
})
27
Q

When a function expects to destructure an object for its arguments, how can you quickly set all default variables?

A

showMenu( {} );

28
Q

Usually this would give an error to a function expecting to destruct an object for it’s arguments
showMenu({}); // ok, all values are default

showMenu(); // this would give an error

How can you get around this?

A

Make { } the default argument when nothign is given

function showMenu({ title = "Menu", width = 100, height = 200 } = {}) {
  alert( `${title} ${width} ${height}` );
}

showMenu(); // Menu 100 200

29
Q

There is a salaries object:

let salaries = {
  "John": 100,
  "Pete": 300,
  "Mary": 250
};
Create the function topSalary(salaries) that returns the name of the top-paid person.

If salaries is empty, it should return null.
If there are multiple top-paid persons, return any of them.

A
Hint Use Object.entries and destructuring to iterate over key/value pairs.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
function topSalary(salaries) {
  let maxSalary = 0;
  let maxName = null;
  for(const [name, salary] of Object.entries(salaries)) {
    if (maxSalary < salary) {
      maxSalary = salary;
      maxName = name;
    }
  }

return maxName;
}

30
Q

What is logged to console?

let anObject = {
  apple: 1,
  one: {
    two: 2,
    three: 3
  }
}
let {
  apple, 
  one: {
    three,
  },
  ...rest
} = anObject;

console.log(rest);

A

undefined

the … operator only collects the variables within it’s level of nesting.

Have to do this:
let {
  apple, 
  one: {
    three,
  ...rest
  },

} = anObject;

31
Q

Create a linked list (a list of a chain of object)

A
let list = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: {
        value: 4,
        next: null
      }
    }
  }
};

OR

let list = { value: 1 };

list. next = { value: 2 };
list. next.next = { value: 3 };
list. next.next.next = { value: 4 };
list. next.next.next.next = null;

32
Q

Split a list and join it back together

let list = { value: 1 };

list. next = { value: 2 };
list. next.next = { value: 3 };
list. next.next.next = { value: 4 };
list. next.next.next.next = null;

A
Split:
let secondList = list.next.next;
list.next.next = null;

Join:
list.next.next = secondList;

33
Q

Prepend a new value to a list (prepend means add to beginning)

Append a new value to a list

let list = { value: 1 };

list. next = { value: 2 };
list. next.next = { value: 3 };
list. next.next.next = { value: 4 };
list. next.next.next.next = null;

A

list = { value: “new item”, next: list };

list.next.next.next.next= {value: 5, next: null}

34
Q

Remove an item from the middle of a list

A

list.next = list.next.next;

35
Q

What is prototypal inheritance?

A

When we read a property from an object, and it’s missing, JavaScript automatically takes it from the prototype.

36
Q

Set an object as the prototype of another (old way)

A
let animal = {
  eats: true
};
let rabbit = {
  jumps: true
};
rabbit.\_\_proto\_\_ = animal; 
(double underscore)
// sets rabbit.[[Prototype]] = animal. If a property isn't found on rabbit, it looks on animal
37
Q

What happens with this code?

let animal = {
  eats: true,
  walk() {
    alert("Animal walk");
  }
};
let rabbit = {
  jumps: true,
  \_\_proto\_\_: animal
};

let longEar = {
earLength: 10,
__proto__: rabbit
};

longEar.eats;

A

returns true

38
Q

What can __proto__ be?
Can it go in circles?
Can there be multiple prototypes?

A

null or objects
No
No but can have a chain

39
Q

What happens with this code?

let animal = {
  eats: true,
  walk() {
   alert(' Walk Walk ');
  }
};
let rabbit = {
  \_\_proto\_\_: animal
};

rabbit.walk = function() {
alert(“Rabbit! Bounce-bounce!”);
};

rabbit.walk();

A

// Rabbit! Bounce-bounce!

prototype is for reading, not writing.

40
Q

What happens with this code?

let animal = {
  eats: true
};
let rabbit = {
  jumps: true,
  \_\_proto\_\_: animal
};

alert(Object.keys(rabbit));

for(let prop in rabbit) alert(prop);

A
// Object.keys only returns own keys
// jumps
// for..in loops over both own and inherited keys
 // jumps, then eats
41
Q

We have rabbit inheriting from animal.

If we call rabbit.eat(), which object receives the full property: animal or rabbit?

let animal = {
  eat() {
    this.full = true;
  }
};
let rabbit = {
  \_\_proto\_\_: animal
};

rabbit.eat();

A

The answer: rabbit.

That’s because this is an object before the dot, so rabbit.eat() modifies rabbit.

Property lookup and execution are two different things.

The method rabbit.eat is first found in the prototype, then executed with this=rabbit.

42
Q

We have two hamsters: speedy and lazy inheriting from the general hamster object.

When we feed one of them, the other one is also full. Why? How can we fix it?

let hamster = {
  stomach: [],

eat(food) {
this.stomach.push(food);
}
};

let speedy = {
  \_\_proto\_\_: hamster
};
let lazy = {
  \_\_proto\_\_: hamster
};

// This one found the food
speedy.eat(“apple”);
alert( speedy.stomach ); // apple

// This one also has it, why? fix please.
alert( lazy.stomach ); // apple
A

It’s pushing to an object. It’s not reassigning “stomach”. So the all share the same stomach object.

Best way to fix:
    // assign to this.stomach instead of this.stomach.push
let hamster = {
  stomach: [],

eat(food) {
this.stomach = [food];
}
};

43
Q

Make a constructor function create objects with a specific prototype.

A
let animal = {
  eats: true
};
function Rabbit(name) {
  this.name = name;
}

Rabbit.prototype = animal;

let rabbit = new Rabbit(“White Rabbit”); // rabbit.__proto__ == animal

alert( rabbit.eats ); // true

prototype on Rabbit is a regular property.

44
Q

__proto__ is old and depracated, how do you set prototypes for the modern age (2022)

  • Create a new object with a set prototype
  • Set a prototype of an existing object
  • return the object’s prototype (as null or an object)
A

Object.create(proto, [descriptors])
Object.setPrototypeOf(obj, proto)
Object.getPrototypeOf(obj)

45
Q

Why put functions on the prototype rather than the constructor?

A

So functions aren’t duplicated on each object.

46
Q

What happens with this code?

let il = {
  obj: {two: 2, three:3, four:4}
};

let {obj: {two, …apple}} = il;

console.log(obj);

A
error
obj not defined
How do you fix it
.
..
.
.
.
.
.
.
.
.
.
.
.
To fix it, do it in 2 steps:
let {obj} = il;
let {obj: {two, ...apple}} = il;