1

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

  • 1
    Convert the assignment to an expression by wrapping it in the parentheses (in the first if). – Teemu Oct 27 '17 at 18:54
  • Couldn't you just assign the variable first, and then do the check later? var divs = getNodes('div'); if (!divs) // falsy – deojeff Oct 27 '17 at 18:55
  • @d30jeff certainly, but i'm trying to do both at once. –  Oct 27 '17 at 19:01
  • @Teemu that was it, thanks! –  Oct 27 '17 at 19:02
  • 1
    What is the benefit of doing it in one step other than being not really readable? – epascarello Oct 27 '17 at 19:02
  • @epascarello I find it easily readable. Less lines, more screen space, I can see more of my code at once, smaller file size, minifies better, etc. –  Oct 27 '17 at 19:05
  • @epascarello I wouldn't say that's an appropriate dup target. This is more about operator precedence. Good reading, though. – Teemu Oct 27 '17 at 19:14

2 Answers2

1

divs = getNodes('div') will basically return the value assigned to divs. That's how you are able to do a = b = 2.

In your case, you can basically do:

and so, ((div = getNodes('div')) == null) evaluates to true.

Which means, you can basically do:

if((div = getNodes('div')) === null){
    //do Whatever
}

Or if you just want to check if its null and you know it will never evaluate to false (or if false is also an error condition), you can:

if(!(div = getNodes('div'))){
    //do whatever
}
Parijat Purohit
  • 921
  • 6
  • 16
0

This should do what you're trying to accomplish.

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');
}

console.log(divs);
Nick
  • 16,066
  • 3
  • 16
  • 32