Middle+
Mida näitab konsool, kui väljast kutsuda typeof a ja typeof b IIFE funktsiooni väljast, kasutades var? Kuidas muutub käitumine rangelt režiimis?
sobes.tech AI
Vastus AI-lt
If variables are declared with var inside an IIFE, for example:
(function() {
var a = 10;
b = 20; // without var
})();
console.log(typeof a); // "undefined"
console.log(typeof b); // "number"
The variable a, declared with var inside the function, is local and not accessible outside, so typeof a will return "undefined".
The variable b, declared without var, let, or const, in non-strict mode, leads to the creation of a global variable. Therefore, typeof b will return "number".
In strict mode ('use strict';), attempting to assign a value to an undeclared variable (b = 20;) will cause a ReferenceError, and the global variable will not be created. Thus, outside the function, both variables will be inaccessible, and typeof a and typeof b will return "undefined" (or an error will be thrown earlier).