Objects Flashcards

1
Q

What function prevents data mutation of an object?

A

Object.freeze(obj);

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

How do you make a new object, using an existing object as the prototype of the newly created object?

A

let obj = Object.create(proto, [descriptors])

Example:
let animal = {
  eats: true
};
// create a new object with animal as a prototype
let rabbit = Object.create(animal);

Technically, we can get/set [[Prototype]] at any time. But usually we only set it once at the object creation time and don’t modify it anymore. Changing a prototype “on-the-fly” with Object.setPrototypeOf or obj.__proto__= is a very slow operation as it breaks internal optimizations for object property access operations.

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

Can inherited properties of an object be overwritten?

A

Yes!

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

What is a JavaScript object?

A

An object is a collection of properties, and a property is an association between a name (or key) and a value. The object can contain any data types (numbers, arrays, object etc.)

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

Describe abstraction

A

Refers to only showing essential details and keeping everything else hidden
Users of the classes should not worry about the inner details of those classes and should not directly interact with other classes’ data
If classes are entangled, then on change creates a ripple effect that causes many more changes
Creating an interface through which classes can interact ensures that each piece can be individually developed

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

What is the difference between encapsulation and abstraction

A

Abstraction is about hiding unwanted details while giving out the most essential details, while Encapsulation means hiding the code and data into a single unit e.g. class or method to protect the inner working of an object from the outside world. In other words, Abstraction means extracting common details or generalizing things.

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

What is polymorphism and what is the difference between static and dynamic polymorphism?

A

Polymorphism is the ability to call the same method on different objects and have each of them respond in their own way.
Dynamic:
-Occurs during the runtime of the program (when it is being executed)
-Describes when a method signature is in both a subclass and a superclass
-The methods share the same name but have different implementation
-The subclass that the object is an instance of overrides that of the superclass
Static:
-Occurs during compile-time rather than during runtime
-Refers to when multiple methods with the same name but different arguments are defined in the same class
-Despite the methods having the same name, their signatures are different due to their different arguments

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q
What will this print:
function Foo(){
    console.log(this);
}
A

It prints the window object because this is a global object. Whatever parent scope is, it will be inherited by the child.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q
let obj1 = {name: 'GreenRoots'};
let obj2 = {name: 'GreenRoots'};

obj1 == obj2 // ???
obj1 === obj2 // ???
Object.is(obj1, obj2); // ???

A

They all return false because non-primitive data types are passed by reference (unlike primitive types that are passed by value).
Hence both obj1 and obj2 the value at the different memory locations that they are created on.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q
What will this return in strict mode and non-strict mode?
function f1() {
  return this;
}
A
Non-strict:
// In a browser:
f1() === window; // true
// In Node:
f1() === globalThis; // true

Strict:
f1() === undefined; // true

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

Describe Object Oriented Programming.

A

OOP is based around the concept of “objects”. These are data structures that contain data fields — known in JavaScript as “properties” — and procedures — known as “methods”.
Some of JavaScript’s in-built objects include Math (used for methods such as random , max and sin ), JSON (used for parsing JSON data), and primitive data types like String , Array , Number and Boolean .
Whenever you rely on in-built methods, prototypes or classes, you are essentially using Object-Oriented Programming

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

What are the 4 main principles of Object Oriented Programming?

A

Encapsulation, abstraction, inheritance, and polymorphism

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

What are prototypes?

A

Prototypes are the mechanism by which JavaScript objects inherit methods and properties from one another.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q
let obj = {
   3: "test"
}
What do these return?
console.log(obj[3]);
console.log(obj["3"]);
A

They both access the same property, return “test”

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

How do you determine if there is a property in an object?

A

“key” in object
Returns true or false
The left side of in there must be a property name. That’s usually a quoted string.

If we omit quotes, that means a variable, it should contain the actual name to be tested.

let user = { age: 30 };
let key = "age";

alert(key in user);
or
alert(“age” in user);

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

How do we make a clone of an object?

A

Object.assign(dest, [src1, src2, …])

Example:
let user = {
  name: "John",
  age: 30
};

let clone = Object.assign({}, user);

Keep in mind if a property is an object, you will l have the same problem of copying a reference. To fix that, we should use a cloning loop that examines each value of user[key] and, if it’s an object, then replicate its structure as well. That is called a “deep cloning”.

17
Q
function makeUser() {
  return {
    name: "John",
    ref: this
  };
}

let user = makeUser();

alert( user.ref.name ); // What’s the result?

A

If in strict mode….Error: Cannot read property ‘name’ of undefined

Below works because user.ref() is a method. And the value of this is set to the object before dot .

function makeUser() {
  return {
    name: "John",
    ref() {
      return this;
    }
  };
}

let user = makeUser();

alert( user.ref().name ); // John

18
Q

What kind of type(s) can be object property keys?

A

String and symbol

19
Q

How can you check if a property of an object is inherited or not?

A

hasOwnProperty()

Example:
function Phone() {
  this.operatingSystem = 'Android';
}
const myPhone = new Phone();
console.log(myPhone.hasOwnProperty('operatingSystem'));
// true
20
Q

How can you can confirm if a particular object serves as the prototype of another object?

