How do I elegantly check for null before calling a method on an object? This is how I do it right now:

var title = document.querySelector('title');
title = title ? title.text : '';

Null Object pattern would be nice in this case but I don't own the document.querySelector code.

  • 2
    \$\begingroup\$ var title = document.querySelector('title') || {text:''}; \$\endgroup\$ – Shmiddty May 9 '13 at 20:21
  • 1
    \$\begingroup\$ @Shmiddty that's wrong. The OP wanted to get either title text or blank. Your code returns either the title object or an object with a property text with a blank string. \$\endgroup\$ – Joseph May 9 '13 at 20:26
  • 2
    \$\begingroup\$ @JosephtheDreamer That's a replacement for the first line, not the second. Then title.text works as the OP expects. \$\endgroup\$ – FizzyTea May 9 '13 at 20:27
  • \$\begingroup\$ @JosephtheDreamer what Fizzy said. OP could do this: ...................................................................... var title = (document.querySelector('title') || {text:''}).text; \$\endgroup\$ – Shmiddty May 9 '13 at 21:51
  • \$\begingroup\$ @Shmiddty I got it. I just preserved the comment for future clarification. \$\endgroup\$ – Joseph May 9 '13 at 22:15

You can do this:

var title = document.querySelector('title') || {text:''};

then just use title.text in-line.

Alternatively, you could use this one-liner:

var title = (document.querySelector('title') || {text:''}).text;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.