Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function parameter scope in javascript

Tags:

javascript

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.

like image 863
Sam Avatar asked Jan 25 '17 19:01

Sam


People also ask

What is the scope of a function parameter JavaScript?

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.

What is the scope of a function parameter?

Local variables have their scope to the function only in which they are declared, while global variables have scope to the program and they can be accessed by any function in the program.

What are function parameters in JavaScript?

Function parameters are the names listed in the function definition. Function arguments are the real values passed to (and received by) the function.

What is function scope and block scope in JavaScript?

Function scoped variables: A function scoped variable means that the variable defined within a function will not accessible from outside the function. Block scoped variables: A block scoped variable means that the variable defined within a block will not be accessible from outside the block.


2 Answers

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.org/en-US/docs/Web/API/Window/name for details.

like image 71
user3413723 Avatar answered Oct 16 '22 05:10

user3413723


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.

like image 26
Ben Aston Avatar answered Oct 16 '22 06:10

Ben Aston