Global variable

var myvar = ‘my value’;

(function() {
console.log(myvar);
var myvar = ‘local value’;
})();

why above is returning undefined? and not my value?

See the variable hoisting section in MDN link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variable_hoisting

From the link,

    var myvar = 'my value';
 
    (function() {
      console.log(myvar); // undefined
      var myvar = 'local value';
    })();

is interpreted as:

var myvar = 'my value';
 
(function() {
  var myvar;
  console.log(myvar); // undefined
  myvar = 'local value';
})();

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.