4
\$\begingroup\$

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.

asked May 9, 2013 at 20:14
\$\endgroup\$
7
  • 2
    \$\begingroup\$ var title = document.querySelector('title') || {text:''}; \$\endgroup\$ Commented May 9, 2013 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\$ Commented May 9, 2013 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\$ Commented May 9, 2013 at 20:27
  • \$\begingroup\$ @JosephtheDreamer what Fizzy said. OP could do this: ...................................................................... var title = (document.querySelector('title') || {text:''}).text; \$\endgroup\$ Commented May 9, 2013 at 21:51
  • \$\begingroup\$ @Shmiddty I got it. I just preserved the comment for future clarification. \$\endgroup\$ Commented May 9, 2013 at 22:15

1 Answer 1

9
\$\begingroup\$

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;
answered May 10, 2013 at 1:08
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.