-1

when I console.log this function, why does it print 12 and undefined? Shouldn't it just be undefined as the function is not returning anything?

function area(w,h) {
console.log(w*h)
}

console.log(area (3,4))

EDIT: Sorry super new and I thought that regardless of what is printed by the console.log, the second console.log would receive only what the function returned.

imad97
  • 7
  • 1

5 Answers5

2
function area(w,h) {
console.log(w*h) // Runs first and logs 12
}

console.log(area (3,4)) // Log undefined as the function doesn't return anything
Nvan
  • 1,126
  • 16
  • 23
0

The area function is logging the area, which is where 12 comes from.

The second undefined is the output of the console.log itself.

Generally, when you run anything which does not have output in a REPL, JavaScript adds an extra undefined

0

Because you already print it once

function area(w,h) {
  console.log(w*h)
}

area (3,4);

or

function area(w,h) {
  return (w*h)
}

console.log(area (3,4));
Reynadan
  • 327
  • 1
  • 10
0

There are two console log in your code. the first console log print 12 that is

console.log(w*h) ------------ 12

while the second console log print undefined because the function does not return anything

console.log(area (3,4)) ------------------ undefined

urchmaney
  • 588
  • 4
  • 6
0

function example(){
  console.log('1')
  return 2
}

function example2(){

}

console.log('start1')
console.log(example())
console.log('start2')
console.log(example2())
  1. run area(3,4); it shows console.log(w*h)
  2. because you do not have return in function, it default return undefined

You can check document Return

Xupitan
  • 876
  • 4
  • 11