Why does my JavaScript code print undefined before the real value?

clock icon

asked 18 days ago

message icon

0 Answers

eye icon

41 Views

I’m new to JS and trying to understand how functions work. Here’s my code:

1function sayHello() {
2 var name = "John";
3 console.log(greeting);
4 var greeting = "Hello " + name;
5}
6
7sayHello();
8
1function sayHello() {
2 var name = "John";
3 console.log(greeting);
4 var greeting = "Hello " + name;
5}
6
7sayHello();
8

When I run this, it prints:

1undefined
1undefined

Why does it print undefined instead of "Hello John"?

0 Answers

Empty state illustration

No Answers Found

The answer board is empty. Make it rain with your brilliant answer.

Write your answer here

Top Questions