Five small examples to help you understand JavaScript core closures and scopes

  • 2020-03-30 04:02:20
  • OfStack

Here are five small scripts to help you really understand the JavaScript core closures and scopes. Before running on the console, try to answer what pops up in each case, and then you can create a test file to check your answers. Are you ready?

1.


 if (!("a" in window)) {
     var a = 1;
 }
 alert(a);

2,

 var a = 1,
     b = function a(x) {
         x && a(--x);
     };
 alert(a);

3,

 function a(x) {
     return x * 2;
 }
 var a;
 alert(a);

4,

 function b(x, y, a) {
     arguments[2] = 10;
     alert(a);
 }
 b(1, 2, 3);

5,

 function a() {
     alert(this);
 }
 a.call(null);

My predicted answers are: undefined, 1, unknown, 10, and null

The answer is at the end of this article. Dare you leave your guess before looking at the answer?

 

 

 

The right answer: 1. Undefined&awards;   2, 1     Function a(x){return x * 2}    4, 10   5, window] [object


Related articles: