connection && connection.close();

I'm reading some pieces of code using Node.js and Tedious to create a full-stack app connecting to MS SQL Server. And I stumbled upon this piece.

function createRequest(query, connection) {
    var Request = require('tedious').Request;
    var req =
        new Request(query, 
                function (err, rowCount) {
                        if (err) {
                            console.trace(err);
                            throw err;
                        }
                        connection && connection.close();
                        console.log('Connection closed');
                });
    return req;
}

Could anyone explain what the line connection && connection.close(); does?

Upvotes: 0

Views: 144

Answers (2)

Cohars
Cohars

Reputation: 4012

connection && connection.close() is actually kind of a "trick" that I would not recommend.

It means

if (connection) {
  connection.close()
}

The trick is to use the && operator as a shorthand syntax. If the left expression is falsy (undefined or null for exemple), the right expression won't even be evaluated.

You can give it a try with

true && console.log('Hello')
// 
false && console.log('will never be logged')

There is a dedicated part about this short-circuit in the MDN documentation

Upvotes: 2

MrPickles
MrPickles

Reputation: 949

It is saying if connection is defined run connection.close()

it is the same as

if(connection){
    connection.close()
}

It works because && returns the first Falsy result.

ie:

console.log(false && 'something'); // false

console.log(true && 'something'); // 'something'

Upvotes: 1

Related Questions