Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why undefined? Even if the this pointer is pointing to the same object and also the strict mode is used

"use strict";
const data = {
firstName: "myName",
lastName: this.firstName,
};
console.log(data.lastName);

Output is undefined.
Can anyone explain why it’s happening?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Because this does not work like that. When you are defining your object literal (data), this does not point to that literal – to see what this actually is, do a console.log(this).

You can solve your problem by modifying your code like this:

"use strict";
const data = {
    firstName: "myName"
}
data.lastname = data.firstname;

Also, I recommend reading up on how this works to avoid confusion in the future – this is a bit weird in Javascript.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading