简体   繁体   中英

Assign a variable as a function parameter with the same name

I cant get why this isn't correct:

let a=5
a = a
//so there are no errors here. In the last statement javascript replaces the left side with a value, and that's it

Now if I write this:

let a=5
function hey(a=a){
return console.log(a)
}
hey()

This will return undefined, so the argument a=a does not get evaluated to a=6


The use case for having the same variable name is that I'd like to create a section in the beginning of the script with variables, and use the same names than I use in the functions later on.

In the first example, you have one variable named a . You can assign the value to a to a . This is pointless, but possible.

In your second example, you have two different variables both named a which exist in different scopes. Inside the function declaration, a refers to the local variable a and not the global variable a . When you try to use a as the default value, it reads the locally scoped a which is undefined .

Use different names if you want to do that. It probably makes sense to organise them in an object too.

 const default_values = { a: 5 }; function hey(a = default_values.a) { console.log(a); } hey();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM