Home > Software design >  Don't know why the startsWith() method isn't working on the array elements
Don't know why the startsWith() method isn't working on the array elements

Time:11-06

The program is required to print the outputs that aren't numbers and don't start with the letter "A" . I got a message in the console that says : "

Uncaught TypeError: friends[index].startsWith is not a function
    at while-loop-assignment.js:6:23

"

The code is :

let friends = ["Ahmed", "Sayed", "Ali", 1, 2, "Mahmoud", "Amany"];
let index = 0;
let counter = 0;

while( index < friends.length ) {
    if(friends[index].startsWith("A") || typeof friends[index] === "number") {
        index  ;
        /* The above index increment is important otherwise the page will still reload
          and nothing will appear in the console  */
    continue;
    } else {
        console.log(` "${  counter} => ${friends[index]}" `);
        index  ;
        /* The increment for the index is important to not print the required values 
           infinitely */ 
    }
}

I don't understand why this error is appearing .

CodePudding user response:

Your friends array contains a mix of strings and numbers. numbers don't have a startsWith method. Only strings have the String.prototype.startsWith method.

You cannot call the startsWith method on something that is not a string. You have to check whether it is a string first.

For example, like this:

typeof friends[index] === "number" || friends[index].startsWith("A")

This makes use of the fact that the || binary logical OR operator is short-circuiting (see step 5 in section 13.13.1 Runtime Semantics: Evaluation), i.e. that the right-hand side is only evaluated if the left-hand side does not already determine the outcome of the operator expression.

CodePudding user response:


// check first if the index is number then being assured its a number then check if it startswith "a"

if(typeof friends[index] === "number" || friends[index].startsWith("A")) {
        index  ;
        /* The above index increment is important otherwise the page will still reload
          and nothing will appear in the console  */
    continue;
    }

  • Related