dimanche 7 mai 2017

How is this && functioning? [duplicate]

This question already has an answer here:

I stumbled upon a piece of code that left me feeling rather perplexed, as I've never encountered this method before. Usually when checking a single case, I use an if statement, then execute the case.

Example:

var DoThing = function() {
    console.log('Do thing')
}
var DoOtherThing = function() {
    console.log('Other thing done')
}
var flag = 3

if(flag == 3)
    DoOtherThing()
else if(flag == 4) 
    DoThing()

However, the code I stumbled upon has the same results, but does this

var DoThing = function() {
    console.log('Do thing')
}
var DoOtherThing = function() {
    console.log('Other thing done')
}
var flag = 3

flag == 3 && DoOtherThing()
flag == 4 && DoThing()
// >Output: 'Other thing done'

What is happening behind the scenes for this to have the same results? What is this called, and why does this work?

Aucun commentaire:

Enregistrer un commentaire