1

I want to know why "console.log(a);" is "undefined"

const number = ['0', '1', '2'];

const pop = array => {
  array.pop();
}

console.log(number); // [ '0', '1', '2' ]
a = pop(number);
console.log(number); // [ '0', '1' ]
console.log(a); // undefined
b = number.pop();
console.log(number); // [ '0' ]
console.log(b); // 1

I expect "undefined" should be "2"

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Chovy
  • 13
  • 3
  • 4
    You are not returning anything from the function. Either `return array.pop()` or remove the `{}` brackets for implicit return like this: `const pop = array => array.pop();` – adiga Jul 20 '19 at 13:23

3 Answers3

4

An arrow function will implicitly return only if the first non-whitespace character after the => is not an opening curly brace {. Remove the braces to make it a concise function:

const pop = array => array.pop();

Or use return like you would in a normal verbose function:

const pop = array => {
  return array.pop();
};

Also note that currently pop does what Array.prototype.pop also does - remove the last element from an array, and return that element. It's simpler not to write your own function, and simply use the inbuilt array method:

a = number.pop();
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • 1
    Thanks a lot!! By the way, I am still confused about 'why the last line is not 'undefined' but '1''. – Chovy Jul 20 '19 at 13:41
  • That's because you use `number.pop()` and not `pop(number)`, you are not calling your function but `Array.prototype.pop` that does return the value popped. – Ricola Jul 20 '19 at 14:12
0

Your pop function is not returning anything.

Add a return on array.pop() call

Martin Choraine
  • 2,296
  • 3
  • 20
  • 37
0

It's because you don't return anything in your arrow function. You could either write

const pop = array => {
  return array.pop();
}

Or, in a simpler way :

const pop = array => array.pop();
Ricola
  • 2,621
  • 12
  • 22