Sprint 7 Flashcards

Introduction to Object-Oriented Programming

1
Q

Encapsulation

A

Encapsulation in JavaScript is a mechanism of bundling data (attributes) and methods that operate on that data within a single unit (object).

It restricts direct access to some of the object’s components, preventing unintended modification and promoting data integrity.

This is achieved by controlling access to the internal state of an object, often using closures or conventions to define private and public members. Encapsulation helps in organizing code, managing complexity, and implementing data hiding.

TripleTen OOP Lesson and definition of Encapsulation
https://tripleten.com/trainer/web/lesson/e968713b-9ec3-4f49-b701-2898a2c1c1ac/task/4f0f0797-f0fd-416b-b78c-04c46bf75f36/?theory_open=false

*ex.

The inner workings of a program are often hidden from the outside world. We call this encapsulation. The main advantage of this is that it hides away the complexity of the device, leaving the user with a convenient and intuitive way of interacting with it.

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

Inheritance

A

In object-oriented programming, inheritance means creating a class based on another class.

  • In JavaScript, inheritance allows programmers to reuse previously written classes. We can have child classes or parent classes, also referred to as subclasses and superclasses respectively. This helps them remove excessive code duplication and makes code much easier to maintain.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Polymorphism

A

*TripleTen Definition
You’ve just seen the concept of polymorphism in action, which is the ability of objects with the same interface to have a different implementation.

Link to lesson for deeper understanding
https://tripleten.com/trainer/web/lesson/03ac1894-88e2-4436-a2f5-b31bf1de8661/task/6b15a92b-02b5-4fa2-80ca-f05428073879/

*Google definition
Polymorphism, meaning “many forms,” is a core concept in object-oriented programming (OOP) that allows objects of different types to be treated as objects of a common type. In JavaScript, polymorphism is primarily achieved through prototype inheritance and method overriding. It enables writing more flexible and maintainable code by allowing different objects to respond to the same method call in their own specific ways.

ex.
class Animal {
constructor(name) {
this.name = name;
}

speak() {
return “Generic animal sound”;
}
}

class Dog extends Animal {
speak() {
return “Woof!”;
}
}

class Cat extends Animal {
speak() {
return “Meow!”;
}
}

const animal = new Animal(“Generic Animal”);
const dog = new Dog(“Buddy”);
const cat = new Cat(“Whiskers”);

console.log(animal.speak()); // Output: Generic animal sound
console.log(dog.speak()); // Output: Woof!
console.log(cat.speak()); // Output: Meow!

const animals = [dog, cat];
animals.forEach(animal => {
console.log(animal.speak()); // Output: Woof!, Meow!
});

Note
In this example, the speak method is polymorphic. Even though we call the same method on different objects (dog and cat), they produce different outputs. This is because the Dog and Cat classes have overridden the speak method of their superclass Animal. The animals array demonstrates how different objects can be treated as a common type (Animal) and still exhibit their specific behaviors.

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

What is a Program Paradigm?

A

A programming paradigm is an approach to coding based on a coherent set of shared principles across a particular discipline.

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

According to OOP, code must comply with what requirements?

A
  1. It is represented by a set of interacting objects that make up a single structure called a program. Objects store data and have methods that enable that data to be passed from one object to another.
  2. It relies on the key OOP concepts, which are encapsulation, inheritance, and polymorphism.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is a method?

A

A method, generally speaking, is any function that’s performed on an object.

We should also take a moment to note that any function in JavaScript is a method, even if it’s declared globally.

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

What is an alert() method?

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

What is an split() method?

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

What is an indexOf() method?

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

What is an object method?

A

The behavior of an object is defined via functions, called object methods. In the code below, song.like is a method of the song object.

ex.

const song = {
title: “Circles”,
artist: “Mac Miller”,
isLiked: false,
like: function () {
song.isLiked = !song.isLiked;
}
};

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

What is an object “state”?

