runEngine
runEngine

Reputation: 25

AND && OR || combination in JavaScript

Task explained shortly: Making a datingsite, that need 4 outcomes. Woman 25 and above, Woman 24 and below. Man 25 and above, Woman 24 and below. Now I want to have 4 more outcomes; all womans, all men, all 25 and above, all 24 and below.

I just started on my bachelor degree in August and have not coded anything before. I am now working on a few tasks that we got, this is a task that we had to deliver that was work requierment. I delivered it with arrays and got the job done with it, and with one else if statement more. Everything good so far. But now later on, we just learned about object literals, and I wanted to check if I could do the code somehow shorter. I actually did with only 1x if statement below.

I am struggling with OR || and && combinations. I've seen some threads on it, saying that parantheses should be placed before and after &&, but I can't seem to get it. The below code does work with the 4 possible combinations, I wanted to check if someone can see how I can add || && combinations more smarter to get the 4 more combinations that I want, in the same if-statement? Or do I have to make a new else if statement? Also, how would you solve this, what type of storing variables would you go for? I have thougth about using some parameters in the function, to shorten something, but I could not come up with something, yet.

var result = document.getElementById('result');
var searchBtn = document.getElementById('search-btn');


var data = {
    profiles: 
    [{
        name: 'Maren',
        age: 26,
        gender: 'female',
        description: 'If you do not like me, I will be attracted by you.',
        image: 'kvinne1.jpg'
    }, {
        name: 'Indie',
        age: 23,
        gender: 'female',
        description: 'Love flowers',
        image: 'kvinne2.jpg'
    }, {
        name: 'Felix',
        age: 22,
        gender: 'male',
        description: 'Snowboard, that is lyfe',
        image: 'mann2.jpg'
    }, {
        name: 'Jon',
        age: 26,
        gender: 'male',
        description: 'Love to fish, and I will learn you to fish if you want!',
        image: 'mann1.jpg'
    }]
};



function getResult() {
    result.innerHTML = '';

    var ageInput = document.getElementById('age-input').value;
    var genderInput = document.getElementById('gender-input').value.toLowerCase();
    
    for (let i = 0; i < data.profiles.length; i++) {
        if ((genderInput === data.profiles[i].gender) && (ageInput < 25) && (data.profiles[i].age < 25) || (genderInput === data.profiles[i].gender) && (ageInput >= 25) && (data.profiles[i].age >= 25)) {
            result.innerHTML += `
                <img src='${data.profiles[i].image}'>
                <h2>${data.profiles[i].name}</h2>
                <p>Age: ${data.profiles[i].age}</p>
                <p>${data.profiles[i].description}</p>
                <hr>
                `;
        }
    }
}

Upvotes: 1

Views: 847

Answers (3)

3limin4t0r
3limin4t0r

Reputation: 21130

I won't go into how you can combine your && and || smarter, since that is already answered by the answer of Nina Scholz. I would like to point out that less if-statements isn't necessary better. In my opinion the best code is understandable and readable code, so colleges and future you understand what you wrote.

function getResult() {
    result.innerHTML = '';

    const ageInput    = document.getElementById('age-input').value;
    const genderInput = document.getElementById('gender-input').value.toLowerCase();
    const matchesAge  = ageInput < 25
                      ? (age) => age < 25
                      : (age) => age >= 25;

    for (const profile of data.profiles) {
        if (profile.gender != genderInput) continue;
        if (!matchesAge(profile.age)) continue;

        result.innerHTML += `
            <img src='${profile.image}'>
            <h2>${profile.name}</h2>
            <p>Age: ${profile.age}</p>
            <p>${profile.description}</p>
            <hr>
            `;
    }
}

This solution uses the ternary operator (condition ? exprIfTrue : exprIfFalse) to create an arrow function that checks the if the provided age matches the criteria.

I opted to loop using for...of instead of the standard for-loop. Since you don't use the index to do anything other than access the current profile you might as well remove some of the visual complexity.

Lastly I use two guard clauses to skip to the next iteration using the continue statement. (Continue means, continue with the next iteration, meaning that the current iteration is skipped.)

Upvotes: 1

Shyam Mohan
Shyam Mohan

Reputation: 129

As per the description, I think you are looking to create different array with some condition if so.

const allMale = data.profiles.filter(profile => profile.gender === 'male') // will give you all men

cont allFemale =data.profiles.filter(profile => profile.gender === 'female' && profile.age > = 25) // will give you all female

const genderFemale = data.profiles.filter(profile => profile.gender === 'female' && profile.age <= 24) // All female with age less than age 24. And so on try the JavaScript filter function

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386654

You have one common part with gender and another with age which is either smaller than 25 or equal or greater than 25.

You need no parenthese around comparisons.

genderInput === data.profiles[i].gender && 
(ageInput < 25 && data.profiles[i].age < 25 || ageInput >= 25 && data.profiles[i].age >= 25)

Upvotes: 3

Related Questions