Javascript (OOP) Flashcards

1
Q

4 pillars of object-oriented programming

A

Encapsulation
Abstraction
Inheritance
Polymorphism

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

Encapsulation in OOP

A

Encapsulation can be defined as “the packing of data and functions into one component”. Packing, which is also known as bundling, grouping and binding, simply means to bring together data and the methods which operate on data. The component can be a function, a class or an object.

This means we group related variables and functions into units which then encapsulate them.

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

Abstraction in OOP

A

In object-oriented programming, abstraction is one of the central principles (along with encapsulation and inheritance). Through the process of abstraction, a programmer hides all but the relevant data about an object in order to reduce complexity and increase efficiency.
For example, when we are driving a car, we are only concerned about driving the car like start/stop the car, accelerate/ break, etc. We are not concerned about how the actual start/stop mechanism or accelerate/brake process works internally.

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

Inheritance in OOP

A

In object-oriented programming (OOP), inheritance is a mechanism that allows an object or other structure to inherit properties and behaviors from another object or other structure. It is a fundamental concept in OOP that promotes code reuse and helps us eliminate redundant code.

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

Polymorphism in OOP

A

The polymorphism is a core concept of an object-oriented paradigm that provides a way to perform a single action in different forms. It provides an ability to call the same method on different JavaScript objects. As JavaScript is not a type-safe language, we can pass any type of data members with the methods.

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

Objects in JS

A

At their core, JavaScript objects are containers storing related data and functionality, i.e. an object is a built-in data type for storing key-value pairs. Data inside objects are unordered, and the values can be of any type.

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

Object Literals

A

Objects can be assigned to variables just like any JavaScript type. We use curly braces, {}, to designate an object literal:

let spaceship = {}; // spaceship is an empty object

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

What do we fill the objects with?

A

We fill an object with unordered data. This data is organized into key-value pairs.
Key-value pairs of an object are also referred to as properties.

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

key-value pairs

A

This is how we organise the data in objects - into key-value pairs. A key is like a variable name that points to a location in memory that holds a value.
All the keys are unique, but values are not.
Key-value pairs of an object are also referred to as properties.

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

key (key-value pairs)

A

A key is like a variable name that points to a location in memory that holds a value. A key’s value can be of any data type in the language including functions or other objects.

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

How do we make a key-value pair in JS?

A

We make a key-value pair by writing the key’s name, or identifier, followed by a colon and then the value. We separate each key-value pair in an object literal with a comma (,). Keys are strings, but when we have a key that does not have any special characters in it, JavaScript allows us to omit the quotation marks:
/* An object literal with two key-value pairs
The spaceship object has two properties Fuel Type and color. ‘Fuel Type’ has quotation marks because it contains a space character. */

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

Name two ways to access object properties in JS

A
  1. Dot notation
  2. Bracket notation
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Dot notation to access object properties

A

Properties of a JavaScript object can be accessed using the dot notation in this manner: object.propertyName. Nested properties of an object can be accessed by chaining key names in the correct order.
If we try to access a property that does not exist on that object, undefined will be returned.
let spaceship = {
homePlanet: ‘Earth’,
color: ‘silver’
};
spaceship.homePlanet; // Returns ‘Earth’,
spaceship.color; // Returns ‘silver’,

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

Bracket notation to access object properties

A

To use bracket notation to access an object’s property, we pass in the property name (key) as a string.
We must use bracket notation when accessing keys that have numbers, spaces, or special characters in them. Without bracket notation in these situations, our code would throw an error.
With bracket notation you can also use a variable inside the brackets to select the keys of an object. This can be especially helpful when working with functions:

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

Differences between dot notation and bracket notation to access object properties

A

We must use bracket notation when accessing keys that have numbers, spaces, or special characters in them. Without bracket notation in these situations, our code would throw an error.

With bracket notation you can also use a variable inside the brackets to select the keys of an object. This can be especially helpful when working with functions:

let returnAnyProp = (objectName, propName) => objectName[propName];

returnAnyProp(spaceship, ‘homePlanet’); // Returns ‘Earth’

If we tried to write our returnAnyProp() function with dot notation (objectName.propName) the computer would look for a key of ‘propName’ on our object and not the value of the propName parameter.

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

Restrictions in Naming Properties

A

