1
function func(){
  var name
  console.log(name)
  name="pavan"
  console.log(name)
}

func()

When I run the above code it gives me the output undefined pavan.


var name
console.log(name)
name="pavan"
console.log(name)

When I run this modified code it's logging pavan pavan.

What's the difference?

SNBS
  • 671
  • 2
  • 22
pavan octa
  • 11
  • 3
  • Typing commands into the console can produce confusing "<- undefined" output. See https://stackoverflow.com/questions/14633968/chrome-firefox-console-log-always-appends-a-line-saying-undefined Your function `func`, while being a totally valid function, doesnt return anything, so your console logs "undefined" when you call it. – James Aug 01 '23 at 16:54
  • No when i run it in html it gives undefined and pavan but when I try the other one its giving me pavan and pavan – pavan octa Aug 01 '23 at 17:01
  • because global is `window.name` – epascarello Aug 02 '23 at 15:35

1 Answers1

0

The problem is that you are reusing same variable names when running your experiments.

Consider:

var name;
name = 'pavan'
var name;
console.log(name); // prints pavan

If you use different variable names in both snippets, you will get expected output:

var name1;
console.log(name1);  // prints undefined
name1="pavan";
console.log(name1);  // prints pavan

Also note that name is a property of Window object. See Window: name property

Lesiak
  • 22,088
  • 2
  • 41
  • 65