Reputation: 117
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]}
>}
Upvotes: 0
Views: 50
Reputation: 31682
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
}
Upvotes: 1
Reputation: 7753
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']) );
Upvotes: 1