JS Objects Flashcards

1
Q

What is JavaScript Objects?

A

Object is an unordered collection of key-value pairs. Each key-value pair is called a property
The key of a property can be a string. And the value of a property can be any value.
They are called properties and methods when they are inside objects

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

How create an object ?

A

let empty = {};

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

How create an object and use the object literal??

A

const person = {
name: [“Bob”, “Smith”],
age: 32,
bio() {
console.log(${this.name[0]} ${this.name[1]} is ${this.age} years old.);
},
introduceSelf() {
console.log(Hi! I'm ${this.name[0]}.);
},
};

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

How create an object with properties?

A

To create an object with properties, you use the key:value within the curly braces

let person = {
firstName: ‘John’,
lastName: ‘Doe’
};

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

How accessing properties to obj ?

A

To access a property of an object, you use one of two notations:
-the dot notation
- array-like notation.

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

The dot notation (.)

A

let person = {
firstName: ‘John’,
lastName: ‘Doe’
};

console.log(person.firstName);
console.log(person.lastName);

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

Array-like notation ( []) Bracket notation

A

let person = {
firstName: ‘John’,
lastName: ‘Doe’
};

console.log(person[‘firstName’]);
console.log(person[‘lastName’]);

const myDataName = “height”;
const myDataValue = “1.75m”;
person[myDataName] = myDataValue;

person.height; //1.75m

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

When a property name contains spaces:

let address = {
‘building no’: 3960,
street: ‘North 1st street’,
state: ‘CA’,
country: ‘USA’
};

A

address[‘building no’];

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

Modifying the value of a property

let person = {
firstName: ‘John’,
lastName: ‘Doe’
};

A

change the value of a property, you use the assignment operator (=)
person.firstName = ‘Jane’;

console.log(person);

{ firstName: ‘Jane’, lastName: ‘Doe’ }

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

Adding a new property to an object

let person = {
firstName: ‘John’,
lastName: ‘Doe’
};

A

person.age = 25

{ firstName: ‘John’, lastName: ‘Doe’, age: 23 }

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

What is objects as object properties

A

const person = {
name: {
first: “Bob”,
last: “Smith”,
},
};

to call properties :
person.name.first;

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

Deleting a property of an object

A

delete person.age
{ firstName: ‘John’, lastName: ‘Doe’ }

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

Checking if a property exists
let employee = {
firstName: ‘Peter’,
lastName: ‘Doe’,
employeeId: 1
};

console.log(‘ssn’ in employee); //false
console.log(‘employeeId’ in employee); //true

A

check if a property exists in an object, you use the in operator
console.log(‘ssn’ in employee);
false
console.log(‘employeeId’ in employee);
true

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

JavaScript objects properties?

A

JavaScript objects have two types of properties: data properties and accessor properties.

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

Pass-by-value primitives values?
What is a result?
function square(x) {
x = x * x;
return x;
}

let y = 10;
let result = square(y);

console.log(result);
console.log(y);

A

In JS, all function arguments are always passed by value.
Any changes that you make to the arguments inside the function do not reflect the passing variables outside of the function
console.log(result); // 100
console.log(y); // 10 – no change

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

Pass-by-value of reference values? What is a result?

let person = {
name: ‘John’,
age: 25,
};

function increaseAge(obj) {
obj.age += 1;
obj = { name: ‘Jane’, age: 22 };
}

increaseAge(person);

console.log(person);

A

JavaScript passes an object by reference because the change to the object is reflected outside the function
JavaScript passes all arguments to a function by values.
Function arguments are local variables in JavaScript.
console.log(person); //{ name: ‘John’, age: 26 }

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

Define methods of an object using the object literal.

A

JavaScript allows you to define methods of an object using the object literal syntax:
let person = {
firstName: ‘John’,
lastName: ‘Doe’,
greet() {
console.log(‘Hello, World!’);
}
};

person.greet();

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

How to use “this value” in methods in object?

A

Inside a method, the this value references the object that invokes the method:
let person = {
firstName: ‘John’,
lastName: ‘Doe’,
greet: function () {
console.log(‘Hello, World!’);
},
getFullName: function () {
return this.firstName + ‘ ‘ + this.lastName;
}
};

console.log(person.getFullName()); //’John Doe’

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

If you create more than one object, can you use ‘this’ the same method definition for every object you create?

A

Yes. This is useful for writing out object literals , not for consructors
const person1 = {
name: “Chris”,
introduceSelf() {
console.log(Hi! I'm ${this.name}.);
},
};

const person2 = {
name: “Deepti”,
introduceSelf() {
console.log(Hi! I'm ${this.name}.);
},
};

20
Q

create function whit ‘this’?

A

Way to define the “shape” of an object — the set of methods and the properties it can have — and then create as many objects as we like, just updating the values for the properties that are different.

The first version of this is just a function /:
function createPerson(name) {
const obj = {};
obj.name = name;
obj.introduceSelf = function () {
console.log(Hi! I'm ${this.name}.);
};
return obj;
}
This function creates and returns a new object each time we call it. The object will have two members:

a property name
a method introduceSelf().
const salva = createPerson(“Salva”);
salva.name;
salva.introduceSelf();

const frankie = createPerson(“Frankie”);
frankie.name;
frankie.introduceSelf();

21
Q

Constructors ?

A

Constructors, by convention, start with a capital letter and are named for the type of object they create.

function Person(name) {
this.name = name;
this.introduceSelf = function () {
console.log(Hi! I'm ${this.name}.);
};
}
const salva = new Person(“Salva”);
salva.name;
salva.introduceSelf();

const frankie = new Person(“Frankie”);
frankie.name;
frankie.introduceSelf();

22
Q

What is Prototypes?

A

Prototypes are the mechanism by which JavaScript objects inherit features from one another. Prototype object chains allow objects to inherit features from one another, the prototype property and how it can be used to add methods to constructors

23
Q

What is standard way to access an object’s prototype?

A

bject.getPrototypeOf() method
So when we call myObject.toString(), the browser:

looks for toString in myObject
can’t find it there, so looks in the prototype object of myObject for toString
finds it there, and calls it.

24
Q

What is the prototype for myObject?

A

This is an object called Object.prototype, and it is the most basic prototype, that all objects have by default. The prototype of Object.prototype is null. The prototype of an object is not always Object.prototype

25
Q

Shadowing properties

A

const myDate = new Date(1999, 10, 21)
console.log(myDate.getYear()); //

myDate.getYear = function() {
console.log(‘New Year’);
}
console.log(myDate.getYear()); //New Year

When we call getYear() the browser first looks in myDate for a property with that name, and only checks the prototype if myDate does not define it. So when we add getYear() to myDate, then the version in myDate is called.
This is called “shadowing” the property.

26
Q

Setting a prototype

A
  • Object.create()
  • constructors
27
Q

Setting a prototype whit Object.create

A

The Object.create() method creates a new object and allows you to specify an object that will be used as the new object’s prototype.
const newPrototype = {
greet(){
console.log(‘Great day’);
}
}

const leo = Object.create(newPrototype)

console.log(leo.greet());

28
Q

Setting a prototype whit constuctor

A

In JavaScript, all functions have a property named prototype. When you call a function as a constructor, this property is set as the prototype of the newly constructed object (by convention, in the property named __proto__).

const newPrototype1 = {
greet(){
console.log(Hello my name is ${this.name});
}
}
function Person(name){
this.name = name
}
Object.assign(Person.prototype, newPrototype1)
// or
Person.prototype.greet = newPrototype1.greet

const call = new Person(‘Call’)
console.log(call.greet());

29
Q

Own properties

A

The objects we create using the Person constructor above have two properties:

a name property, which is set in the constructor, so it appears directly on Person objects
a greet() method, which is set in the prototype.
Properties that are defined directly in the object, like name here, are called own properties, and you can check whether a property is an own property using the static Object.hasOwn() method:

const leo = new Person(‘Leo’)

console.log(Object.hasOwn(leo, ‘name’)); //true
console.log(Object.hasOwn(leo, ‘greet’)); //false

Can also use the non-static Object.hasOwnProperty() method here, but we recommend that you use Object.hasOwn() if you can.

30
Q

Prototypes and inheritance

A

Prototypes making possible to reuse code and combine objects. They support a version of inheritance. Inheritance is a feature of OOP languages and Professor and Student objects can have Person prototypes, then they can inherit the common properties, while adding and redefining those properties which need to differ

31
Q

What is OOP?

A

Object-oriented programming is about modeling a system as a collection of objects, where each object represents some particular aspect of the system. Objects contain both functions (or methods) and data. An object provides a public interface to other code that wants to use it but maintains its own private, internal state; other parts of the system don’t have to care about what is going on inside the object.

32
Q

Classes ?

A

When we model a problem in terms of objects in OOP, we create abstract definitions representing the types of objects we want to have in our system.
class Person {
constructor(name){
this.name = name;
}
getName(){
return this.name
}
}
let Lia = new Person(‘Lia 1’)
let name = Lia.getName()
console.log(Lia.getName()); //Lia 1
console.log(name); //Lia 1

33
Q

Classes??

A

class is: a kind of template for creating concrete objects of that type. The process of creating an instance is performed by a special function called a constructor. We pass values to the constructor for any internal state that we want to initialize in the new instance
class Professor {
constructor(name, teacher){
this.name = name;
this.teacher = teacher
}
grade(paper){

}
introduceSelf(){
  console.log(`My name is Professor ${this.name} and I will be your ${this.teacher} professor.`);
}

}

let acho = new Professor(‘Acho’, ‘Programing’)

acho.introduceSelf() //My name is Professor Acho and I will be your Programing professor.

34
Q

What is Inheritance ?

A

inheritance in ES6. The class to be extended is called a base class or parent class. The class that extends the base class or parent class is called the derived class or child class.
Call the super(arguments) in the child class’s constructor to invoke the parent class’s constructor.
Use super keyword to call methods of the parent class in the methods of the child class.
the Person is the superclass or parent class of both Professor and Student. Conversely, Professor and Student are subclasses or child classes of Person.
introduceSelf() is defined in all three classes- reason for this is that while all people want to introduce themselves, the way they do so is different:
class Person {
constructor(name) {
this.name = name;
}
introduceSelf() {
console.log(My name is ${this.name});
}
}

let leo = new Person(“Leo”);
console.log(leo.introduceSelf()); //My name is Leo

class Professor extends Person {
constructor( name, teacher) {
super(name);
this.teacher=teacher;
}
introduceSelf() {
console.log(
My name is Professor ${this.name} and I will be your ${this.teacher} professor.
);
}
}

let lia = new Professor(‘Lia’, ‘Space’)
console.log(lia.introduceSelf()); //My name is Professor Lia and I will be your Space professor.

class Students extends Professor {
constructor(name, year){
super(name)
this.year = year;
}
introduceSelf(){
console.log(My name is ${this.name} and I'm in the ${this.year} year.)
}
}

let lia1 = new Students(‘Lia1’, 3)
console.log(lia1.introduceSelf()); //My name is Lia1 and I’m in the 3 year.

35
Q

What is Polymorphism?

A

When a method has the same name but a different implementation in different classes - is called polymorphism. When a method in a subclass replaces the superclass’s implementation, we say that the subclass overrides the version in the superclass.

36
Q

What is Queue?

A

class Queue extends Array {
enqueue(e){
super.push(e);
}
dequeue(){
return super.shift();
}
peek(){
return !this.empty() ? this[0] : undefined
}
empty() {
return this.length === 0;
}
}

let customers = new Queue()
customers.enqueue(‘Lia1’)
customers.enqueue(‘Lia12’)
customers.enqueue(‘Lia13’)
customers.enqueue(‘Lia14’)

console.log(customers); //Queue(4) [ ‘Lia1’, ‘Lia12’, ‘Lia13’, ‘Lia14’ ]

while (!customers.empty()) {
console.log(customers.dequeue());
}
console.log(customers); //Lia1 Lia12 Lia13 Lia14 Queue(0) []

37
Q

What is Encapsulation in JavaScript?

A

The JavaScript Encapsulation is a process of binding the data with the functions acting on that data. It allows us to control the data and validate it. To achieve an encapsulation in JavaScript: -

Use let keyword to make data members private.
Use setter methods to set the data and getter methods to get that data.
The encapsulation allows us to handle an object using the following properties:

Read/Write - Here, we use setter methods to write the data and getter methods read that data.

Read Only - In this case, we use getter methods only.

Write Only - In this case, we use setter methods only.

38
Q

JavaScript Encapsulation

A

class Student {
constructor(){
let name;
let marks;
}

getName(){
return this.name
}
setName(name){
this.name=name
}
getMarks(){
return this.marks;
}
setMarks(marks){
this.marks=marks
}
}

let student = new Student()
student.setName(‘Lia’)
student.setMarks(100)
console.log(${student.getName()} ${student.getMarks()}); //Lia 100

39
Q

JavaScript Encapsulation , Validate

A

class Student {
constructor(){
let name;
let marks;
}

getName(){
return this.name
}
setName(name){
this.name=name
}
getMarks(){
return this.marks;
}
setMarks(marks){
(marks<0 || marks > 100) ? console.log(‘Invalid Marks’) : this.marks=marks
}
}

let student = new Student()
student.setName(‘Lia’)
student.setMarks(110)
console.log(${student.getName()} ${student.getMarks()}); //Invalid Marks Lia undefined

40
Q

Have difference between class-based OOP, classes and objects?

A

in class-based OOP, classes and objects are two separate constructs, and objects are always created as instances of classes. Also, there is a distinction between the feature used to define a class (the class syntax itself) and the feature used to instantiate an object (a constructor). In JavaScript, we can and often do create objects without any separate class definition, either using a function or an object literal. This can make working with objects much more lightweight than it is in classical OOP.

41
Q

Can constructors and prototypes can be used to implement class-based OOP patterns in JavaScript?

A

Constructors and prototypes can be used to implement class-based OOP patterns in JavaScript. But using them directly to implement features like inheritance is tricky, so JavaScript provides extra features, layered on top of the prototype model, that map more directly to the concepts of class-based OOP.

42
Q

Classes in JavaScript?

A

class Person {
constructor(name) {
this.name = name;
}
introduceSelf() {
console.log(Hello i am ${this.name});
}
}
This declares a class called Person, with:

a name property.
a constructor that takes a name parameter that is used to initialize the new object’s name property
an introduceSelf() method that can refer to the object’s properties using this.
The name; declaration is optional: you could omit it, and the line this.name = name; in the constructor will create the name property before initializing it. However, listing properties explicitly in the class declaration might make it easier for people reading your code to see which properties are part of this class.
The constructor is defined using the constructor keyword. Just like a constructor outside a class definition, it will:

create a new object
bind this to the new object, so you can refer to this in your constructor code

const girl = new Person(‘Lia3’)
girl.introduceSelf() //Hello i am Lia3

43
Q

What is Omitting constructors?

A

If you don’t need to do any special initialization, you can omit the constructor, and a default constructor will be generated for you.

class Animal {
sleep(){
console.log(‘sh sh sh sh sh sh’);
}
}

const cat = new Animal()
cat.sleep() //sh sh sh sh sh sh

44
Q

What is Inheritance in Classes?

A

class Professor extends Person{
constructor(name, teacher){
super(name);
this.teacher = teacher;
}

introduceSelf(){
console.log(My name is ${this.name} and I will be your ${this.teacher} professor.);
}

grade(paper){
const grade = Math.floor(Math.random()*(5-1) + 1)
console.log(grade);
}
}
We use the extends keyword to say that this class inherits from another class.
The Professor class adds a new property teaches, so we declare that.
constructor does is call the superclass constructor using super(), passing up the name parameter. The superclass constructor takes care of setting name. After that, the Professor constructor sets the teaches property.
overridden the introduceSelf() method from the superclass, and added a new method grade()

const vily = new Professor(‘Vily’, ‘History’)
vily.introduceSelf() //My name is Vily and I will be your history professor.
vily.grade() //2

45
Q

What is Encapsulation in Classes?

A

class Person {
constructor(name) {
this.name = name;
}
introduceSelf() {
console.log(Hello i am ${this.name});
}
}

class Student extends Person {
#year;

constructor(name, year){
super(name);
this.#year=year;
}

introduceSelf(){
console.log(Hi i am ${this.name}, an i am in year ${this.#year}. );
}

canStudy(){
(this.#year > 1) ? console.log(‘yes’) :console.log(‘no’)
}
}
const lia5 = new Student(‘Lia5’, 2)
lia5.introduceSelf() //Hi i am Lia5, an i am in year 2.
lia5.canStudy() //yes

In this class declaration, #year is a private data property. We can construct a Student object, and it can use #year internally, but if code outside the object tries to access #year the browser throws an error:

46
Q

What is Private Methods in Classes?

A

You can have private methods as well as private data properties. Just like private data properties, their names start with #, and they can only be called by the object’s own methods:

class Example{
somePublicMethod() {
this.#somePrivateMethod()
}

#somePrivateMethod(){
console.log(‘You call me?’);
}
}

const oneExample = new Example() //You call me?
oneExample.somePublicMethod()
// oneExample.#somePrivateMethod() //SyntaxError: Private field