Why function is returning undefined

Why function is returning undefined with result

const halves = function(x) {
  console.log(x/2);
};

console.log(halves(100));

console.log returns undefined and so does the function by default.

console.log always returns undefined?

Yes, you will see the logged value and then undefined if you look in the browser console.

Your function is just not returning the value. Return the value the expression (the math) evaluates to.

const halves = function(x) {
  return x / 2
};

console.log(halves(100));
// 50 < value printed
// undefined < console.log return value
1 Like

now I understand
here:

first it return value for x, than for console.log right?

It doesn’t return anything. It prints 50 to the console inside the function.

The second console.log is supposed to log the function return value but the function just returns undefined (all functions do by default if no other return is given).

const halves = function(x) {
  // 50 < console.log inside the function
  console.log(x/2);
};

console.log(halves(100));
// undefined < function default return value
// undefined < console.log default return value
1 Like
const halves = function(x) {
  return console.log(x/2);
};

console.log(halves(100));

Now in-return it should print 50. Why it prints 50 and than return undefined?

Because that is exactly what you are telling it to do.

You tell it to return console.log (x/2). First it has to evaluate that to get its return value. In the process of evaluating it, it logs it to the screen. Then, since console.log doesn’t return anything, it effectively returns undefined. So, since that is what console.log (x/2) evaluates to, that is what your function returns.

If you want your function to log that value and return it, it would need two steps.

1 Like

Sorry for asking dumb questions.
thanks for taking the time to explain me this.

The only dumb question is the one someone is too afraid to ask. We once were all where you are now. Just keep at it, you’ll get there.

1 Like