Return 2 distinct values in the same block within an if statement?



Is it possible to return 2 distinct values in the same block within an if statement?
In my code, when the if statement gives a value of false, I want the function to return false, and also .push() the string that gives false value to an array. What I 've tried is this:

function exclusion (element) {
let i = 0;
while (i<=unnecessaryWords.length){ 
  if (i === unnecessaryWords.length) {
    return true;
 } else if (unnecessaryWords[i] === element){
    return false;
    return wordsExcluded.push (element);
 } else if (unnecessaryWords[i] !== element){           

But it, expectedly, only returns false.
So, is it possible to do it in that block of code or should I create another block out of the function?


lets take a step back first, why would you use a while loop here? We are looping over an array, why not use a for loop? While loops are great when you don’t know how many times the loop needs to run (getting valid user input for example), for loops are useful are the amount of iterations are known (like looping over an array)

to answer your other question: no.


I was just trying to get used to type while loops. But thanks for your advice!


we were not done yet :wink:

i would then do the reverse, i would return false when no exclusion is happening (loops through unnecessaryWords without a problem). Return wordsExcluded if a word needs to be excluded. A array with a value is seen as true (if (['test'])), so then you have “true” and false. Quite useful


Two things are wrong with the above…

return ...

Anything after return is unreachable, meaning the second return and the break.

We never need to write break after a return. The switch (and the function) have already been exited.

You function might take advantage of the one of the iterators learned in this unit… .filter(). Give it a try.


@stetim94 @mtf

Thank you very much. You guys have been so helpful. So, I think I am overloaded after “functions over other functions which are nested in functions that are indeed data for other functions” kindda lessons :smile: and I have been thinking about just this code over 12 hours. But now, my synapses’ junctions finally connected. Or,…not yet, I don’t know. This is the last version below and it works okay:

const re = /\s*\W|$\s/;
const storyWords = story.split(re);

let justWords = [];
for (let i = 0; i<storyWords.length; i++) {
if (storyWords[i] !== '' && storyWords[i] !==' ') {justWords.push(storyWords[i])}

function exclusion (element) {
  for (let i = 0; i<=unnecessaryWords.length; i++){
    if (unnecessaryWords[i] !== element && i === unnecessaryWords.length) {
      return true;
    }else if (unnecessaryWords[i] === element) {
      return false;

let betterWords = justWords.filter (better=>{
  return exclusion(better)