1

Different behavior in javascripts code

First :

(function(){
   c();
   var c=function (){
      console.log("C");
   }
})();

Error : Uncaught TypeError: c is not a function

vs

(function(){
   c();
   function c(){
      console.log("C");
   }
})();

C

Second :

var a;
console.log(a);
a=10;

10

vs

(function(){
   var a; 
   console.log(a);
   a=10;
})()

undefined

Please help me to understand this behaviors. Thanks!!

ozil
  • 6,930
  • 9
  • 33
  • 56
Javascript Coder
  • 5,691
  • 8
  • 52
  • 98

1 Answers1

0

First

(function(){c();var c=function (){console.log("C");}})()

c is not yet defined, so it's an error.

(function(){c();function c(){console.log("C");}})()

function something() {} is always called at compile time, so c is defined here.

Second

var a;console.log(a);a=10;

The assignment returns the value of the assignment, so it's 10. It's also the reason why you can write a = b = 4.

(function(){var a; console.log(a);a=10;})()

The function doesn't return (there is not return) anything, so it's undefined.

If we are talking about about the console.log result here, they are both undefined since a is not yet defined.

Community
  • 1
  • 1
Vadim Pushtaev
  • 2,332
  • 18
  • 32