JavaScript object key names must adhere to some restrictions to be valid. Key names must either be strings or valid identifier or variable names (i.e. special characters such as - are not allowed in key names that are not strings).

// Example of invalid key names
const trainSchedule = {
platform num: 10, // Invalid because of the space between words.
40 - 10 + 2: 30, // Expressions cannot be keys.
+compartment: ‘C’ // The use of a + sign is invalid unless it is enclosed in quotations.
}

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

Properties and values of a JavaScript object

A

A JavaScript object literal is enclosed with curly braces {}. Values are mapped to keys in the object with a colon (:), and the key-value pairs are separated by commas. All the keys are unique, but values are not.

Key-value pairs of an object are also referred to as properties.

const classOf2018 = {
students: 38,
year: 2018
}

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

Explain mutability of JS objects

A

JavaScript objects are mutable, meaning their contents can be changed, even when they are declared as const. New properties can be added, and existing property values can be changed or deleted.

It is the reference to the object, bound to the variable, that cannot be changed.

const student = {
name: ‘Sheldon’,
score: 100,
grade: ‘A’,
}

console.log(student)
// { name: ‘Sheldon’, score: 100, grade: ‘A’ }

delete student.score
student.grade = ‘F’
console.log(student)
// { name: ‘Sheldon’, grade: ‘F’ }

student = {}
// TypeError: Assignment to constant variable.

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

Property (re)assignment in JS objects

A

It’s important to know that although we can’t reassign an object declared with const, we can still mutate it, meaning we can add new properties and change the properties that are there.

We can use either dot notation, ., or bracket notation, [], and the assignment operator, = to add new key-value pairs to an object or change an existing property.

One of two things can happen with property assignment:

If the property already exists on the object, whatever value it held before will be replaced with the newly assigned value.
If there was no property with that name, a new property will be added to the object.

const spaceship = {type: ‘shuttle’};
spaceship = {type: ‘alien’}; // TypeError: Assignment to constant variable.
spaceship.type = ‘alien’; // Changes the value of the type property
spaceship.speed = ‘Mach 5’; // Creates a new key of ‘speed’ with a value of ‘Mach 5’

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

Delete operator

A

Once an object is created in JavaScript, it is possible to remove properties from the object using the delete operator. The delete keyword deletes both the value of the property and the property itself from the object. The delete operator only works on properties, not on variables or functions.

const person = {
firstName: “Matilda”,
age: 27,
hobby: “knitting”,
goal: “learning JavaScript”
};

delete person.hobby; // or delete person[hobby];

console.log(person);
/*
{
firstName: “Matilda”
age: 27
goal: “learning JavaScript”
}
*/

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

Object methods

A

JS objects may have functions as property values. These are referred to as object methods.

Methods may be defined using anonymous arrow function expressions, or with shorthand method syntax.

Object methods are invoked with the syntax: objectName.methodName(arguments).

const engine = {
// method shorthand, with one argument
start(adverb) {
console.log(The engine starts up ${adverb}...);
},
// anonymous arrow function expression with no arguments
sputter: () => {
console.log(‘The engine sputters…’);
},
};

engine.start(‘noisily’);
engine.sputter();

/* Console output:
The engine starts up noisily…
The engine sputters…
*/

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

What is the difference between object property and method?

A

A property is what an object has, while a method is what an object does.

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

How do we access nested properties of an object?

A

Nested properties of an object can be accessed by chaining key (property) names in the correct order. We’ll have to pay attention to which operator makes sense to use in each layer.

const apple = {
color: ‘Green’,
price: {
bulk: ‘$3/kg’,
smallQty: ‘$4/kg’
}
};
console.log(apple.color); // ‘Green’
console.log(apple.price.bulk); // ‘$3/kg’

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

What does it mean when we say that JS objects are passed by reference?

A

This means when we pass a variable assigned to an object into a function as an argument, the computer interprets the parameter name as pointing to the space in memory holding that object. As a result, functions which change object properties actually mutate the object permanently (even when the object is assigned to a const variable).

const origNum = 8;
const origObj = {color: ‘blue’};

const changeItUp = (num, obj) => {
num = 7;
obj.color = ‘red’;
};

changeItUp(origNum, origObj);

// Will output 8 since integers are passed by value.
console.log(origNum);

