0

function nextAction(arr) {
  if (nextAction = []) {
    return 'Nothing to do.';
  } else {
    return [0];
  }
}
console.log(nextAction(['tea', 'coffee', 'bread']));

How do I get tea returned. Thank You!

hgb123
  • 13,869
  • 3
  • 20
  • 38

3 Answers3

2

= is assignment operator, so to check if array is empty, you should check for its length instead

if (arr.length === 0) { ... }

Moreover, to access array element, use array_variable[index] instead of just [0] or use the function name nextAction

arr[0]

Demo

function nextAction(arr) {
  if (arr.length === 0) {
    return 'Nothing to do.';
  } else {
    return arr[0];
  }
}
console.log(nextAction(['tea', 'coffee', 'bread']));
hgb123
  • 13,869
  • 3
  • 20
  • 38
0

I guess you wanted this:

function nextAction(arr) {
  if (arr.length === 0) {
    return 'Nothing to do.';
  } else {
    return arr[0];
  }
}
console.log(nextAction(['tea', 'coffee', 'bread']));

Aside from using the assignment operator where a condition is expected, you can't check to see if an array is empty by comparing it to a different array. It's doing identity comparison, and you'd be comparing two different arrays with two different identities.

Also, you were using the function name instead of the parameter.

Then the index needs to be taken from the arr. It can't just stand alone. That syntax makes it seem as though you're creating a new array with the number 0 in it.

A more concise way would be like this:

function nextAction(arr) {
  return arr.length === 0 ? 'Nothing to do.' : arr[0];
}
console.log(nextAction(['tea', 'coffee', 'bread']));
0

function nextAction(arr) {
    if (arr == []) {
        return 'Nothing to do.';
    } else {
        return arr[0];
    }
}
console.log(nextAction(['tea', 'coffee', 'bread']));
Madhan
  • 79
  • 10