What is the difference between using while and if conditions in JavaScript?

78 Views Asked by At

I'm currently building a reactive form in Angular in which the form fields are adjusted dinamically depending on the user input.
Example of function to create the form:

this.form = this.formBuilder.group({
    name: this.formBuilder.control('', {nonNullable: true}),
    isOne: this.formBuilder.control({value: null, disabled: true}, {nonNullable: true}),
    type: this.formBuilder.control({value: null, disabled: true}),
    model: this.formBuilder.control({value: null, disabled: true}),
    city: this.formBuilder.control({value: null, disabled: true}),
})

Then I made subscriptions to the form values that should enable/disable/change inputs when a condition is met or not:

this.form.get('name').valueChanges.subscribe(newValue => {
    if (newValue !== '') {
        this.form.get('isOne').enable();
    } else {
        this.form.get('isOne').disable();
    }
    ...
}

Because I don't want model field to change other things before the user touches it, I added the condition in the function that checks whether the field is pristine or not before doing the logic.

this.form.get('type').valueChanges.subscribe(newValue => {
    while (this.form.get('type').pristine) { // if (this.form.get('type').pristine) {
        return;
    }
    if (newValue === 'house') {
       this.form.get('model').disable();
       this.form.get('city').enable();
    } else {
       this.form.get('model').enable();
       this.form.get('city').disable();
    }
});

In my logic it makes sense to use while here becasue pristine is a condition that will be met for a while until the user touches it. Therefore, it seems to improve code readability. However, if can also handle the logic here and it is used much more often than while in javaScript.
My question is what are the implications of using while here? Does it adversely affects performance? Is there an advantage in using if instead of while?

I made the form using while and I expect it to be functionally the same as if.

1

There are 1 best solutions below

2
Riheldo Melo On BEST ANSWER

Interesting proposition.

We can test: https://stackblitz.com/edit/node-2dqj59?file=index.js
Dont know how trust is the test, but surprising while condition is a bit faster.

The execution flow will be the same. While-return and If, when compiled, may generate scopes from different sizes, but dont believe that will be that different, and about performance, i think it will be irrelevant.

But, i believe the point is about maintainability, if another developer check this code, will be expecting a loop execution code, and not just the return, it will looks wrong. So maybe, it will be necessary some commentary code explanning. But an if condition wont need any further explanation, because everyone is teached like that.