0

I am using MEAN stack and I am sending query parameters dynamically to my Nodejs server endpoints. My client controller :

$http.get('/api/things',{params:{query:query}}).then(response => {
      this.awesomeThings = response.data;
      socket.syncUpdates('thing', this.awesomeThings);
    });

where query is a value injected into the controller. This is the server controller function (which works):

export function index(req, res) {
  var query = req.query.query && JSON.parse(req.query.query)
  Thing.find(query).sort({_id:-1}).limit(20).execAsync()
    .then(respondWithResult(res))
    .catch(handleError(res));
}

The above works but I am trying to understand the line

var query = req.query.query && JSON.parse(req.query.query)

as I have never seen this before( and I don't come from a programming background). I console.logged query and understand it's an object (which is required by Mongodb) but when I console.logged (JSON.parse(req.query.query)) or JSON.parse(query) to find out the final output, the program stops working with no error messages, very strange.. If someone can explain the above syntax and why it has to be done this way for it work, that would be much appreciated.. PS when I try to console log the JSON.parse like so, it fails to load even though it should have no effect whatsoever:

export function index(req, res) {
  var query = req.query.query && JSON.parse(req.query.query)
  var que = JSON.parse(req.query.query)
  Thing.find(query).sort({_id:-1}).limit(20).execAsync()
    .then(respondWithResult(res))
    .catch(handleError(res));
    console.log("que"+que)
}
A Allen
  • 273
  • 1
  • 4
  • 12
  • Possible duplicate of [Assignment with double ampersand "&&"](http://stackoverflow.com/questions/12878612/assignment-with-double-ampersand) – DAXaholic Jul 11 '16 at 03:45
  • This is the only code that will work. If I don't code it that way, it doesn't work. The codes above are taken from actual working codes, I am just asking what that syntax means and why it works. – A Allen Jul 11 '16 at 03:49

1 Answers1

1

function one() {
  var x = {};
  var res = JSON.parse(x.y);
  console.log(res);
}

function two() {
  var x = {};
  var res = x.y && JSON.parse(x.y);
  console.log(res);
}
<button onclick="one()">ERROR</button>
<button onclick="two()">NO ERROR</button>
var x = data && JSON.parse(data);

Since expression is evaluated from left, first data is evaulated.

If it is undefined then, the next part -> JSON.parse() is not performed. On the other hand, if data is defined parse is tried and the result is returned and stored in x.

Main advantage here is the parse doesn't run if the variable wasn't defined.

it could be equivalent to saying:

if(data) {x = JSON.parse(x);}
Iceman
  • 6,035
  • 2
  • 23
  • 34