A

The object state includes its variables and properties, also called fields.

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

What is memory consumption?

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

What is “this”?

A

this - is a JavaScript keyword that refers to an object. The value of that object can be dependent on the context where we find “this.”

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

What is a string interpolation or template literal?

A

${}

It’s a way to embed expressions directly within a string. Instead of concatenating strings with the + operator, you can use backticks (`) to define the string and place variables or expressions inside ${}.

ex.

const name = “Alice”;
const age = 30;
const message = My name is ${name} and I am ${age} years old.;
console.log(message); // Output: My name is Alice and I am 30 years old.

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

“class” Naming Convention

A

We always write a class name in TitleCase

ex. TitleCase

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

“new” keyword

A

The new keyword need to be included whenever we create a new class instance

17
Q

constructor() function

A

Each class comes equipped with a constructor() function, which takes arguments in the (…, …).

Each time an object is created, a constructor function would automatically run it’s code and return a newly created object.

ex.

class Song {
constructor(title, artist) {
// run some code
this.artist = artist;
// return new song
this.title = title;
}
}

18
Q

What is the Prototype Chain?

19
Q

The “class” keyword

A

A class defines the data and functionality that an object will possess.

Think of it as a blueprint used to create objects. Such objects are called class instances.

Classes declare properties (data) and methods (functionality) in their objects.

20
Q

What is ES6?

A

ES6 is the sixth version of the ECMAScript specification introduced in 2015.

That’s why it’s sometimes called “ES2015”.

21
Q

What is a User Interface?

A

In programming, we can often come across the term “user interface.” When we talk about a user interface, we’re referring to the appearance of the program. This includes things like the user menu, any buttons or switches, input fields, and so on. This is what allows our users to interact with a program, and acts as the medium between the program’s code and the user.

Any complex device must have an easy-to-use interface. It’s much simpler to start a car using a key instead of popping open the hood and trying to manually start the engine yourself.

22
Q

Emulate

A

Emulation is the ability of one computer program to imitate the functionality of another program.

23
Q

Interface Principle in OOP

A

In OOP, the same principle is applied to objects. Outer objects of the interface are the public methods you can safely call in external code.

In addition to public methods, objects also have private methods and properties. The difference between these is that private methods are solely intended for the internal workings of an object.

24
Q

What does Inheritance mean in OOP?

A

In object-oriented programming, inheritance means creating a class based on another class.

  • In JavaScript, inheritance allows programmers to reuse previously written classes. We can have child classes or parent classes, also referred to as subclasses and superclasses respectively. This helps them remove excessive code duplication and makes code much easier to maintain.
25
Q

What does OOP stands for?

A

Object-Oriented Programming

26
Q

What is the “extend” keyword? What is it used for?

A

We can solve the problem of code duplication in our classes with inheritance. We can use the extends keyword to create new classes that will inherit all of the properties and methods of their parent classes:

ex.

class WebDeveloperStudent extends Student {

}

class PythonDeveloperStudent extends Student {

}

class DataAnalystStudent extends Student {

}

We’ve now created three classes of students based on their desired profession. All three classes inherit from the same parent class Student because we used the extends keyword.

Link to lesson for deeper understanding
https://tripleten.com/trainer/web/lesson/3a6da929-0860-47f0-b77e-9ed57735c073/task/9daf51b1-fd9d-4765-aa09-8ff8cc8bf3b1/

27
Q

What is the “super” keyword? What is it used for?

A

Note that in the example below, super() is called in every class constructor inherited from the Student class.

*The super keyword allows us to make a reference to the parent class that the child class inherits from.

Writing super() calls the constructor() method of the parent class. In this case, it’s the Student class.

ex.
class WebDeveloperStudent extends Student {
constructor(name, group) {
super(name, group);
this._profession = “Web developer”;
this._trainingDuration = 10;
}
}

class PythonDeveloperStudent extends Student {
constructor(name, group) {
super(name, group);
this._profession = “Python developer”;
this._trainingDuration = 9;
}
}

class DataAnalystStudent extends Student {
constructor(name, group) {
super(name, group);
this._profession = “Data analyst”;
this._trainingDuration = 6;
}
}

Link to lesson for deeper understanding
https://tripleten.com/trainer/web/lesson/3a6da929-0860-47f0-b77e-9ed57735c073/task/9daf51b1-fd9d-4765-aa09-8ff8cc8bf3b1/

28
Q

What is a Spread Operator “…”?

A

Found in Google Search
The spread operator in JavaScript is a syntax introduced in ECMAScript 6 (ES6) that allows you to spread the elements of an iterable (such as arrays, strings, or objects), into another iterable or function call. It is denoted by three dots “ … ” followed by an expression or an iterable.

Found on mdn web docs
The spread (…) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. In an object literal, the spread syntax enumerates the properties of an object and adds the key-value pairs to the object being created.

Spread syntax looks exactly like rest syntax. In a way, spread syntax is the opposite of rest syntax. Spread syntax “expands” an array into its elements, while rest syntax collects multiple elements and “condenses” them into a single element. See rest parameters and rest property.

ex.
function sum(x, y, z) {
return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(…numbers));
// Expected output: 6

console.log(sum.apply(null, numbers));
// Expected output: 6

Link to TripleTen YouTube vid example
https://youtu.be/cux_oaokPJ4?si=plA5v5rGzCv2peIw

29
Q

What does “Refactoring” mean in coding?

A

Code refactoring is the process of improving the structure and quality of existing code without changing its functionality. It’s a key skill for software developers.

Goals of refactoring
Readability: Make code easier to understand
Maintainability: Make code easier to maintain and fix
bugs
Complexity: Reduce the complexity of the code
Extensibility: Make it easier to add new features and
extensions to the code

When to refactor
After a product has been deployed
Before adding new features or updates to existing code
As part of daily programming

How to refactor
Move code between classes or objects to group related
functionality together
Restructure confusing code into simpler code
Optimize performance

Benefits of refactoring Improves the design of the code,
Reduces the chances of introducing bugs, Makes it
easier to build onto existing code, Reduces maintenance costs, and Allows the program to scale.

Refactoring vs. rewriting

Refactoring improves existing code, while rewriting starts with a new codebase.

30
Q

What does dynamically access mean in coing/js?

A

In coding, particularly in JavaScript, dynamically accessing refers to the ability to access properties of an object using a variable or expression at runtime, rather than using a fixed, hardcoded name. This provides flexibility and allows for more adaptable code.

In JavaScript, there are two primary ways to access object properties:

Dot notation: This method is used when the property name is known beforehand and is a valid identifier. For example:

ex.
JavaScript

const myObject = { name: ‘John’, age: 30 };
console.log(myObject.name); // Output: John

Square bracket notation: This method allows accessing properties using a string or a variable that evaluates to a string. This is where dynamic access comes into play. For example:

ex.
JavaScript

const myObject = { name: ‘John’, age: 30 };
const propertyName = ‘name’;
console.log(myObject[propertyName]); // Output: John

const key = “age”;
console.log(myObject[key]); // Output: 30

Dynamic access is particularly useful in scenarios such as:

Iterating over object properties: When you need to loop through the properties of an object, you can use a for…in loop and access each property dynamically.

ex.
JavaScript

const myObject = { name: ‘John’, age: 30, city: ‘New York’ };
for (const key in myObject) {
console.log(${key}: ${myObject[key]});
}
// Output:
// name: John
// age: 30
// city: New York

Handling user input or data from external sources: If you’re working with data where the structure or property names might vary, you can use dynamic access to handle it gracefully.

ex.
JavaScript

function getValue(object, key) {
return object[key];
}

const person = { name: ‘Alice’, occupation: ‘Engineer’ };
const field = ‘occupation’;

console.log(getValue(person, field)); // Output: Engineer

Creating more generic and reusable functions: By using dynamic access, you can write functions that can work with different objects and property names without needing to be modified for each specific case.

ex.
JavaScript

function updateProperty(object, key, value) {
object[key] = value;
}
const product = { id: 123, price: 25 };
updateProperty(product, ‘price’, 30);
console.log(product.price); // Output: 30

31
Q

What is “Method Overriding” in OOP (js)?

A

Method overriding is a feature of object-oriented programming that allows a subclass to redefine a method from its superclass. The overridden method has the same name, parameters, and return type as the method in the superclass.

How does it work?
A subclass inherits the actions of its superclass.

The subclass can override the inherited method by providing its own implementation.

The method in the subclass will be called instead of the method in the superclass.

Benefits of method overriding
Allows a class to inherit from a superclass with “near enough” actions and then change it as required.

Allows a subclass to use a method with the same name as in the superclass but with its own implementation.

YouTube video for more in-depth learning
https://www.youtube.com/watch?v=y-yrPdSth3g

32
Q

What is IIFE “Immediately Invoked Function Expression” in js?

A

An Immediately Invoked Function Expression (IIFE) is a JavaScript construct that executes a function as soon as it is defined. It is a design pattern that produces a lexical scope using function scoping, and it’s also known as a self-executing anonymous function. The primary use cases for IIFEs are to create private scopes for variables, preventing them from polluting the global scope, and to encapsulate code, thus avoiding naming conflicts.

Here’s the basic syntax for an IIFE:
JavaScript

ex.
(function() {
// Code inside the IIFE
})();

The function is wrapped in parentheses to create a function expression, and the trailing parentheses immediately invoke the function.

IIFEs can also accept arguments:
JavaScript
ex.
(function(name) {
console.log(“Hello, “ + name + “!”);
})(“World”);

IIFEs are useful in scenarios where you need to execute a block of code once and then discard it, such as during library or module initialization. They help maintain a clean global scope and prevent unintended side effects.

TripleTen YouTube intro for in-depth understanding
https://www.youtube.com/watch?v=K4E07naFBEA

33
Q

What are Modules in JS?

A

Google AI Overview
In JavaScript, modules are self-contained units of code that encapsulate related functionality. They promote code organization, reusability, and maintainability by allowing developers to divide code into smaller, manageable pieces. Modules can contain variables, functions, classes, or any other valid JavaScript code.
Modules are defined using the import and export keywords. The export keyword is used to make variables, functions, or classes available for use in other modules, while the import keyword is used to bring in functionality from other modules.

Here’s an example:

JavaScript
ex.
// myModule.js
export const myVariable = 10;

export function myFunction() {
console.log(“Hello from myModule!”);
}
ex.
JavaScript

// main.js
import { myVariable, myFunction } from “./myModule.js”;

console.log(myVariable); // Output: 10
myFunction(); // Output: Hello from myModule!

Triple Ten lesson for in-depth understanding
https://tripleten.com/trainer/web/lesson/72f4d5f5-ad4c-4402-8067-ef6551f5ac8c/task/dfcc3005-99a0-4739-b1d9-64ef0670d89c/

34
Q

What are the two ways to export and import JS modules?

A

The two ways to export and import JavaScript modules are “named” and “default”.

Google Search finding
You can import modules into a file in two ways, based on if they are named exports or default exports. Named exports are constructed using curly braces. Default exports are not.

Export syntax:
ex.
export const array = [1, 2, 3] — export on declaration.
export { dog, cat } — export multiple entities separate from their declaration.
export default data — export a single variable, function, or class.

Import syntax:
ex.
import { array } from “./data.js” — import using a feature’s original name.
import * — import all exports.
import { array as arr } from “./data.js” — rename feature on import.
import data from “./data.js”; — import of a default export (no curly braces needed).