JavaScript Objects Flashcards
How do you create a JS object?
let user = new Object(); // "object constructor" syntax let user = {}; // "object literal" syntax
How do you remove an attribute from an object?
With “delete”
delete user.age;
Can you use mutliword property names for objects?
Yes, but they must be quoted:
let user = { name: "John", age: 30, "likes birds": true // multiword property name must be quoted };
How do you access multiword properties?
With square notation:
user[“likes birds”]
What is the result of the following code?
let fruit = ‘Apple’
let bag = { [fruit]: 5, };
alert( bag.apple );
5
What is the value of “bag”?
let fruit = 'apple'; let bag = { [fruit + 'Computers']: 5 };
{
appleComputers: 5
}
What is printed?
let obj = { for: 1, let: 2, return: 3 };
alert( obj.for + obj.let + obj.return );
6
What values can be used as object property names?
Basically, any name is allowed, but there’s a special one: “__proto__” that gets special treatment for historical reasons.
What is the result of the following?
let name=0; let age = 0; return { name, age };
{
name: 0,
age: 0
}
How can you verify if a property exist in an object?
With the “in” operator.
“key” in obj // true if it exists
What will the second alert print?
let obj = { test: undefined }; alert( obj.test ); // it's undefined, so - no such property? alert( "test" in obj );
true
The property obj.test technically exists. So the in operator works right.
How do you iterate through all the keys in an object using a “for” statement
With “for .. in”
Are the properties in an object ordered when accessing them with a “for .. in” loop?
Yes, they are “ordered in a special fashion”: integer properties are sorted, the all others appear in creation order.
What will the alert print?
let user = { name: 'John' }; let admin = user; admin.name = 'Pete'; alert(user.name);
‘Pete’,
the property was updated by the “admin” reference but changes are seen from the “user” reference and both point to the same object
What will the two alerts print?
let a = {}; let b = a; // copy the reference
alert( a == b );
alert( a === b );
true and true
both variables reference the same object
When comparing two objects, what is the difference between == and ===?
Nothing, both work exactly the same
What will happen with the following constant-declared object?
const user = { name: "John" };
user.age = 25;
alert(user.age);
The alert will print 25.
Constant-defined objects can change their property values. What cannot change is the value of “user” itself
What will happen with the following constant-declared object?
const user = { name: "John" };
// Error (can't reassign user) user = { name: "Pete" };
An error will be thrown. Can’t reassign constant variables
How can you create the copy of an object?
By copying each property, one by one, to a new object, or by using Object.assign().
What does “deep clone” an object mean?
Copying an object, making sure that if one or many properties are objects themselves, those objects are also cloned
What does “Object.assign”
It takes multiple objects as parameters and returns a new object which contains all the cloned properties of the parameters
How is memory managed (allocated and freed) in JavaScript
Memory is allocated in the heap and it’s freed by the Garbage Collector
When is memory freed in JavaScript?
When objects are not reachable, they are marked by the Garbage Collector for deletion.
When is an object considered “unreachable”?
When there are no variables with references pointing tot he object
What is an internal algorithm used by the Garbage Collector in JavaScript?
It’s mark-and-sweep
How does “mark-and-sweep” word?
The garbage collector takes roots and “marks” (remembers) them.
Then it visits and “marks” all references from them.
Then it visits marked objects and marks their references. All visited objects are remembered, so as not to visit the same object twice in the future.
…And so on until every reachable (from the roots) references are visited.
All objects except marked ones are removed.
What are some optimizations done for the Garbage Collector to not affect execution?
Generational collection, incremental collection and idle-time collection
What is “general collection” in the Garbage Collector?
Objects are split into two sets: “new ones” and “old ones”. Many objects appear, do their job and die fast, they can be cleaned up aggressively. Those that survive for long enough, become “old” and are examined less often.
What is “incremental collection” in the Garbage Collector?
If there are many objects, and we try to walk and mark the whole object set at once, it may take some time and introduce visible delays in the execution. So the engine tries to split the garbage collection into pieces. Then the pieces are executed one by one, separately. That requires some extra bookkeeping between them to track changes, but we have many tiny delays instead of a big one.
What is “idle-time” in the Garbage Collector?
The garbage collector tries to run only while the CPU is idle, to reduce the possible effect on the execution.
How can you force running the Garbage Collector
It cannot be forced
How can you prevent the Garbage Collector from running?
It cannot be prevented
What are Symbols?
A “symbol” represents a unique identifier. A value of this type can be created using Symbol()
How can you add a description to a Symbol and what is that description for?
The description can be passed as a string to the constructor:
let id = Symbol(“id”);
It’s mostly used for debugging purposes
What will the alert print?
let id1 = Symbol("id"); let id2 = Symbol("id");
alert(id1 == id2);
false
Even if they have the same description, both symbols are different
What will the alert print?
let id = Symbol("id"); alert(id);
An error will be thrown
TypeError: Cannot convert a Symbol value to a string
How can you convert a Symbol into a String?
Using “toString”
let id = Symbol("id"); alert(id.toString()); // Symbol(id), now it works
Or get symbol.description property to show the description only
What are Symbols used for?
Symbols allow us to create “hidden” properties of an object, that no other part of code can accidentally access or overwrite.
For instance, if we’re working with user objects, that belong to a third-party code.
What’s the benefit of using Symbol(“id”) over a string “id”?
A symbol cannot be accessed or overriden accidentally: If third-party tries to set Symbol(“id”), there will be no conflict between our and their identifiers, because symbols are always different, even if they have the same name.
Are Symbols included in “for .. in” loops?
No, symbolic properties do not participate in for..in loop.
Are Symbols included in Object.keys(user)?
No, symbolic properties are not included
Are Symbols copied with Object.assign?
Yes, Object.assign copies both string and symbol properties:
What will the following alerts print?
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)
Both print “test”.
We can only use strings or symbols as keys in objects. Other types are converted to strings.
For instance, a number 0 becomes a string “0” when used as a property key:
Can you retrieve an existing Symbol?
Yes, you can retrieve it from the Symbol Registry
What does Symbol.for(key) do?
In order to read (create if absent) a symbol from the registry, use Symbol.for(key).
What does Symbol.keyFor do?
The Symbol.keyFor internally uses the global symbol registry to look up the key for the symbol.
What will Symbol.keyFor return if the parameter is not a symbol or the symbol is not global?
Symbol.keyFor will return undefined.
How can you retrieve the description of a Symbol
With the “description” property
Mention 4 well known symbols
Symbol.hasInstance
Symbol.isConcatSpreadable
Symbol.iterator
Symbol.toPrimitive
What is a method?
A function that is the property of an object is called its method.
What will the alert print?
let user = {
name: “John”,
age: 30,
sayHi() { alert(this.name); } }; user.sayHi();
“John”
“this” points to user
What will the alert print?
let user = {
name: “John”,
age: 30,
sayHi() {
alert(user.name);
}
};
“John”
user.name is the same as this.name, inside “sayHi”
What will the alert print?
let user = {
name: “John”,
age: 30,
sayHi() {
alert( user.name );
}
};
let admin = user; user = null; admin.sayHi();
An error is thrown as “user” now points to null.
When is “this” evaluated?
The value for “this” is evaluated during run-time
Can a function have different values for “this”?
The value of this is evaluated during the run-time, depending on the context.
If the same function is assigned to two different objects it has different “this” values in the calls.
What will the alert print in strict mode?
function sayHi() {
alert(this);
}
sayHi();
undefined
What will the alert print in non-strict mode?
function sayHi() {
alert(this);
}
sayHi();
the global object (window in a browser)
What will the alert print?
let user = { name: "John", hi() { alert(this.name); }, bye() { alert("Bye"); } };
(user.name == “John” ? user.hi : user.bye)();
An error is thrown.
The value of “this” inside the call becomes undefined.
What is the difference between in values for “this” in
let hi = user.hi; hi();
and
user.hi()
For the first one, “this” inside hi() is undefined. The second “this” will point to user.
Why is “this” undefined in
let hi = user.hi; hi();
but not in
user.hi()
To make user.hi() calls work, JavaScript uses a trick – the dot ‘.’ returns not a function, but a value of the special Reference Type.
When parentheses () are called on the Reference Type, they receive the full information about the object and its method, and can set the right this (=user in this case).
What is the value of “this” for arrow functions?
Arrow functions are special: they don’t have their “own” this. If we reference this from such a function, it’s taken from the outer “normal” function.
How can objects be converted to primitives?
Yes, by implementing ob[Symbol.toPrimitive]:
obj[Symbol.toPrimitive] = function(hint) { // must return a primitive value };
For the “Symbol.toPrimitive” function, what are valid values for the hints?
one of “string”, “number”, “default”
For the “Symbol.toPrimitive” function, what does the “default” hint indicates?
For cases when the operator is “not sure” what type to expect.
For instance, binary plus + can work both with strings (concatenates them) and numbers (adds them), so both strings and numbers would do. So if the a binary plus gets an object as an argument, it uses the “default” hint to convert it.
What is the difference between “toPrimitive” and “toString”
If “toPrimitive” is not implemented:
if hint is “string” try obj.toString() and obj.valueOf(), whatever exists.
Otherwise if hint is “number” or “default” try obj.valueOf() and obj.toString(), whatever exists.
What happens if toString or valueOf returns an object?
It’s ignored (same as if there were no method).
If not implemented for an object, what does “toString” return?
“[object Object]”
If not implemented for an object, what does “valueOf” return?
The object itself
Does the “Symbol.toPrimitive” function have to return the hinted type?
No, it doesn’t
What data types can be returned from “Symbol.toPrimitive”?
Anything, as long as its a primitive
What happens if you try to return an object from “Symbol.toPrimitive”?
An error is thrown
What are the requirements for object constructors?
They are named with capital letter first.
They should be executed only with “new” operator.