Home > Back-end >  return Element if exists using ternary operator by the shorten way as possible in JS
return Element if exists using ternary operator by the shorten way as possible in JS

Time:08-12

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:

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

JavaScript:

function myFx(){

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

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

CodePudding user response:

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>

CodePudding user response:

The answer of @c0m1t is correct, just be aware that this might not work in older browsers. I am not sure if it's still a real issue today, but anyway .. here is solution which should work even in ancient browsers.

function myFx(){
  var element = document.getElementById('myID');
  return element || false;
}

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