\$\begingroup\$
\$\endgroup\$
7
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.
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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
default
var title = document.querySelector('title') || {text:''};
\$\endgroup\$text
with a blank string. \$\endgroup\$var title = (document.querySelector('title') || {text:''}).text;
\$\endgroup\$