0%

JavaScript Basics

JavaScript Basics Summary (Hoisting, Strict Mode)


Rules for Variable and Function Hoisting

  • Variable hoisting: Execution still happens in order; variable declarations are hoisted but assignments are not.
  • Function hoisting: The entire function body is hoisted to the top of its scope.
  • Priority: Function hoisting > Variable hoisting.
1
2
3
4
5
6
7
console.log(a); // undefined
var a = 2;

foo(); // works normally
function foo() {
console.log("Function hoisting succeeded");
}

Using Strict Mode with use strict

What it does:

  • Prevents creating accidental global variables;
  • Disallows using undeclared variables, helping avoid memory leaks;
  • Binds this to undefined by default instead of window.
1
2
3
4
5
6
7
function foo() {
"use strict";
console.log(this.a); // ❌ TypeError
}

var a = 2;
foo(); // in strict mode, this is undefined, so this.a cannot be read

1
2
3
4
5
6
7
8
9
10
(function() {
"use strict";
foo(); // calling foo here doesn't change its default binding
})();

function foo() {
console.log(this.a);
}

var a = 2;
-------------本文结束感谢您的阅读-------------