Home > Software engineering >  Conditional evaluating to a string
Conditional evaluating to a string

Time:05-18

I'm trying to create a check that looks to see if a field has changed from the placeholder value. If it hasn't I reassign the original changed value, as the function (in my actual codebase) has to look at multiple fields.

I'm just a bit confused why:

changed = (locationField.value && locationField.value !== locationField.placeholder) ? true : changed;

is evaluating to an empty string* if the field is submitted with no value.

*output at end of post

I assume it's the empty value of locationField.value, but shouldn't it be assigning either 'true' or the value of changed? Changed (as far as I can see) is never, and should never, be a string.

Probably a simple question, but I can't see the answer.

Codepen

const locationField = document.querySelector('.location');
const submit = document.querySelector('.submit');
let changed = false;

submit.addEventListener('click', e => {
  changed = (locationField.value && locationField.value !== locationField.placeholder) ? true : changed;
  console.log(locationField.value, locationField.placeholder, (locationField.value && locationField.value !== locationField.placeholder));
  console.log(changed);
  
  // reset 
  changed = false;
});
<input type="text" placeholder="test" >
<button >Submit</button>

**EDIT:

Results I get:

input "changed" => "changed", "test", true

input "test" => "test", "test", false

input "" "", "test", "", when I'd expect "", "test", false

CodePudding user response:

Logical AND (&&) evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; if all values are truthy, the value of the last operand is returned.

(source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND)

So in your case, if locationField.value is "" which evaluates as a falsy value, then logical AND going to return the value of locationField.value (which is why it returns an empty string)

CodePudding user response:

If you first convert locationField.value to a boolean, either with !! or with Boolean(), then you should get the expected result.

(!!locationField.value && locationField.value !== locationField.placeholder)
  • Related