// Will output ‘red’ since objects are passed
// by reference and are therefore mutable.
console.log(origObj.color);

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

JS for…in loop

A

The JavaScript for…in loop can be used to iterate over the keys of an object. In each iteration, one of the properties from the object is assigned to the variable of that loop.

const object = { a: 1, b: 2, c: 3 };

for (const property in object) {
console.log(${property}: ${object[property]});
}

// Expected output:
// “a: 1”
// “b: 2”
// “c: 3”

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

Why do we have to use a for … in loop to iterate over the keys of an object?

A

Because key-value pairs in objects are not ordered, which means we cannot iterate through them using numerical indexing like we can do with arrays.

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

this Keyword

A

The reserved keyword this refers to a method’s calling object, and it can be used to access properties belonging to that object.

Here, using the this keyword inside the object function to refer to the cat object and access its name property.

const cat = {
name: ‘Pipey’,
age: 8,
whatName() {
return this.name
}
};

console.log(cat.whatName());
// Output: Pipey

The this keyword references the calling object which provides access to the calling object’s properties. In the example above, the calling object is cat and by using this we’re accessing the cat object itself, and then the name property of cat by using property dot notation.

The this keyword always refers to an object, but it can refer to different objects depending on how this is being invoked (used or called). We should always make sure we know which object this keyword will refer to before using it.

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

Why do we need the reserved this keyword?

A

That’s because inside the scope of a method, we don’t automatically have access to other properties of the object of this method.

We need the this keyword to access the object itself and then we can access its other properties using dot notation.

We should always make sure we know which object this keyword will refer to before using it.

29
Q

Name all uses of this keyword.

A

In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called).

The this keyword refers to different objects depending on how it is used:

In an object method, this refers to the object.
Alone, this refers to the global object.
In a function, this refers to the global object.
In a function, in strict mode, this is undefined.
In an event, this refers to the element that received the event.
Methods like call(), apply(), and bind() can refer this to any object.

We should always make sure we know which object this keyword will refer to before using it.

30
Q

Explain keyword this in relation to the function scope

A

Every JavaScript function or method has a this context. For a function defined inside of an object, this will refer to that object itself. For a function defined outside of an object, this will refer to the global object (window in a browser, global in Node.js).

const restaurant = {
numCustomers: 45,
seatCapacity: 100,
availableSeats() {
// this refers to the restaurant object
// and it’s used to access its properties
return this.seatCapacity - this.numCustomers;
}
}

We should avoid using arrow functions when using this in a method because it will not work as we expect it to.

31
Q

Why should we avoid using arrow functions when using this in a method?

A

This is because arrow functions inherently bind, or tie, an already defined this value to the function itself that is NOT the calling object. This means that JavaScript arrow functions do not have their own this context, but use the this of the surrounding lexical context. Thus, they are generally a poor choice for writing object methods.

const myObj = {
data: ‘abc’,
loggerA: () => { console.log(this.data); },
loggerB() { console.log(this.data); },
};

myObj.loggerA(); // undefined
myObj.loggerB(); // ‘abc’

loggerA is a property that uses arrow notation to define the function. Since data does not exist in the global context, accessing this.data returns undefined.

loggerB uses method syntax. Since this refers to the enclosing object, the value of the data property is accessed as expected, returning “abc”.

32
Q

Privacy in objects (JS)

A

When discussing privacy in objects, we define it as the idea that only certain properties should be mutable or able to change in value.

33
Q

Privacy in JS

A

Certain languages have privacy built-in for objects, but JavaScript does not have this feature. Rather, JavaScript developers follow naming conventions that signal to other developers how to interact with a property. One common convention is to place an underscore _ before the name of a property to mean that the property should not be altered. Here’s an example of using _ to prepend a property.

const bankAccount = {
_amount: 1000
}

In the example above, the _amount is not intended to be directly manipulated.

Even so, it is still possible to reassign _amount.

34
Q

JavaScript Getter (The get Keyword)

A

The get syntax binds an object property to a function that will be called when that property is looked up. It can also be used in classes.

const obj = {
log: [‘a’, ‘b’, ‘c’],
get latest() {
return this.log[this.log.length - 1];
},
};

console.log(obj.latest);
// Expected output: “c”

35
Q

