Skip to content
Advertisement

nested if statements javascript

I’m trying to do a lookup until i found an especific value; currently using if statements like this but right now its only two levels and i dont need how many if statements will be needed until the conditions meets.

if (newObject.parent.toString() != 1) {
            alert(newObject.shareholder + ' no es 1 Buscaremos sus padres');
            var newObject = parentSearch.search(newObject.parent.toString())[0].item;

            if (newObject.parent.toString() != 1) {

                var newObject = parentSearch.search(newObject.parent.toString())[0].item;

            } else {
                alert(newObject.shareholder + ' Found');

            }
        } else {
            alert(newObject.shareholder + ' Found');

        }

Is there a way to avoid using infinite IF statements ?

Advertisement

Answer

You can make use of recursion as follow:

function checkObject(newObject) {
    if (newObject.parent.toString() != 1) {
        alert(newObject.shareholder + ' no es 1 Buscaremos sus padres');
        const newObject = parentSearch.search(newObject.parent.toString())[0].item;

        checkObject(newObject)  // recursion
    } else {
        alert(newObject.shareholder + ' Found');

    }
}

In case you cannot use recursion, you can use following:

function checkObject(newObject) { 
    while (true){
        if (newObject.parent.toString() != 1) {
            alert(newObject.shareholder + ' no es 1 Buscaremos sus padres');
            
            newObject = parentSearch.search(newObject.parent.toString())[0].item;
        } else {
            alert(newObject.shareholder + ' Found');
            break;
        }
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement