Object Knowledge Flashcards
Deep Copy an object
JSON.stringify( )
then
JSON.parse( )
or
JSON.parse(JSON.stringify( ))
Delete from an object
delete myObject.myKey
delete myObject[‘myKey’]
What’s the difference between a deep copy and a shallow copy
Shallow copy- when you shallow copy an object, all you do is copy the first layer data from the heap. This includes the pointers to other objects
Deep copy- A deep copy also makes a copy of all the nested objects and points to those objects accordingly.
Add to an object
dot notation
myObject.newKey =
square bracket notation
myObject[‘newKey’] =
Change an object key’s value
dot notation
myObject.oldKey =
square bracket notation
myObject[‘oldKey’] =
Change an object key’s name
No built in method
Create an object
let myObj = { }
d
f
Shallow copy an object (1 ways)
Does it work with arrays?
1. spread syntax let newObject = { ...oldObject };
What is returned from adding an entry to an objects?
ex.
{a: 1, b: 2, c: 3}.d = 4
4
(and it adds d: 4 to the object.
Why is adding an entry to an object in this way:
{a: 1, b: 2, c: 3}.d = 4
useless?
Because there is no variable pointing to it. You can not no longer retrieve the object you’ve just changed.
What defines an object? (3 things)
- An unordered collection of data in the form of “key: value” pairs.
- JS objects have properties attached to the object.
- These keys can be variable or functions (called methods).
How do objects, functions and arrays differ?
Object-they can have properties and methods
Array- they can have properties and methods just like any other object
BUT they have an ordered collection
Function- they can have properties and methods just like any other object
BUT they can be called
let myObject = { apple: 'berry', purrple: 'tomato' }
If you want to log the values to console within a for…in statement:
for (let key in myObject) {
??????
}
How do you do it? (bracket or dot notation)
Bracket notation
for (let key in myObject) {
console.log(myObject[key]);
}
What happens if you use myObject.key instead of bracket notation?
(scroll down)
myObject.key
converts key to a string. it will return undefined for each key.
What is an object property?
a key: value pair
What is the object property name?
the key
How to:
- add and
- access
multiword object keys
Use apostrophes.
let anObject = {‘a key’ : ‘a property’}
Use bracket notation
anObject[‘a key’]
Input a variable as a key
Use bracket notation let aVariable = 'apple'; let user = { [aVariable]: 2 }
let user = { name: "John", age: 30 };
let key = prompt(“What do you want to know about the user?”, “name”);
alert( user[key] )
It does not work with dot notation
What is dot notation
What is square bracket notation
dot notation
myObject.newKey =
square bracket notation
myObject[‘newKey’] =
What is a computed property?
A key that created using the value of a variable:
let apple = 123; let myObject = { [apple] : 1234}; console.log(myObject) // { '123' : 1234 }
When to use dot vs square notation
Dot for known and simple names.
Use square when you need it.
Does this throw an error?
function makeUser(name, age) { return { name: name, age: age, }; }
No.
Dot notation keys are converted to strings. So the keys name and age, don’t register as variables.
What is property value shorthand?
When creating an object where the key name and the variable name used as the value are the same, you can:
let name = 'apple'; let anObject = { name, }
Is the same as:
let name = 'apple'; let anObject = { name: name } which gives {name: 'apple'}
Which of these have the correct spacing let anObject = {
name: ‘John’
}
or
let anObject = { name : 'John'
}
or
let anObject = { name : 'John' }
or
let anObject = {
name : ‘John’
}
let anObject = { name: 'John' }
It's acceptable to use language reserved names as object keys: let obj = { for: 1, let: 2, return: 3 }; T or F
True
They are converted to strings, and called as strings. So it doesn’t interfere with regular code function.
Numbers aren’t allow as variables, so why does this work:
let obj = { 0: "test" // same as "0": "test" };
// both alerts access the same property (the number 0 is converted to string “0”)
alert( obj[“0”] ); // test
alert( obj[0] ); // test (same property)
In the object creation, 0 is converted to a string
In this:
alert( obj[0] )
because numbers aren’t allowed as variables, 0 isn’t a potential variable. JS converts it to string (since object keys are strings)
Return Boolean based on whether a key is a part of an object (or a variable containing the key)
Why use it instead of just checking whether anObject.aKey exists?
'key' in anObject (use quotation marks or bracket notation or it won't look for a string by default) For example with a variable: let variable = 'key' variable in anObject
In case the key value is explicitly ‘undefined’
How are objects ordered…
if the keys are strings?
if the keys are numbers (as strings)?
if they are a mix of strings and numbers(as strings)?
if the keys are strings
They are ordered by creation order
if the keys are numbers (as strings)
They are ordered by number
if they are a mix of strings and numbers(as strings)?
Numbers are pushed to the beginning
If object keys are numbers, they will auto rearrange. How can you stop this?
The properties are only reordered IF they are integer properties
So you can cheat by naming the keys
“+10”
“+3”
and they will keep the order (but have a + in them)
Write a function to see if an object is empty
2 ways
function isEmpty(obj) { for (let key in obj) { // if the loop has started, there is a property return false; } return true; }
function isEmpty(array1) { return Object.keys(object).length === 0; }
What's the difference between: let apple = 9; let pear = apple; and let apple = {9}; let pear = apple;
With the primitive number, apple and pear have their own 9 value attached. Primitives are copied as whole values.
But apple and pear for the object both point to a specific instance of {9}. They are stored and copied “by reference”
let apple = {9:9}; let pear = apple;
what is returned from:
pear == apple;
Why?
True
Because the reference is the same
let apple = {9:9}; let pear = {9:9};
what is returned from:
pear == apple;
Why?
False
Because the reference is different
let apple = JSON.stringify({9:9}); let pear = JSON.stringify({9:9});
what is returned from:
pear == apple;
True
Because the string of the objects are the same
Term for using objects to represent entities
OOP
Object-oriented programming
Why use ‘this’ to refer to the object rather than just the object name?
So if the object gets copied, or the variable name changes, the references remain local and working.
You can put ‘this’ in a function and assign it to multiple objects.
What does ‘this’ refer to?
‘this’ references the object of which the function is a property
So the specific thing it references is context specific.
When a function is declared, it may have a ‘this’. But the ‘this’ has no value until the function is called.
T or F
True
Which returns true, which returns false:
function show() { console.log(this === undefined); } ---show();
—console.log(this === undefined)
"use strict"; function show() { console.log(this === undefined); } ---show();
false
false
They equal the global object / browser
true
Why?
Basically the rules the people at ECMA setup.
In browser, what does ‘this’ refer to?
In node.js, what does ‘this’ refer to?
window
global
What is logged to console
let car = { brand: 'Honda', getBrand: function () { return this.brand; } }
console.log(car.getBrand());
let brand = car.getBrand;
console.log(brand());
Honda
undefined
The method is now just a function attached to ‘brand’. So it references the global object.
What’s logged to console:
let car = { brand: 'Honda', getBrand: function () { return this.brand; } }
console.log(car.getBrand());
let brand = car.getBrand.bind(car);
console.log(brand());
Honda
Honda
Set a variable to an objects method and connect the variable’s ‘this’ to a specific object (doesn’t have to be the same object as the method)
let anObject = { aMethod() { ... } } let aFunction = anObject.aMethod.bind(anObject);
In browser what is logged to console from:
let show = () => this;
console.log(show() === window);
let show1 = () => { return this; } console.log(show1() === window);
let show1 = () => { console.log(this === window); } show1();
function show2() { return this; } console.log(show2() === window);
function show3() { console.log(this === window) } show3()
true
true
true
true
true
(because the function was not called on an object!)
What is returned from these:
let myObject = { method1: function() { return this; } } myObject.method1() == myObject Why?
let myObject2 = { method2: () => this } myObject2.method2() == myObject2 Why?
True
‘this’ refers to the object the function is a property
False
It is global.
Arrow functions do not have their own binding to ‘this’ and use the binding of their object parent. In this case, the global object.
Does ‘this’ in the arrow function refer to the global object? Why?
let user = { firstName: "Ilya", sayHi() { let arrow = () => alert(this.firstName); arrow(); } }; user.sayHi();
let user = {
arrow: () => this
};
user.arrow()
It references user. The sayHi method binds the arrow function’s this sayHi’s
Yes, it references the global object. It does not have it’s own binding unless within another function
Can you apply the bind method to arrow functions to set their ‘this’?
no
You cannot rebind this in an arrow function. It will always be defined as the context in which it was defined. If you require this to be meaningful you should use a normal function.
Create a constructor function and create a new object with it
function User(name) { this.name = name; this.isAdmin = false; }
let user = new User(“Jack”);
When a function is executed with new, it runs through the following 3 step algorithm:
1 A new empty object is created and assigned to this.
2 The function body executes. Usually it modifies this, adds new properties to it.
3 The value of this is returned (unless if an object return is defined. Primitives returns are ignored)
Any function can be run with new and it will run through the ‘new’ algorithm
T or F
T,
not arrow functions though because they don’t have a ‘this’
Within a constructor function:
What happens if you don’t have a ‘return’ operator?
What happens if you return an object?
What happens if you return a primitive?
It returns the value of ‘this’
It returns that object
The primitive is ignored and it returns the value of ‘this’
You cannot ommit the parenthesis when calling constructor functions: let user = new User; //
F
This works with constructors
Is it possible to create functions A and B so that new A() == new B()?
function A() { ... } function B() { ... }
let a = new A; let b = new B;
alert( a == b );
Yes, it’s possible.
If a function returns an object then new returns it instead of this.
So they can, for instance, return the same externally defined object obj:
let obj = {};
function A() { return obj; } function B() { return obj; }
alert( new A() == new B() ); // true
What is returned from the follow let user = { address: { street: 'af' } }; console.log(user.address.street);
let user = { address: 'fasd' }; alert(user.address.street);
let user = { }; alert(user.address.street);
‘af’
undefined
error. Trying to retrieve something from undefined.
How can you make sure this doesn’t throw an error?
let user = { }; alert(user.address.street);
(2 bad ways, 1 good way)
Question mark before each dot ?.
Can do:
alert(user.address ? user.address.street ? user.address.street.name : null : null);
alert( user.address && user.address.street && user.address.street.name );
OR
Use optional chaining: (it’s not an operator)
alert( user?.address?.street );
or with bracket notation
user?.[‘address’]?.[‘street’]
What does ? do in
alert( user?.address?.street );
?
It returns undefined if the preceeding key is called on undefined or null
What does ? do in
alert( user?.address.street );
?
It returns undefined if user returns undefined or null
When should you use optional chaining?
Only when it’s ok to have something not exist. Otherwise, you want the error.
What happens with
alert( user?.address.street );
if there’s no user variable?
Throws an error.
There is no user variable. A non-existent variable name is not “undefined”.
How can you use optional chaining to short circuit to stop the evaluation.
let user = null; let x = 0;
user?.sayHi(x++); // no “sayHi”, so the execution doesn’t reach x++
alert(x); // 0, value not incremented
What happens with:
let userGuest = {};
userGuest.admin();
Throws an error
userGuest.admin is not a function
How can you make the following not throw an error:
let userGuest = {};
userGuest.admin();
with ?.()
userGuest.admin?.();
What happens with this if user doesn't exist? let user = {} delete user.name.apple; delete user?.name.apple; delete user?.name?.apple;
error
error
returns true
What happens with:
console.log(console.log(‘fad’));
Why?
fad
undefined
Lines of code passed as arguments are run.
What is returned from:
{p: 1} + {q: 2}
[object Object][object Object]
Boolean( { } )
True
Write a method that makes an object return specific things when converted to primitives (2 ways)
1. [Symbol.toPrimitive](hint) let user = { name: "John", money: 1000,
[Symbol.toPrimitive](hint) { alert(`hint: ${hint}`); return hint == "string" ? `{name: "${this.name}"}` : this.money; } };
// conversions demo: alert(user); // hint: string -> {name: "John"} alert(+user); // hint: number -> 1000 alert(user + 500); // hint: default -> 1500
- toString() and valueOf()
let user = {
name: “John”,
money: 1000,
// for hint="string" toString() { return `{name: "${this.name}"}`; },
// for hint="number" or "default" valueOf() { return this.money; }
};
alert( String(user) ); // toString -> {name: “John”}
alert( +user ); // valueOf -> 1000
alert( user + 500 ); // valueOf -> 1500
What can you use this for:
Symbol.toPrimitive {
}
Allows you to return specific primitives based on whether the object is converted to specific primitives.
Can return anything but it has to be primitive.
When the object is converted, strings of “string”, “default” or “number” are passed as arguments under hint.
let user = {
name: “John”,
money: 1000,
[Symbol.toPrimitive](hint) { alert(`hint: ${hint}`); return hint == "string" ? `{name: "${this.name}"}` : this.money; } };
// conversions demo: alert(String(user)); // hint: string -> {name: "John"} alert(+user); // hint: number -> 1000 alert(user + 500); // hint: default -> 1500
What is logged to console from:
let user = {
name: “John”,
money: 1000,
[Symbol.toPrimitive](hint) { alert(`hint: ${hint}`); return hint == "string" ? `apples` : 123; } };
alert(String(user));
alert(user.toString());
‘apples’
[object Object]
What's the difference between: forEach for for in for of
Which is best for arrays?
The forEach() method executes a provided function once for each array element.
for is just a generic looper and can be used for anything
for of is made for arrays and is faster (just works with values, not numbers or keys but is usually better)
for in can be used with arrays. (the key being the number for (let key in arr) {
alert( arr[key] ); // Apple, Orange, Pear
}
For of is probably the best. For in will run over all properties, not just numbered values. It’s also like 10-100 times slower for arrays.
Truncate an array with the length property.
array.length = 2;
Why do we usually use arr = [] rather than let arr = New Array(0) (2 reasons)
It’s easier and shorter
Creating a new array with only a number as the argument will create a new array with that number as the length.
How will this: let apple = {a:1};
function B() { this.aa= 'aa'; return apple; } Differ from this: let apple = {a:1}; function B() { this.aa= 'aa'; }
when constructing an object.
In the first case, this.aa is overwritten. The constructed object will be apple references.
Can you use a function to create an object key?
Yes.
myobj.[aFunction()]
The return of the function becomes the key.