Some advantages of using getter methods:

A
  • Getters can perform an action on the data when getting a property.
  • Getters can return different values using conditionals.
  • In a getter, we can access the properties of the calling object using this.
  • The functionality of our code is easier for other developers to understand.
36
Q

Differences between methods and getters.

A

All getters are methods, but not all methods are getters. Only those specially declared with get are getters, and they always return the value of the variable to which they are associated.

37
Q

JavaScript Setter (The set Keyword)

A

The setter methods reassign values of existing properties within an object. The set syntax binds an object property to a function to be called when there is an attempt to set that property. It can also be used in classes.

const language = {
set current(name) {
this.log.push(name);
},
log: [],
};

language.current = ‘EN’;
language.current = ‘FA’;

console.log(language.log);
// Expected output: Array [“EN”, “FA”]

38
Q

Some advantages of using setter methods:

A

Like getter methods, there are similar advantages to using setter methods that include checking input, performing actions on properties, and displaying a clear intention for how the object is supposed to be used.

39
Q

What does it mean when we say that getters and setters intercept property access?

A

JavaScript getter and setter methods are helpful in part because they offer a way to intercept property access and assignment, and allow for additional actions to be performed before these changes go into effect.

const myCat = {
_name: ‘Snickers’,
get name(){
return this._name
},
set name(newName){
//Verify that newName is a non-empty string before setting as name property
if (typeof newName === ‘string’ && newName.length > 0){
this._name = newName;
} else {
console.log(“ERROR: name must be a non-empty string”);
}
}
}

40
Q

What do we mean when we say that getters and setters restrict interactions with object properties?

A

JavaScript object properties are not private or protected. Since JavaScript objects are passed by reference, there is no way to fully prevent incorrect interactions with object properties.

One way to implement more restricted interactions with object properties is to use getter and setter methods.

Typically, the internal value is stored as a property with an identifier that matches the getter and setter method names, but begins with an underscore (_).

const myCat = {
_name: ‘Dottie’,
get name() {
return this._name;
},
set name(newName) {
this._name = newName;
}
};

// Reference invokes the getter
console.log(myCat.name);

// Assignment invokes the setter
myCat.name = ‘Yankee’;

41
Q

Why do we need a setter, if we are using _ to not have the property changed by others?

A

When we decide to implement setters, it is because even though we used the underscore to visually alert other developers that the property must not be changed directly, we plan to use that property dynamically (aka, we want to have it’s value changed) through the setter to modify its value indirectly and under our own conditions, that way we can make sure there is always a value being assign(not an empty value like null or an empty string), and/or it is of the type we need (ie. string).

In short, we give “privatized” properties (because they are only private by developer’s code of honor, not because of JavaScript) a setter when we want them to be modified in such way that we can prevent unnecessary or unexpected errors.

const robot = {
_model: ‘1E78V2’,
_energyLevel: 100,

//lets give it a energy level getter

get energyLevel () {
return this._energyLevel;
}

/*and since we want to have the energy level to be modified as the robot performs different tasks, we will give it a setter: */

set energyLevel(numLevel) {
if( numLevel && typeof numLevel === “Number” && numLevel > 0 ){

/* we check first if the argument is true (aka if a value has been given), and if its type is a number, and if the value is greater than 0. If all that is true, then: */

  this._energyLevel = numLevel;
} else {
  console.log( 'Error:  Value does not exist, is not a number, or not greater than zero' );    }   }

};

With that setter we can interact with the energy level, making sure that it is under our conditions. So, as we can see, some of the properties that we don’t want to have directly changed, we do intend to use them as mutable properties (having their values change), but we use setters as safety measure so they can be modifed under the conditions that we want.

42
Q

Why use Getters and Setters?

A

It gives simpler syntax
It allows equal syntax for properties and methods
It can secure better data quality
It is useful for doing things behind-the-scenes

43
Q

JS factory functions

A

A factory function is a function that returns an object and can be reused to make multiple object instances. Factory functions can also have parameters allowing us to customize the object that gets returned.

/* A factory function that accepts ‘name’, ‘age’, and ‘breed’ parameters to return a customized dog object. */

const dogFactory = (name, age, breed) => {
return {
name: name,
age: age,
breed: breed,
bark() {
console.log(‘Woof!’);
}
};
};

