Object Knowledge Flashcards

1
Q

Deep Copy an object

A

JSON.stringify( )
then
JSON.parse( )

or
JSON.parse(JSON.stringify( ))

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

Delete from an object

A

delete myObject.myKey

delete myObject[‘myKey’]

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

What’s the difference between a deep copy and a shallow copy

A

Shallow copy- when you shallow copy an object, all you do is copy the first layer data from the heap. This includes the pointers to other objects

Deep copy- A deep copy also makes a copy of all the nested objects and points to those objects accordingly.

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

Add to an object

A

dot notation
myObject.newKey =

square bracket notation
myObject[‘newKey’] =

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

Change an object key’s value

A

dot notation
myObject.oldKey =

square bracket notation
myObject[‘oldKey’] =

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

Change an object key’s name

A

No built in method

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

Create an object

A

let myObj = { }

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

d

A

f

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

Shallow copy an object (1 ways)

Does it work with arrays?

A
1.
spread syntax
let newObject = {
    ...oldObject
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is returned from adding an entry to an objects?
ex.
{a: 1, b: 2, c: 3}.d = 4

A

4

(and it adds d: 4 to the object.

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

Why is adding an entry to an object in this way:
{a: 1, b: 2, c: 3}.d = 4
useless?

A

Because there is no variable pointing to it. You can not no longer retrieve the object you’ve just changed.

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

What defines an object? (3 things)

A
  1. An unordered collection of data in the form of “key: value” pairs.
  2. JS objects have properties attached to the object.
  3. These keys can be variable or functions (called methods).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do objects, functions and arrays differ?

A

Object-they can have properties and methods

Array- they can have properties and methods just like any other object
BUT they have an ordered collection

Function- they can have properties and methods just like any other object
BUT they can be called

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q
let myObject = {
  apple: 'berry',
  purrple: 'tomato'
}

If you want to log the values to console within a for…in statement:

for (let key in myObject) {
??????
}

How do you do it? (bracket or dot notation)

A

Bracket notation
for (let key in myObject) {
console.log(myObject[key]);
}

What happens if you use myObject.key instead of bracket notation?
(scroll down)

myObject.key
converts key to a string. it will return undefined for each key.

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

What is an object property?

A

a key: value pair

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

What is the object property name?

A

the key

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

How to:
- add and
- access
multiword object keys

A

Use apostrophes.
let anObject = {‘a key’ : ‘a property’}
Use bracket notation
anObject[‘a key’]

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

Input a variable as a key

A
Use bracket notation
let aVariable = 'apple';
let user = {
  [aVariable]: 2
}
let user = {
  name: "John",
  age: 30
};

let key = prompt(“What do you want to know about the user?”, “name”);

alert( user[key] )

It does not work with dot notation

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

What is dot notation

What is square bracket notation

A

dot notation
myObject.newKey =

square bracket notation
myObject[‘newKey’] =

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

What is a computed property?

A

A key that created using the value of a variable:

let apple = 123;
let myObject = { [apple] : 1234};
console.log(myObject) // { '123' : 1234 }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

When to use dot vs square notation

A

Dot for known and simple names.

Use square when you need it.

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

Does this throw an error?

function makeUser(name, age) {
  return {
    name: name,
    age: age,
  };
}
A

No.

Dot notation keys are converted to strings. So the keys name and age, don’t register as variables.

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

What is property value shorthand?

A

When creating an object where the key name and the variable name used as the value are the same, you can:

let name = 'apple';
let anObject = {
  name,
}

Is the same as:

let name = 'apple';
let anObject = {
  name: name
}
which gives {name: 'apple'}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q
Which of these have the correct spacing
let anObject = { 

name: ‘John’
}

or

let anObject = { 
  name : 'John'

}

or

let anObject = { 
  name : 'John'
}

or

let anObject = {

name : ‘John’

}

A
let anObject = { 
  name: 'John'
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q
It's acceptable to use language reserved names as object keys:
let obj = {
  for: 1,
  let: 2,
  return: 3
};
T or F
A

True

They are converted to strings, and called as strings. So it doesn’t interfere with regular code function.

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

Numbers aren’t allow as variables, so why does this work:

let obj = {
  0: "test" // same as "0": "test"
};

// both alerts access the same property (the number 0 is converted to string “0”)
alert( obj[“0”] ); // test
alert( obj[0] ); // test (same property)

A

In the object creation, 0 is converted to a string

In this:
alert( obj[0] )
because numbers aren’t allowed as variables, 0 isn’t a potential variable. JS converts it to string (since object keys are strings)

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

Return Boolean based on whether a key is a part of an object (or a variable containing the key)

Why use it instead of just checking whether anObject.aKey exists?

A
'key' in anObject 
(use quotation marks or bracket notation or it won't look for a string by default)
For example with a variable:
let variable = 'key'
variable in anObject

In case the key value is explicitly ‘undefined’

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

How are objects ordered…
if the keys are strings?
if the keys are numbers (as strings)?
if they are a mix of strings and numbers(as strings)?

A

if the keys are strings
They are ordered by creation order

if the keys are numbers (as strings)
They are ordered by number

if they are a mix of strings and numbers(as strings)?
Numbers are pushed to the beginning

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

If object keys are numbers, they will auto rearrange. How can you stop this?

A

The properties are only reordered IF they are integer properties

So you can cheat by naming the keys
“+10”
“+3”
and they will keep the order (but have a + in them)

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

Write a function to see if an object is empty

2 ways

A
function isEmpty(obj) {
  for (let key in obj) {
    // if the loop has started, there is a property
    return false;
  }
  return true;
}
function isEmpty(array1) {
  return Object.keys(object).length === 0;
}
31
Q
What's the difference between:
let apple = 9;
let pear = apple;
and 
let apple = {9};
let pear = apple;
A

With the primitive number, apple and pear have their own 9 value attached. Primitives are copied as whole values.

But apple and pear for the object both point to a specific instance of {9}. They are stored and copied “by reference”

32
Q
let apple = {9:9};
let pear = apple;

what is returned from:
pear == apple;

Why?

A

True

Because the reference is the same

33
Q
let apple = {9:9};
let pear = {9:9};

what is returned from:
pear == apple;

Why?

A

False

Because the reference is different

34
Q
let apple = JSON.stringify({9:9});
let pear = JSON.stringify({9:9});

what is returned from:
pear == apple;

A

True

Because the string of the objects are the same

35
Q

Term for using objects to represent entities

A

OOP

Object-oriented programming

36
Q

Why use ‘this’ to refer to the object rather than just the object name?

A

So if the object gets copied, or the variable name changes, the references remain local and working.

You can put ‘this’ in a function and assign it to multiple objects.

37
Q

What does ‘this’ refer to?

A

‘this’ references the object of which the function is a property
So the specific thing it references is context specific.

38
Q

When a function is declared, it may have a ‘this’. But the ‘this’ has no value until the function is called.
T or F

A

True

39
Q

Which returns true, which returns false:

function show() {
    console.log(this === undefined);
}
---show();

—console.log(this === undefined)

"use strict";
function show() {
    console.log(this === undefined);
}
---show();
A

false

false
They equal the global object / browser
true

Why?

Basically the rules the people at ECMA setup.

40
Q

In browser, what does ‘this’ refer to?

In node.js, what does ‘this’ refer to?

A

window

global

41
Q

What is logged to console

let car = {
    brand: 'Honda',
    getBrand: function () {
        return this.brand;
    }
}

console.log(car.getBrand());

let brand = car.getBrand;

console.log(brand());

A

Honda

undefined
The method is now just a function attached to ‘brand’. So it references the global object.

42
Q

What’s logged to console:

let car = {
  brand: 'Honda',
  getBrand: function () {
      return this.brand;
  }
}

console.log(car.getBrand());

let brand = car.getBrand.bind(car);

console.log(brand());

A

Honda

Honda

43
Q

Set a variable to an objects method and connect the variable’s ‘this’ to a specific object (doesn’t have to be the same object as the method)

A
let anObject = {
  aMethod() {
    ...
  }
}
let aFunction = anObject.aMethod.bind(anObject);
44
Q

In browser what is logged to console from:
let show = () => this;
console.log(show() === window);

let show1 = () => {
  return this;
}
console.log(show1() === window);
let show1 = () => {
  console.log(this === window);
}
show1();
function show2() {
  return this;
}
console.log(show2() === window);
function show3() {
  console.log(this === window)
}
show3()
A

true

true

true

true

true

(because the function was not called on an object!)

45
Q

What is returned from these:

let myObject = {
  method1: function() {
    return this;
  }
}
myObject.method1() == myObject
Why?
let myObject2 = {
  method2: () => this
}
myObject2.method2() == myObject2
Why?
A

True
‘this’ refers to the object the function is a property

False
It is global.
Arrow functions do not have their own binding to ‘this’ and use the binding of their object parent. In this case, the global object.

46
Q

Does ‘this’ in the arrow function refer to the global object? Why?

let user = {
  firstName: "Ilya",
  sayHi() {
    let arrow = () => alert(this.firstName);
    arrow();
  }
};
user.sayHi();

let user = {
arrow: () => this
};
user.arrow()

A

It references user. The sayHi method binds the arrow function’s this sayHi’s

Yes, it references the global object. It does not have it’s own binding unless within another function

47
Q

Can you apply the bind method to arrow functions to set their ‘this’?

A

no
You cannot rebind this in an arrow function. It will always be defined as the context in which it was defined. If you require this to be meaningful you should use a normal function.

48
Q

Create a constructor function and create a new object with it

A
function User(name) {
  this.name = name;
  this.isAdmin = false;
}

let user = new User(“Jack”);

49
Q

When a function is executed with new, it runs through the following 3 step algorithm:

A

1 A new empty object is created and assigned to this.
2 The function body executes. Usually it modifies this, adds new properties to it.
3 The value of this is returned (unless if an object return is defined. Primitives returns are ignored)

50
Q

Any function can be run with new and it will run through the ‘new’ algorithm
T or F

A

T,

not arrow functions though because they don’t have a ‘this’

51
Q

Within a constructor function:
What happens if you don’t have a ‘return’ operator?
What happens if you return an object?
What happens if you return a primitive?

A

It returns the value of ‘this’
It returns that object
The primitive is ignored and it returns the value of ‘this’

52
Q
You cannot ommit the parenthesis when calling constructor functions:
let user = new User; //
A

F
This works with constructors

53
Q

Is it possible to create functions A and B so that new A() == new B()?

function A() { ... }
function B() { ... }
let a = new A;
let b = new B;

alert( a == b );

A

Yes, it’s possible.

If a function returns an object then new returns it instead of this.

So they can, for instance, return the same externally defined object obj:

let obj = {};

function A() { return obj; }
function B() { return obj; }

alert( new A() == new B() ); // true

54
Q
What is returned from the follow
let user = {
  address: {
    street: 'af'
}
}; 
console.log(user.address.street);
let user = {
  address: 'fasd'
}; 
alert(user.address.street); 
let user = {
}; 
alert(user.address.street);
A

‘af’

undefined

error. Trying to retrieve something from undefined.

55
Q

How can you make sure this doesn’t throw an error?

let user = {
}; 
alert(user.address.street); 

(2 bad ways, 1 good way)

A

Question mark before each dot ?.
Can do:
alert(user.address ? user.address.street ? user.address.street.name : null : null);
alert( user.address && user.address.street && user.address.street.name );

OR

Use optional chaining: (it’s not an operator)
alert( user?.address?.street );
or with bracket notation
user?.[‘address’]?.[‘street’]

56
Q

What does ? do in
alert( user?.address?.street );
?

A

It returns undefined if the preceeding key is called on undefined or null

57
Q

What does ? do in
alert( user?.address.street );
?

A

It returns undefined if user returns undefined or null

58
Q

When should you use optional chaining?

A

Only when it’s ok to have something not exist. Otherwise, you want the error.

59
Q

What happens with
alert( user?.address.street );
if there’s no user variable?

A

Throws an error.

There is no user variable. A non-existent variable name is not “undefined”.

60
Q

How can you use optional chaining to short circuit to stop the evaluation.

A
let user = null;
let x = 0;

user?.sayHi(x++); // no “sayHi”, so the execution doesn’t reach x++

alert(x); // 0, value not incremented

61
Q

What happens with:
let userGuest = {};
userGuest.admin();

A

Throws an error

userGuest.admin is not a function

62
Q

How can you make the following not throw an error:
let userGuest = {};
userGuest.admin();

A

with ?.()

userGuest.admin?.();

63
Q
What happens with this if user doesn't exist?
let user = {}
delete user.name.apple; 
delete user?.name.apple;
delete user?.name?.apple;
A

error
error
returns true

64
Q

What happens with:
console.log(console.log(‘fad’));
Why?

A

fad
undefined

Lines of code passed as arguments are run.

65
Q

What is returned from:

{p: 1} + {q: 2}

A

[object Object][object Object]

66
Q

Boolean( { } )

A

True

67
Q

Write a method that makes an object return specific things when converted to primitives (2 ways)

A
1.  [Symbol.toPrimitive](hint)
let user = {
  name: "John",
  money: 1000,
  [Symbol.toPrimitive](hint) {
    alert(`hint: ${hint}`);
    return hint == "string" ? `{name: "${this.name}"}` : this.money;
  }
};
// conversions demo:
alert(user); // hint: string -> {name: "John"}
alert(+user); // hint: number -> 1000
alert(user + 500); // hint: default -> 1500
  1. toString() and valueOf()
    let user = {
    name: “John”,
    money: 1000,
  // for hint="string"
  toString() {
    return `{name: "${this.name}"}`;
  },
  // for hint="number" or "default"
  valueOf() {
    return this.money;
  }

};

alert( String(user) ); // toString -> {name: “John”}
alert( +user ); // valueOf -> 1000
alert( user + 500 ); // valueOf -> 1500

68
Q

What can you use this for:
Symbol.toPrimitive {
}

A

Allows you to return specific primitives based on whether the object is converted to specific primitives.
Can return anything but it has to be primitive.
When the object is converted, strings of “string”, “default” or “number” are passed as arguments under hint.

let user = {

name: “John”,
money: 1000,

  [Symbol.toPrimitive](hint) {
    alert(`hint: ${hint}`);
    return hint == "string" ? `{name: "${this.name}"}` : this.money;
  }
};
// conversions demo:
alert(String(user)); // hint: string -> {name: "John"}
alert(+user); // hint: number -> 1000
alert(user + 500); // hint: default -> 1500
69
Q

What is logged to console from:
let user = {
name: “John”,
money: 1000,

  [Symbol.toPrimitive](hint) {
    alert(`hint: ${hint}`);
    return hint == "string" ? `apples` : 123;
  }
};

alert(String(user));
alert(user.toString());

A

‘apples’

[object Object]

70
Q
What's the difference between:
forEach
for
for in
for of

Which is best for arrays?

A

The forEach() method executes a provided function once for each array element.

for is just a generic looper and can be used for anything

for of is made for arrays and is faster (just works with values, not numbers or keys but is usually better)

for in can be used with arrays. (the key being the number for (let key in arr) {
alert( arr[key] ); // Apple, Orange, Pear
}

For of is probably the best. For in will run over all properties, not just numbered values. It’s also like 10-100 times slower for arrays.

71
Q

Truncate an array with the length property.

A

array.length = 2;

72
Q
Why do we usually use
arr = []
rather than
let arr = New Array(0)
(2 reasons)
A

It’s easier and shorter

Creating a new array with only a number as the argument will create a new array with that number as the length.

73
Q
How will this:
 let apple = {a:1};
function B() { 
  this.aa= 'aa';
  return apple;
 }
Differ from this:
 let apple = {a:1};
function B() { 
  this.aa= 'aa';
 }

when constructing an object.

A

In the first case, this.aa is overwritten. The constructed object will be apple references.

74
Q

Can you use a function to create an object key?

A

Yes.
myobj.[aFunction()]

The return of the function becomes the key.