243 views
What is the output in the console when calling typeof a and typeof b outside the IIFE code with var? How does the behavior change in strict mode?
Asked at
AI answer
If variables are declared inside an IIFE using var, for example:
(function() {
var a = 10;
b = 20; // without var
})();
console.log(typeof a); // "undefined"
console.log(typeof b); // "number"
Variable a declared with var inside the function is local and inaccessible outside, so typeof a will return "undefined".
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 throw 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 before this).
Also asked at Ifellow
- Tell us about yourself, your experience, and your recent projects.
- [name] asked: why did you decide to change your job?
- Please tell us about your experience: what tasks do you solve, what is your area of responsibility, what technologies have you worked with, and how are the team processes organized?
- Tell about generics in TypeScript: what are they and how do you use them in your work?
- Briefly tell us about yourself: what should we know about you?
Similar questions
- What will be logged to the console in the example with variables, functions, and block scope?
- console.log(allo); var allo = 'Я var'; function allo() { console.log('Я function declaration'); } console.log(allo); Explain the output of this code snippet.
- What is an IIFE (Immediately Invoked Function Expression), and what kinds of function declarations are there in JavaScript?
- How does strict mode affect the value of 'this' when calling a function?
- What is IIFE (Immediately Invoked Function Expression)?