Properties Flashcards
In the following, what do we call ‘surname’ and ‘age’?
let sherlock = { surname: 'Holmes', age: 64, };
Properties!
Here, sherlock is still a variable, but surname and age are not. They are properties. Unlike variables, properties belong to a particular object.
Note: properties don’t contain values—they point to them
Do variables and properties look the same in our mental model?
In our JavaScript universe, both variables and properties act like “wires.”
However, the wires of properties start from objects rather than from our code.
Remember that our universe is full of wires. Some of them start from our code (variables), and others start from objects (properties). All wires always point to values.
Do values live inside objects?
Nope! They are just wired to objects - the values themselves float outside.
What’s are two important restriction about properties?
- A single object can’t have two properties with the same name
- Property names are also always case-sensitive
How does JS check if an object has X property?
JavaScript uses a set of rules that looks something like this:
Figure out the value of the part before the dot (.).
If that value is null or undefined, throw an error immediately:
“Uncaught TypeError: Cannot read properties of undefined”
Check whether a property with that name exists on our object:
a. If it exists, answer with the value this property points to.
b. If it doesn’t exist, answer with the undefined value.
What will this give:
x.poop
// Type error - cant access property on undefined
What will this give:
x = {}
x.poop
// undefined
Given:
x = {}
x.poop // undefined
Does our mental model hold that x has a property called poop wired to undefined?
Nope! Its just a law of the universe that accessing non existent properties on objects evaluates to undefined
Is the following valid and self-referring?
const president = {
name: “pooh:”,
next: president,
}
Nope! Objects can’t refer to their won assignments like this.
Assignment happens in three steps: (1) find the wire on the left, (2) find the value on the right, (3) point the wire to that value.
By the time we create the { next: president } object (step 2), we haven’t yet pointed president variable anywhere (step 3), so we can’t use it yet!
So instead, we create our object and assign it to the president variable first. Then, we point the next property wire from that object to itself.
let president = { name: 'Pooh' }; president.next = president;