patternjavascriptMinor
Elegantly check for null before method call
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:
Null Object pattern would be nice in this case but I don't own the
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:
then just use
Alternatively, you could use this one-liner:
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.