Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
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:

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

JavaScript:

function myFx(){

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

myFx().innerHTML = "Goodbye Cruel World!";
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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!";
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!