0

I want to create a function that takes in an array. If the array is empty (or === 0) I want to return one string. If the array is not empty, I want to return a different string + remove+return first element of array. How do I accomplish this?

Sample

> function(ary) {
> if (ary.length === 0) {
>-return string-
>}
>else {return other string + ary.shift[0]}
>}
7
  • The code seems to be fine. What issues did you encounter? Commented Feb 9, 2017 at 0:54
  • And the question is? Commented Feb 9, 2017 at 0:54
  • @MaxZoom I did not get to the else under any circumstance, it just returned the first string. Commented Feb 9, 2017 at 0:55
  • See the documentation for shift Commented Feb 9, 2017 at 0:56
  • @MaxZoom forgive my ignorance but I am an extreme beginner. If my if statement isn't true, my code still does not make it into my else. It just returns the string from the if statement. Commented Feb 9, 2017 at 1:00

2 Answers 2

1

Below is your code with one shift correction:

function check(ary) {
  if (ary.length === 0) {
    return "empty";
  } else {
    return "First was the " + ary.shift()
  }
}

console.log( check([]) );
console.log( check(['word', 'chaos', 'light']) );

Sign up to request clarification or add additional context in comments.

Comments

1

shift is a function that take no parameter. It should be called like this:

function(ary) {
    if (ary.length === 0) {
        return "string";
    }
    else {
        return "other string" + ary.shift();
    }
}

Note that the else could be removed. Just the return statment is enough since if the length of ary is 0 the code after if will never be reached (because of the return inside the if body), so the code after could be left unwrapped by the else. Like this:

function(ary) {
    if (ary.length === 0) // remove the braces as well since the `if` body is just one statement
        return "string";
    return "other string" + ary.shift(); // if `if`'s test is true this line will never be reached
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.