the_velour_fog the_velour_fog - 3 months ago 7
Javascript Question

javascript: using an assignment statement where a conditional expression would normally be

I just came across a piece of javascript code which used an assignment statement in the place where a logical

&&
or logical
OR
expression would be used:

var geo;

function getGeoLocation() {
try {
if ( !! navigator.geolocation ) {
return navigator.geolocation;
} else {
return undefined;
}
} catch(e) {
return undefined;
}
}


if (geo = getGeoLocation()) {
// ^^^^^^^^^^^^^^^^^^^^^ this is the statement I am interested in
console.log('conditional expression was true/truthy');
}


My question is, from the perspective of the
if
statement, what is being returned when

geo = getGeoLocation()
is evaluated?

Particularly what is it the result of? and what is the type?

is it


  • Whatever the function
    getGeoLocation()
    returned?

    (in which the type would be truthy/falsy)

  • is it the "result" of the assignment? i.e. whether or not something non-null was assigned?

    (in which case the "result" might be boolean, true/false?)

  • or something else?


Answer
if (geo = getGeoLocation()) {  
  // ...
}

My question is, from the perspective of the if statement, what is being returned when geo = getGeoLocation() is evaluated?

Here are the chronological steps of what will happen:

  • getGeoLocation() will execute first
  • assignment operation will happen next, where whatever getGeolocation() returns will be stored in geo

    • This will be either undefined or navigator.geolocation, if it exists.
  • geo will then be coerced to a boolean and evaluated as the condition to the if statement

The equivalent of that code is the following:

geo = getGeoLocation();
if (geo) {
  // ...
}