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 does nullish coalescing executing two parts?

I have a method:

const objT2 = {
  calcAge(year) {
    console.log(2022 - year);
  },
};

but when I use the nullish coalescing both parts is being executed.

objT2.calcAge(1990) ?? console.log(`method not found`);
//output => 32    method not found

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

>Solution :

first you are calling calcAge method with 1990. so by calling it, the method gets executed objT2.calcAge(1990). this calculated 2022 - 1990 which is 32 and then logs it to the console. then this method returns undefined which gets evaluated as the left hand operand of the ?? operator. As this operator sees the left hand side is returning a nullish value (null or undefined), it goes on to execute the right hand side which logs method not found as well.

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