Defining a variable inside an IIFE block

Can someone explain what is the difference between the following two IIFE blocks:

a) (f1 = function(){console.log('IIFE Block1')})()
b) (var f1 = function(){console.log('IIFE Block2')})()

I understand that "b" "will cause an error after execution. What is the use of defining the variable" f1 "and what are its properties.

+4
source share
3 answers

The first does not use the ad keyword, so it f1will become global (which defeats the IIFE goal). But this is the legitimate expression syntax — a function can be called, and the result (if any) can be assigned f1. Please note that this will not work with use strict.

(f1 = function(){console.log('IIFE Block1')})()

// f1 is Global and can be accessed from anywhere
console.log(f1);
Run codeHide result

The second setback is because this is invalid IIFE syntax - this declaration , , .

(var f1 = function(){console.log('IIFE Block2')})()
Hide result
+1

a . f1 IIFE. , , f1 ​​ var, let, const :

function quirks() {
  (f1 = function() { return 'f1 IIFE'; })();
  return f1;
}
console.log(quirks());

function strict() {
  "use strict";
  
  (f2 = function() { return 'f2 IIFE'; })();
  return f2;
}
console.log(strict());
Hide result
+2

, . , window, :

(f1 = function(){console.log('IIFE Block1')})()
console.log(f1);

// managed object
var local = {};
(local.f2 = function(){console.log('IIFE Block2')})()
console.log(local.f2);


// or any predefined variable
var f3;
(f3 = function(){console.log('IIFE Block3')})()
console.log(f3);

// just not in the parens
// (var f4 = function(){console.log('IIFE Block4')})()
// console.log(f4);
Hide result
+1

Source: https://habr.com/ru/post/1694626/


All Articles