0

Can any one explain why this happens?

// Example 1
(function () {
    var a = b = 5;
})();

console.log(b); // Output 5

var a = b = 5 and var b = 5 is totally different?

  • `var a = b = 5;` is like `b = 5; var a = 5;` – CertainPerformance Dec 18 '22 at 06:25
  • var a = b = 5; means var a = 5; and window.b =5; thats why b is accessible outside IIFE. – Asad Gulzar Dec 18 '22 at 06:27
  • 1
    I strongly encourage you to use `const` or `let` instead of `var`, and move to [JavaScript modules](//developer.mozilla.org/en/docs/Web/JavaScript/Guide/Modules) or at least enable [strict mode](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Strict_mode). The syntax for a declaration like `var` consists of a _VariableDeclarationList_ after the keyword. You have one _VariableDeclaration_ which consists of _BindingIdentifier Initializer_. The _BindingIdentifier_ is `a`, the _Initializer_ is the `=` followed by the _AssignmentExpression_ `b = 5`. `b` was never a _BindingIdentifier_. – Sebastian Simon Dec 18 '22 at 08:08

0 Answers0