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

return Element if exists using ternary operator by the shorten way as possible in JS

Is there any way to shorten the myFx() function without repeating document.getElementById('myID') ?
I just want to return the Element if it exists, if it doesn’t, return "false".

The function is working well that manner, but I would like to know if there is any way to shorten it a little more.

HTML:

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

<div id="myID">Hello World!</div>

JavaScript:

function myFx(){

  return (document.getElementById('myID') === null) ? false : document.getElementById('myID');
  
}

myFx().innerHTML = "Goodbye Cruel World!";

>Solution :

Use Nullish coalescing operator (??).

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

function myFx() {
  return document.getElementById('myID') ?? false;

}

myFx().innerHTML = "Goodbye Cruel World!";
<div id="myID">Hello World!</div>
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