Search code examples
javascriptstringvariable-assignmentlogical-operatorsboolean-logic

Why does the log of a variable declared with string + AND (&&) act differently to doing the same with OR (||)


I am at the beginning of learning JavaScript and came across different behaviour when declaring a variable with strings and && (the string doesn't show if used first) vs Strings and ||.

Edit:

I was essentially wanting to output the string before the Boolean value in the console.log and now realise that due to && going from left to right which is different for || that I need to add the number to both sides like the code below the "Snippet Edit" comment in code below (OR am I still wrong?)

Example:

const passDriversLicense = true;
const hasGoodVision = false;

//OR: Declaring a variable with strings and ||
let shouldDrive = ('1 ' + passDriversLicense || hasGoodVision);

console.log(`${shouldDrive} that she should drive`) // Output in console is "1 true that she should drive"
//AND: Declaring a variable with strings and &&
shouldDrive = ('2 ' + passDriversLicense && hasGoodVision);

console.log(`${shouldDrive} that she should drive`); // Output in console is "false that she should drive" which doesn't have the string before it, like in the OR version IE I would think it should output "2 false that she should drive"

//Snippet Edit
shouldDrive = ('1 ' + passDriversLicense && '1 ' + hasGoodVision);
console.log(`${shouldDrive} that she should drive`);


Solution

  • Trimming out the unnecessary baggage and substituting in the values directly, your question comes down to this:

    const one = '1 ' + true || false;
    console.log(one);
    
    const two = '2 ' + true && false;
    console.log(two);

    Which should make it clearer what's going on.

    In the first case, the left side of the || is '1 ' + true. This is a truthy expression, so the whole thing evaluates to that: '1 true'.

    In the second case, with &&, not only the left side needs to evaluate to a truthy expression, but the right side does too. But the right side is false, which isn't truthy - and && evaluates to the right-hand side if the left side isn't truthy.

    You could remove the + trues to get the same sort of effect:

    const one = '1 ' || false;
    console.log(one);
    
    const two = '2 ' && false;
    console.log(two);