A

isPrototypeOf()

Example:
const rodent = {
  hasTail: true
};
function Mouse() {
  this.favoriteFood = 'cheese';
}
Mouse.prototype = rodent;
const ralph = new Mouse();
console.log(rodent.isPrototypeOf(ralph));
// true
21
Q

What do you get when you use the constructor property on an object?

A

It returns a reference to the constructor function that created that object in the first place.

Example:
function Longboard() {
  this.material = 'bamboo';
}

const board = new Longboard();console.log(board.constructor);

// function Longboard() {
//   this.material = 'bamboo';
// }

If an object was created using literal notation, its constructor is the built-in Object() constructor function!

22
Q

How do you confirm an object’s prototype?

A

Object.getPrototypeOf()

23
Q

Let’s say we want a Child object to inherit from a Parent object. Why shouldn’t we just set Child.prototype = Parent.prototype

A

Objects are passed by reference. This means that since the Child.prototype object and the Parent.prototype object refer to the same object – any changes you make to Child’s prototype will also be made to Parent’s prototype! We don’t want children being able to modify properties of their parents!

On top of all this, no prototype chain will be set up. What if we want an object to inherit from any object we want, not just its prototype?

24
Q

What does instanceof operator do?

A

The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value.

25
Q

What types can a prototype be?

A

A prototype can be either an object or null. Other types are ignored

26
Q

True or false: The for..in loop iterates over both its own and its inherited properties.

A
True!
If want just own properties, could do something like this:
let animal = {
  eats: true
};
let rabbit = {
  jumps: true,
  \_\_proto\_\_: animal
};
for(let prop in rabbit) {
  let isOwn = rabbit.hasOwnProperty(prop);
  if (isOwn) {
    alert(`Our: ${prop}`); // Our: jumps
  } else {
    alert(`Inherited: ${prop}`); // Inherited: eats
  }
}
27
Q

What types of object to primitive conversions are there and name some examples?

A
1) string: when we're doing an operation an an object that expects a string
// output
alert(obj);
// using object as a property key
anotherObj[obj] = 123;
2) number: For an object-to-number conversion, like when we’re doing maths
// explicit conversion
let num = Number(obj);
// maths (except binary plus)
let n = +obj; // unary plus
let delta = date1 - date2;
// less/greater comparison
let greater = user1 > user2;

3) default: when operator not sure what type to expect. With the exception of working with Date object, the default conversion works the same way as number.

// binary plus uses the "default" hint
let total = obj1 + obj2;
// obj == number uses the "default" hint
if (user == 1) { ... };
28
Q

What is a mixin?

A

A mixin is a technique that takes the properties and methods from one object and copies them over to another object. In other words: a mixin is an technique that provides some useful functionality, but is not meant to be added to the prototype chain.

29
Q

What is Object.assign()?

A

Object.assign() is a method that copies an object’s own (non-inherited) properties from one or more source objects into a target object, then returns the updated target object.

Object.assign() does not create and return a new object; it directly modifies then returns the same target object that was passed in! As such, values of existing properties will be overwritten, while properties that don’t exist in the source object will remain intact.

30
Q

What is a factory function and how does it compare to a constructor function?

A

A factory function is a function that returns an object, but isn’t itself a class or constructor. Using a factory function, we can easily create object instances without the complexity of classes and constructors! Factory functions don’t implicate prototypal inheritance and don’t use the ‘new’ operator.

function Basketball(color) {
  return {
    color: color,
    numDots: 35000
  };
}
31
Q

What is a functional mixin?

A

A factory function creates objects. It is invoked as normal function, not with the new operator. Functional mixins take things a bit further by accepting a mixin as an argument, copies properties and methods from the mixin, and returns a new object.

Example:
function CoffeeMaker(object) {
  let needsRefill = false;
  return Object.assign({}, object, {
    pourAll: function () {
      needsRefill = true;
    },
    isEmpty: function () {
      return needsRefill;
    }
  });
}
32
Q

How do you destructure an object?
How do you assign a property to a variable with another name?
How do you set a default value?

A

Assign a property with a colon. Add default value with an equality sign.

let options = {
  title: "Menu"
};

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

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

33
Q

What is the difference between for..in and for..of?

A

Both for..of and for..in statements iterate over lists; the values iterated on are different though, for..in returns a list of keys on the object being iterated, whereas for..of returns a list of values of the numeric properties of the object being iterated.

let list = [4, 5, 6];

for (let i in list) {
console.log(i); // “0”, “1”, “2”,
}

for (let i of list) {
console.log(i); // “4”, “5”, “6”
}

Another distinction is that for..in operates on any object; it serves as a way to inspect properties on this object. for..of on the other hand, is mainly interested in values of iterable objects. Built-in objects like Map and Set implement Symbol.iterator property allowing access to stored values.

let pets = new Set(["Cat", "Dog", "Hamster"]);
pets["species"] = "mammals";

for (let pet in pets) {
console.log(pet); // “species”
}

for (let pet of pets) {
console.log(pet); // “Cat”, “Dog”, “Hamster”
}

34
Q

What is ‘this’?

A

this is the object that the function is a property of