44
Q

Give a real-life example of using a factory function.

A

Since Factory Functions are meant to create alike objects in a way that makes it easier to produce in mass quantities, a possible example when you would think on using a factory function instead of making a regular object literal would be a social network where let’s say each profile is an object.

If we wanted a very minimalistic user with only name, image, friends and posts we could dynamically create them with a factory function where we could also have methods to add friends and create posts:

const makeUser = (id, name, image) => {
return({
id,
name,
image,
friends: [],
posts: [],
addFriend (friend) {
this.friends.push(friend);
},
createPost (post) {
this.posts.push(post);
}
})
};

Now every time a user wants to sign up in our very simple social network app when they click sign up, this function will be triggered and they will become a new user object, where if they decide to add a friend the .addFriend() method will trigger with the friend to be added to the friends array.

45
Q

Property Value Shorthand (shorthand property name syntax for object creation)

A

The shorthand property name syntax in JavaScript allows creating objects without explicitly specifying the property names (ie. explicitly declaring the value after the key). In this process, an object is created where the property names of that object match variables which already exist in that context. Shorthand property names populate an object with a key matching the identifier and a value matching the identifier’s value.

regular code:

const monsterFactory = (name, age) => {
return {
name: name,
age: age
}
};

shorthand:

const monsterFactory = (name, age) => {
return {
name,
age
}
};

46
Q

Destructuring assignment in JS

A

ES6 introduced some new shortcuts for assigning properties to variables known as destructuring.

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

// the example below is for arrays

let a, b, rest;
[a, b] = [10, 20];

console.log(a);
// Expected output: 10

console.log(b);
// Expected output: 20

[a, b, …rest] = [10, 20, 30, 40, 50];

console.log(rest);
// Expected output: Array [30, 40, 50]

47
Q

Destructuring assignment in JS for objects

A

The JavaScript destructuring assignment is a shorthand syntax that allows object properties to be extracted into specific variable values.

It uses a pair of curly braces ({}) with property names on the left-hand side of an assignment to extract values from objects. The number of variables can be less than the total properties of an object.

const rubiksCubeFacts = {
possiblePermutations: ‘43,252,003,274,489,856,000’,
invented: ‘1974’,
largestCube: ‘17x17x17’
};
const {possiblePermutations, invented, largestCube} = rubiksCubeFacts;
console.log(possiblePermutations); // ‘43,252,003,274,489,856,000’
console.log(invented); // ‘1974’
console.log(largestCube); // ‘17x17x17’

48
Q

Name two types of built-in object methods.

A
  1. object instance methods,
  2. object class methods
49
Q

.hasOwnProperty() for objects

A

The hasOwnProperty() method of Object instances returns a boolean indicating whether this object has the specified property as its own property (as opposed to inheriting it).

const object1 = {};
object1.property1 = 42;

console.log(object1.hasOwnProperty(‘property1’));
// Expected output: true

console.log(object1.hasOwnProperty(‘toString’));
// Expected output: false

50
Q

.hasOwnProperty() for objects

A

The valueOf() method of Object instances converts the this value to an object. This method is meant to be overridden by derived objects for custom type conversion logic.

function MyNumberType(n) {
this.number = n;
}

MyNumberType.prototype.valueOf = function () {
return this.number;
};

const object1 = new MyNumberType(4);

console.log(object1 + 3);
// Expected output: 7

51
Q

.valueOf() for objects

A

The valueOf() method of Object instances converts the this value to an object. This method is meant to be overridden by derived objects for custom type conversion logic.

JavaScript calls the valueOf method to convert an object to a primitive value. You rarely need to invoke the valueOf method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.

function MyNumberType(n) {
this.number = n;
}

MyNumberType.prototype.valueOf = function () {
return this.number;
};

const object1 = new MyNumberType(4);

console.log(object1 + 3);
// Expected output: 7

52
Q

Object.assign()

A

The Object.assign() static method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// Expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget === target);
// Expected output: true

53
Q

Object.entries()

A

The Object.entries() static method returns an array of a given object’s own enumerable string-keyed property key-value pairs.

const object1 = {
a: ‘somestring’,
b: 42,
};

for (const [key, value] of Object.entries(object1)) {
console.log(${key}: ${value});
}

// Expected output:
// “a: somestring”
// “b: 42”

54
Q

Object.keys()

A

The Object.keys() static method returns an array of a given object’s own enumerable string-keyed property names.

const object1 = {
a: ‘somestring’,
b: 42,
c: false,
};

console.log(Object.keys(object1));
// Expected output: Array [“a”, “b”, “c”]

55
Q

Give an example of using an object as a “trick” to return multiple values from a function

A

function test() {
const name = ‘Flavio’
const age = 38

return { name, age }
}

Then we can call the function and save the object to a variable, or use object destructuring like this:

const { name, age } = test()

56
Q

Give an example of passing objects as function parameters

A

const printNameAndAge = ({ name, age }) => {
console.log(name, age)
}

const person = {
name: ‘Flavio’,
age: 38
}

printNameAndAge(person)

//or

printNameAndAge({ name: ‘Roger’, age: 9 })

57
Q

Give two ways to clone objects in JS

A
  1. The simplest is to use the spread operator (this way has an issue, though as if some properties of the object are in turn objects, then only their references are copied),
  2. Deep cloning with structuredClone() function.
58
Q

Explain the use of spread operator to clone objects.

A

This is the simplest way to clone objects

const a = { test: ‘test’ }
const b = { …a }

Now b is a new object with the same properties as a, but completely independent.

This way has an issue, though as if some properties of the object are in turn objects, then only their references are copied.

const a = { dog: { name: ‘test’ } }
const b = { …a }
a.dog.name= ‘good dog’
b.dog.name //’good dog’

59
Q

Explain the use of structuredClone() function to clone objects.

A

This is the built-in method in JS that allows us to perform deep cloning - to ensure that objects and their object-properties are completely independent, i.e. copied wholly and not only by-reference.

const a = { dog: { name: ‘test’ } }
const b = structuredClone(a)

a.dog.name= ‘good dog’
b.dog.name //’test’

60
Q

Explain how to sort an array of objects by a property value

A

You can use the sort() method of Array, which takes a callback function, which takes as parameters 2 objects contained in the array (which we call a and b):

list.sort((a, b) => (a.color > b.color) ? 1 : -1)
When we return 1, the function communicates to sort() that the object b takes precedence in sorting over the object a. Returning -1 would do the opposite.

The callback function could calculate other properties too, to handle the case where the color is the same, and order by a secondary property as well:

list.sort((a, b) => (a.color > b.color) ? 1 : (a.color === b.color) ? ((a.size > b.size) ? 1 : -1) : -1 )

61
Q

Explain how to merge two objects into one

A

To merge two simple objects into one you can use the spread operator in this way:

const object1 = {
name: ‘Flavio’
}

const object2 = {
age: 35
}

const object3 = {…object1, …object2 }
Notice that if both objects have a property with the same name, then the second object property overwrites the first.

Also note that if properties of the object are not primitive types, only their reference is copied, not the object.

62
Q

Give three functions that can help us apply the ‘this’ keyword

A

apply,
call,
bind

63
Q

Explain the call function in JS

A

Call is a function that helps you change the context of the invoking function. In layperson’s terms, it helps you replace the value of this inside a function with whatever value you want.

This function accepts a variable number of parameters, which it passes as function arguments.

64
Q

Explain the apply function in JS

A

Similarly to call, apply helps you replace the value of this inside a function with whatever value you want. The only difference is that in apply you can pass an array as an argument list.

65
Q

Explain the bind function in JS

A

Bind is a function that helps us create another function that we can execute later with the new context of this that is provided.

This is helpful when we want to have a function access the object properties but we can’t because we defined it outside of the object.

66
Q

Give an example of using the call/apply function

A

const car = {
maker: ‘Ford’,
model: ‘Fiesta’
}

const drive = function(kmh) {
console.log(Driving a ${this.maker} ${this.model} car at ${kmh} km/h!)
}

drive.call(car, 100)
//Driving a Ford Fiesta car at 100 km/h!

drive.apply(car, [100])
//Driving a Ford Fiesta car at 100 km/h!

67
Q

Give an example of using the bind function

A

const drive = function() {
console.log(Driving a ${this.maker} ${this.model} car!)
}.bind(car)

drive()
//Driving a Ford Fiesta car!

68
Q
A