0

I have a function resFormat(restrictions) which takes an array of restrictions as a parameter and returns a string which contains diet restrictions. When calling it with ["res1","res2","res3"], it should return "res1, res2, res3"

function resFormat(restrictions){
    let result="",i
    for (i in restrictions){
        if(i===restrictions.length-1){ //always returns false 
            result += restrictions[i]
            continue
        }          
        result += restrictions[i]+", "
    }
    return result
}

console.log(resFormat(["res1", "res2", "res3"]));

Here i===restrictions.length-1 should return true when the loop reaches the last element of the array, but it always returns false.

Expected output:

res1, res2, res3

Actual output:

res1, res2, res3,
trincot
  • 317,000
  • 35
  • 244
  • 286
Ansh Malik
  • 162
  • 2
  • 7
  • 1
    `i` is a string, `restrictions.length-1` is a number, so `===` will not consider them the same. – VLAZ May 08 '21 at 19:32

2 Answers2

1

This is what happens when you use for..in over arrays: it leads to these kinds of errors. i will be a string data type, not numerical, since it iterates properties.

It would work if you did a loose comparison with == instead of ===, but it still is better to avoid for..in when iterating arrays.

Instead you can solve this problem with the native method join:

restrictions.join(", ");
trincot
  • 317,000
  • 35
  • 244
  • 286
0

Your code works when === is changed to ==

restrictions = ["res1","res2","res3"]
 let result="",i
        for (i in restrictions){
            if(i==restrictions.length-1){  
                result += restrictions[i]
            } 
            else
                result += restrictions[i]+", "
        }

=== is strict equality comparison operator in JavaScript, which returns false for the values which are not of a similar type.

i in this context refers to string and restrictions.length refers to number, you could try by checking with typeof command in javascript and examine the difference.

=== will work only when both operators are of same type. Hence, under such circumstances I advise you to use == , here content is just checked over here, not the type of operand and suits well in this domain.

Or if you wish to use ===, then value of i must be number, not a string

TMan
  • 39
  • 2