1

Im struggling with multiple complex statements in javaScript and wondered if anyone could point me in the right direction.

    function findFlights()
    {
    var yourDestination = readTheDestination();
    var yourAirline = readTheAirline();
    var yourFare = readTheFare();


    if (yourDestination == 'Choose your destination')
        {
        displayMessage('<B>Please choose a destination city from the Destination menu and then click Find flights again.</B>');
        }
    else
        {
        var destinationTime, destinationOperator, destinationFare;
        var message = '<B>You asked about flights to ' + yourDestination + '</B><BR>' + "";

        for (var i=0; i < flightTimes.length; i++)                      //flight destinations
        {
        if    // statement                                              // IF flight:
           ((flightDestinations[i] == yourDestination &&                // destination = selected destination &
            yourAirline == 'Any airline' &&                             // airline = any airline &
            yourFare == 'Any price'))                                    // fare <= chosen fare
            ||                                                          // OR
           (flightDestinations[i] == yourDestination &&                // destination = selected destination &
           yourAirline == flightOperators[i] &&                        // airline = chosen airline &
           yourFare <= flightFares[i]))                                // fare <= chosen fare

            {
            destinationTime = flightTimes[i];
            destinationOperator = flightOperators[i];
            destinationFare = flightFares[i];



            message += destinationTime + ' ' + destinationOperator + '. £' + destinationFare + '<BR>';
            displayMessage(message);

            }
        }
        else if (flightDestinations[i] == yourDestination && 
                flightOperators[i] != yourAirline && 
                flightFares[i] != yourFare)
            {
            displayMessage('There are no flights to ' + yourDestination + ' with ' + yourAirline + '. Please select Any Airline and try again.');
            }
        }

This is what I have so far and its making me gray.

4
  • 7
    uh... is there a question here? Commented Sep 13, 2010 at 16:57
  • You should describe what it's supposed to do. Commented Sep 13, 2010 at 16:57
  • Is the issue the if statement quantity? or whether there is a better way to do this task that you showed us? Commented Sep 13, 2010 at 17:01
  • First of all, correct all errors (JSLint), format the code (JSBeautifier) .... Commented Sep 13, 2010 at 17:07

4 Answers 4

7

Refactor complex code to function

If you have complex if statements try and wrap them up in functions. So

(flightDestinations[i] == yourDestination &&
yourAirline == 'Any airline' &&
yourFare == 'Any price')

could become

function YourDestinationIsTheSameForAnyAirlineOrPrice(flightDestination, yourDestination, yourAirline, yourFare){
    return flightDestination == yourDestination &&
        yourAirline == 'Any airline' &&
        yourFare == 'Any price';
}

// And called from if
if (YourDestinationIsTheSameForAnyAirlineOrPrice(flightDestinations[i], yourDestination, yourAirline, yourFare)) {}

Rather than trying to decipher the if statement you have a function name telling you what it does.

Use an object over multiple arrays

Specific to your example I would also try and create a single flight object that contains the destination, time and airline. eg:

var flight = {
    destination = "London",
    operator = "BA",
    time = "18:00 UTC",
    fare = "£239829"
}

This should make the code more readable than using multiple arrays. Example:

destinationTime = flightTimes[i];
destinationOperator = flightOperators[i];
destinationFare = flightFares[i];

message += destinationTime + ' ' + destinationOperator + '. £' + destinationFare + '<BR>';

// Using an object
message += flight.time + ' ' + flight.operator + '. £' + flight.fare + '<br />';

Return early

Finally I would break out of the function as soon as possible. So use:

if (yourDestination == 'Choose your destination') {
    displayMessage('<B>Please choose a destination city from the Destination menu and then click Find flights again.</B>');
    return;
}

instead of an if...else. I personally find this more readable, so feel free to ignore this.

Sign up to request clarification or add additional context in comments.

3 Comments

I wish I was learning this from another source, but I have to work within the confined of my tutors, I have picked up some tips now to change what Im looking at so will go with them, will ask again if get stuck further. thanks
Mate, you forgot to put the return at the beginning of the function YourDestinationIsTheSameForAnyAirlineOrPrice otherwise that is a great solution.
Thanks @Puiu. Good spot! :)
1

You've mismatched your parenthesis here:

((flightDestinations[i] == yourDestination &&                // destination = selected destination &
 yourAirline == 'Any airline' &&                             // airline = any airline &
 yourFare == 'Any price'))                                    // fare <= chosen fare
 ||                                                          // OR
(flightDestinations[i] == yourDestination &&                // destination = selected destination &
yourAirline == flightOperators[i] &&                        // airline = chosen airline &
yourFare <= flightFares[i]))                                // fare <= chosen fare

Change yourFare == 'Any price')) to yourFare == 'Any price').

1 Comment

I know, I have changed them on my hard copy, was just easier for posting, I have also used tabs to indent so I can see where the statements are supposed to go. Apparently we have been taught using very old writing style and not sure if thats whats causing problem
0

I'm not sure what the question is, but you should use more consistent indentation and the complex if statements will definitely become clearer.

My rules:

  • use tabs to indent your lines of code according to scope (e.g. +1 tab while within curly braces, if statements, etc.)
  • do not use tabs for anything else; use spaces for alignment, multiple spaces if necessary (so, use spaces to line up your conditions in the if statement if the statement spans multiple lines)

4 Comments

his indentation could have been messed up from copy & pasting, it looks like there is a form of indentation. Not really an answer here.
Sorry, my question is can you have so many if/or's in the statement.
Im working on the second If statement. I need it to have the selected destination, the selected airline and the fare to be less than or equal to the selected amount, its not happy with what I added here.
@amamam: you should update the question as well. But, there is no limit to the number of conditionals you can have in an if statement.
0

Although I think that this is not a necessary tuning, you can write the code as follows:

if (yourDestination == 'Choose your destination') {
    displayMessage('<B>Please choose a destination city from the Destination menu and then click Find flights again.</B>');
    return;
}

This helps you remove the else and its brackets {...}.

You can change the for loop to reduce the code size:

if(flightDestinations[i] != yourDestination) continue;

So that, you don't need to write this condition repeatedly.

2 Comments

may souond stupid but, does the break mean the script will stop at that point, we not been told the break in tutorials
No, it doesn't stop. It just gets to the next cycle without executing the code afterwards. i is incremented and iteration continues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.