Javascript (OOP) Flashcards
4 pillars of object-oriented programming
Encapsulation
Abstraction
Inheritance
Polymorphism
Encapsulation in OOP
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.
Abstraction in OOP
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.
Inheritance in OOP
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.
Polymorphism in OOP
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.
Objects in JS
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.
Object Literals
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
What do we fill the objects with?
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.
key-value pairs
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.
key (key-value pairs)
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 do we make a key-value pair in JS?
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. */
Name two ways to access object properties in JS
- Dot notation
- Bracket notation
Dot notation to access object properties
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’,
Bracket notation to access object properties
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:
Differences between dot notation and bracket notation to access object properties
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.
Restrictions in Naming Properties
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.
}
Properties and values of a JavaScript object
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
}
Explain mutability of JS objects
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.
Property (re)assignment in JS objects
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’
Delete operator
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”
}
*/
Object methods
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…
*/
What is the difference between object property and method?
A property is what an object has, while a method is what an object does.
How do we access nested properties of an object?
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’
What does it mean when we say that JS objects are passed by reference?
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);
JS for…in loop
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”
Why do we have to use a for … in loop to iterate over the keys of an object?
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.
this Keyword
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.