Objects Flashcards
How can can create an object and once you’ve made one, how could you edit one value of a key?
let person = { name: 'Scott', age: 18, amVirgin: true
};
person.name = ‘Scottttyyyy’;
How can you access a key’s value from an object? (2 Ways)
console.log(person.name);
or
console.log(person[name]);
What is one advantage that bracket notation has over dot?
Using bracket notation you can access variables inside the brackets to select a key from an object.
Within an object you can assign keys to strings, numbers, booleans and arrays, but how can you assign a key to a function? (Give example)
sayHello = () {
return Hello there, ${this.name}
;
}
How can we create a method/faction to operate on data inside of the same object? (Give Example)
You use the this keyword, like so:
amVirgin = () { if (!amVirgin) { return 'Gotta work on that!'; } }
You can use the this keyword in a method/function to access data within the object. What if we wanted to access the name not in my object but a different one, to log a different name to the console?
let myself = { name: 'Scott', sayHello() { return `${this.name} says hello!`; }
};
let friend = { name: 'Mohit', }; friend.sayHello = person.sayHello(); console.log(friend.sayHello())
What method can you use together within an object to update the value of a key according if new data is valid?
You an use setter methods, like so:
let person = { _age: 18,
set age(newAge) { if (typeof newAge === 'number') { this._age = newAge; console.log(`${newAge} is a valid input, age updated to ${newAge}`); } else { console.log(`${newAge} is not a valid input, please make sure to enter a number as input`); } } }; person.age = 19; console.log(person._age);