how can i get age from this keyword? - javascript

const meDetails = {
firstName: 'arman',
lastName: 'soltani',
birthday: 1991,
hasDriverLicense: true,
calcAge: function () {
this.age = 2037 - this.birthday;
return this.age;
}
};
console.log(meDetails.age);
why the age is not defined??

the variable of named 'age' is not initialized before calling calcAge.
at first you should call calcAge to init meDetailes.age variable at runtime
then meDetails.age is valued and you can use it

You need to call calcAge() first to set the age property
meDetails.calcAge();
console.log(meDetails.age);
But you probably want a getter for age.
const meDetails = {
firstName: 'arman',
lastName: 'soltani',
birthday: 1991,
hasDriverLicense: true,
get age() {
return 2037 - this.birthday;
}
};
console.log(meDetails.age);

Related

why can't i assign one object's property to another property?

what could i do to assign the value of firstName's property to lastName's?
const user = {
firstName: "Someone",
lastName: this.firstName,
};
console.log(user.lastName);
// outputs undefined
Using a getter:
const user = {
firstName: "Someone",
get lastName() { return this.firstName; }
};
console.log(user.lastName);

Why is the object property returning 'undefined?'

Here is my code:
jack = {
name: 'Jack',
birthYear: 1992,
calcAge: function () {
this.age = 2021 - this.birthYear;
return this.age;
}
};
console.log(jack.age);
Calling 'jack.age' returns 'undefined' in the console. Why is it not returning the result of the
expression in the function?
As mentioned by #Pointy you have not defined the age property in your object, for that you have created a function called calcAge if you don't call it then the property would be undefined which is what is returned.
If you call the calcAge function then age property would be defined and you can access it through the object.
You don't need to return age property from calcAge you can directly access it from the object if you want to recalculate the age property again then you can again call the calcAge function.
jack = {
name: 'Jack',
birthYear: 1992,
calcAge: function () {
this.age = 2021 - this.birthYear;
}
};
jack.calcAge();
console.log(jack.age);

Shorthand for picking object properties - combine ES6 `Object Deconstruction` with `Object Property Value` shorthand

Following code outputs {name: "Bob", surname: "Smith"} and it works fine. I want to know can I make it shorter.
((person = { name: 'Bob', surname: 'Smith', age: 22, }) => {
const {
name, // (a) create variable from deconstructing
surname,
} = person;
return {
name, // (b) reuse variable as new object parameter name (and value)
surname
}
})();
Can I somehow merge object deconstruction to variables (a) with returning a new object with Object Property Value shorthand (b)?
I use here shorthand but then its purpose is defeated by the need to manually re-use parameters. I want to mention the name or surname word in my function once not twice...
Destructure person in the function's declaration:
const result = (({ name, surname } = { name: 'Bob', surname: 'Smith', age: 22, }) => ({
name, // (b) reuse variable as new object parameter name (and value)
surname
}))();
console.log(result);
You can not mention it at all
((person = { name: 'Bob', surname: 'Smith', age: 22, }) => {
const {age,...ans} = person;
return ans
})()

Having troubles to get return from a function within an object

I'm trying to understand the use of "this". I can't get the age from the function calculation(undefined). What am I doing wrong?
const reina= {
firstName: 'Reina',
birthYear: 1998,
location:'Tokyo',
friends:['Chihomi','Lei','Louis'],
calcAge: function(){
this.age= 2021 - this.birthYear;
return this.age;
}
}
console.log(reina.age);
output:
undefined
You never called the calcAge function.
const reina = {
firstName: 'Reina',
birthYear: 1998,
location: 'Tokyo',
friends: ['Chihomi', 'Lei', 'Louis'],
calcAge: function() {
this.age = 2021 - this.birthYear;
return this.age;
}
}
console.log(reina.calcAge());
console.log(reina.age);
It seems like a getter is most appropriate in this case.
const reina = {
firstName: 'Reina',
birthYear: 1998,
location: 'Tokyo',
friends: ['Chihomi', 'Lei', 'Louis'],
get age() {
return 2021 - this.birthYear;
}
}
console.log(reina.age);
For the sake of reusability, I would use a Class instead of assigning to an object. That would leave less code in the long run.
this points to the current scope you're in, whether your in a method, an object or a class.
To create a class, you need to add a constructor, that you can send in parameters to. As you can see in the code, this in the constructor means the class Person when I call calcAge().
I also added new Date().getFullYear() which should be self-explanatory.
class Person {
constructor(firstName, birthYear, location, friends) {
this.firstName = firstName;
this.birthYear = birthYear;
this.location = location;
this.friends = friends;
this.age = this.calcAge(birthYear);
}
calcAge(birthYear) {
return new Date().getFullYear() - birthYear;
}
}
const reina = new Person('Reina', 1998, 'Tokyo', ['Chihomi', 'Lei', 'Louis']);
const rickard = new Person('Rickard', 1890, 'Stockholm', ['Beatrice', 'Gretchen', 'Hans']);
console.log(reina.firstName, reina.age);
console.log(rickard.firstName, rickard.age);

Lazy computed properties in Immutable.js Records?

Is there a standard way to define lazy computed properties on Records? When I access the computed property, it should run a function to compute the value, then cache the value. For example, something like:
const UserRecord = Record({
firstName: '',
lastName: '',
get fullName() {
console.log('Ran computation');
return `${this.firstName} ${this.lastName}`;
},
});
const user = new UserRecord({ firstName: 'Mark', lastName: 'Zuck' });
console.log(user.fullName); // Ran computation\nMark Zuck
console.log(user.fullName); // Mark Zuck
The closest I can get is defining a getFullName() method, then manually memoizing the computed value. I.e.:
getFullName() {
if (!this._fullName) {
this._fullName = `${this.firstName} ${this.lastName}`;
}
return this._fullName;
}
As long as you don't need it to ever "re-compute" this should do it I think.
const UserRecord = Record({
firstName: '',
lastName: '',
get fullName() {
console.log('Ran computation');
var value = `${this.firstName} ${this.lastName}`;
delete this.fullName;
Object.defineProperty(this, 'fullName', {
value: value
});
return value;
},
});
const user = new UserRecord({ firstName: 'Mark', lastName: 'Zuck' });
console.log(user.fullName); // Ran computation\nMark Zuck
console.log(user.fullName); // Mark Zuck

Categories