How can we assign a variable and also detect if the result is null or false in one if statement?
function getNodes(selector) {
var nodeList = document.querySelectorAll(selector);
if(!nodeList.length) { return null; } else { return nodeList; }
}
var divs;
if( ! divs = getNodes('div') ) { // ReferenceError: invalid assignment left-hand side
console.log('no divs found');
}
if( divs = getNodes('div') && !divs ) { // does not work
console.log('no divs found');
}
if( divs = getNodes('div') && divs==null ) { // does not work
console.log('no divs found');
}
<p>
no divs here
</p>
Simply if(divs = getNodes('div'))
does work but that is not what I am after. I need to catch if it's null or assign it in one statement.
Solution 1 if( !(divs = getNodes('div')) )
Solution 2 if( (divs = getNodes('div')) == null )
Thank you everyone