HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Elegantly check for null before method call

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
methodnullcallelegantlyforbeforecheck

Problem

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.

Solution

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;

Code Snippets

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

Context

StackExchange Code Review Q#26000, answer score: 9

Revisions (0)

No revisions yet.