In a node.js application, I found a function (which is a monkey-patch for the http.ServerResponse class) having two parameters passed to it:
- content: I suppose this is a message string (or JSON) which will be the response message to the client.
- status: a number.
This the function code:
http.ServerResponse.prototype.respond = function (content, status) {
if ('undefined' == typeof status) { // only one parameter found
if ('number' == typeof content || !isNaN(parseInt(content))) { // usage "respond(status)"
status = parseInt(content);
content = undefined;
} else { // usage "respond(content)"
status = 200;
}
}
if (status != 200) { // error
content = {
"code": status,
"status": http.STATUS_CODES[status],
"message": content && content.toString() || null
};
}
if ('object' != typeof content) { // wrap content if necessary
content = {"result":content};
}
// respond with JSON data
this.send(JSON.stringify(content)+"\n", status);
};
I couldn't understand the meaning of the value affected to the content's message property in this line:
"message": content && content.toString() || null
As the '&&' is a logical operator so content and content.toString() must be interpreted as binaries (true/false). What does it mean to convert a String to a Binary in javascript? (Is it that when it's not null or undefined so it will be as true?)
I have made a test like this:
//content = {var1:'val1', var2:'val2'};
content = "some content here";
/*console.log('content.toString() : ' + content.toString()); // [object Object]
console.log('JSON.stringify() : ' + JSON.stringify(content));
*/
console.log('content == true' + content == true); // this will display : false
console.log('content.toString() == true' + content.toString() == true); // false too..
console.log('content && content.toString() : ' + content && content.toString()); // this will display nothing
console.log('(content && content.toString()) == true' + (content && content.toString()) == true); // false
var message = content && content.toString() || null; //
console.log('message : ' + message);
And as it's shown:
content == true // returns false
content.toString() == true // returns false too
I just assume that the value affected to the "message" tests if a content exists and converts it to String but I don't understand the logic behind it.