简体   繁体   中英

JavaScript Global variable value changes on Function value

Why am i getting two different results from the below code. The only change i am doing is passing the value to a function, in first code i am getting the value of global variable "count" as 10 and in the second code the global variables("count") value changes to 30.

  function addTen(count) { count = count + 20; return count; } var count = 10 var result = addTen(count); console.log(count); //10 console.log(result); //30 

  function addTen(num) { count = num + 20; return count; } var count = 10 var result = addTen(count); console.log(count); //30 console.log(result); //30 

In your second function, the statement

count = num + 20;

assigns to the global variable (it's the only count in scope). To make it a local variable for the function scope only, and not affect the global, use

var count = num + 20;

In your first function, the parameter count implicitly declares such a local variable, shadowing the global variable of the same name.

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