Problem with Checking Last String

This challenge is to write a function that checks the last part of a string, which I’ve attempted, but my code isn’t working as it should. I’d appreciate diagnostic help.

  **My code so far**
      function confirmEnding(str, target) {
  let arr = [];
  let newArray = arr.push(str);
  let i = newArray.length - 1;
    if (newArray[i] == target) {
      return true;
  } else {
    return false;

I’m getting false when it should be true.

console.log(confirmEnding("Bastian", "n"));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36.

Challenge: Confirm the Ending

Link to the challenge:

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Well you do a couple of weird things that indicate you should read up again on strings and arrays.

For a start, you create an empty array.
Then you want to create a second array which is like the first, if it contained a string - except as gaac510 pointed out, the .push() function returns the new length of the array, so newArray is actually an integer.
Then you calculate the length of the new “array” (which would be 1, because you pushed one element into it) and subtract 1, so i==0 in every case.
→ except since newArray is actually an integer, it doesn’t have a .length attribute so it’s undefined.
Then you take your second array, look at it’s first entry (which would be str) and check if it is identical to target.
→ though again, because it’s an integer, that’s undefined.

In other words, all your code would do at best is:

function confirmEnding(str, target) {
   return str == target

Right now it’s checking if undefined == target.

Meaning you have to rethink your entire approach.
Also keep in mind that target can have different lengths.


Also I seem to remember push returns the new length instead of the changed array? I could be wrong

Tested it in the editor and you are right.

Thanks! I’ll do this next time.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.