简体   繁体   中英

Not able to understand the output of javascript function

I am getting 5 as the output of following code

 function myfunction1(){ number = 5; } function myfunction(number){ number = number + 10; } myfunction1(); myfunction(number); console.log(number); 

I expected to throw a reference error for number . It would be great if someone can explain the behavior.thanks in advance

By never declaring number , the javascript interpreter is evaluating number as global variable.

If you do:

 function myfunction1(){ var number = 5; } function myfunction(number){ number = number + 10; } myfunction1(); myfunction(number); console.log(number); 

This should throw you an error, since now, number=5 is only true inside myfunction1

Because you have same names for global variable and function argument you are assigning to an argument.

This should work.

 let number; function myfunction1(){ number = 5; } function myfunction(n){ number = n + 10; } myfunction1(); myfunction(number); console.log(number); 

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