# Elegantly check for null before method call

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.

• var title = document.querySelector('title') || {text:''}; – Shmiddty May 9 '13 at 20:21
• @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. – Joseph May 9 '13 at 20:26
• @JosephtheDreamer That's a replacement for the first line, not the second. Then title.text works as the OP expects. – FizzyTea May 9 '13 at 20:27
• @JosephtheDreamer what Fizzy said. OP could do this: ...................................................................... var title = (document.querySelector('title') || {text:''}).text; – Shmiddty May 9 '13 at 21:51
• @Shmiddty I got it. I just preserved the comment for future clarification. – Joseph May 9 '13 at 22:15

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

then just use title.text in-line.
var title = (document.querySelector('title') || {text:''}).text;