Front-end interview question: Please explain what is the scope of a function?

I solved a question today: Please explain what is the scope of a function?

My answer is:

The scope of a function refers to the data space created after the function is executed internally. Within the scope of the function, the validity period of the variables defined by let is the function scope.

AI thinks my answer is relatively simple: the answer is basically correct, but more details can be added to improve the quality of the answer.

I just wanted to check what function scope is in JavaScript.

After verification, the front-end inspection scope mainly inspects an exception, that is, the variable defined in the block within the function may be raised to the function level, such as the following golang example

var a = 1

func TestScope(t *testing.T) {
	//测试golang的作用域
	t.Log("a=", a)
	if true {
		var a = 2
		t.Log("a=", a)
	}
}

Prints as:

test.go:29: a= 1

test.go:32: a= 2

When printing for the first time, a should be the a defined in the first line of the global, so print 1

The second time, an a is defined in the independent scope of if, covering the global a, so the second print, a=2

Let’s look at the corresponding javascript version

var var_a = 1
function test_Scope(){
	console.log(var_a)
	if (true){
		var var_a = 2
		console.log(var_a)
	}
	logc()
}
var var_a = 1
function test_Scope(){
	console.log(var_a)
	if (true){
		var var_a = 2
		console.log(var_a)
	}
}
test_Scope()

Printing is:

When printing for the first time, according to other languages, it should still be global 1, but because JavaScript puts all the variables defined in the function into a unified function scope, at this time, the runtime thinks var_a already exists, but it has not been assigned a value.

The same problem also exists in the loop

for (var i = 0; i < 10; i++) {    
    console.log(i);    
}    
console.log(i);  // 10 i只是for里面的函数,按道理在这里应该是undefined

And the let I answered does exist to solve this problem:

Let’s look at the let version of the above program

let var_a = 1
function test_Scope(){
	console.log(var_a)
	if (true){
		let var_a = 2
		console.log(var_a)
	}
}
test_Scope()

Printing becomes

This is consistent with the definition of other languages.

So if I answer again, I think I should answer like this:

The scope of a function refers to the data space created after the function is executed internally. Within the scope of the function, variables defined by var have the same common scope. Variables defined by let have only block definition domains, starting from the definition statement and ending with ends with braces. When writing programs, you should pay attention to the differences between JavaScript and other languages ​​to avoid definition inconsistencies.

Guess you like

Origin blog.csdn.net/baijiafan/article/details/133036138