admin管理员组

文章数量:1327488

What is the scope of function parameter in Javascript

var greetFunc = function(name){
var something;
}

console.log("Hello" +name);
console.log(something);

I understand the scope of something is just inside the function, it will not exist outside that. But what about name. Why the value is blank for name variable.

What is the scope of function parameter in Javascript

var greetFunc = function(name){
var something;
}

console.log("Hello" +name);
console.log(something);

I understand the scope of something is just inside the function, it will not exist outside that. But what about name. Why the value is blank for name variable.

Share Improve this question asked Jan 25, 2017 at 19:53 SamSam 1892 silver badges10 bronze badges 3
  • What do you see? What did you expect to see? – Bergi Commented Jan 25, 2017 at 19:58
  • Possible duplicate of stackoverflow./questions/30748819/… – DJ. Commented Jan 25, 2017 at 20:01
  • Possible duplicate of JavaScript function parameter and scope – DJ. Commented Jan 25, 2017 at 20:01
Add a ment  | 

2 Answers 2

Reset to default 4

Referencing name outside the function doesn't throw an error like you would expect because it is actually a global variable in every page, part of the global window object. Typing name is the same as window.name.

The something variable causes an error because it hasn't been defined yet. However, the name variable doesn't cause any problems because it is blank by default, at least in Chrome. You are correct that variables created in a function don't exist outside it.

See https://developer.mozilla/en-US/docs/Web/API/Window/name for details.

The parameter name is similar to declaring a variable name at the top of the function.

So the scope of a parameter is the function it is a part of.

本文标签: Function parameter scope in javascriptStack Overflow