How to define variables in JS, three methods, three scopes

Three ways to define variables in JavaScript

There are roughly three ways to define variables in JavaScript, using the var and let keywords, and not using keywords. The scopes of these three declared variables are different, and they will be introduced one by one through examples below.

The var keyword defines JS variables

Variables declared with the var keyword have function-level scope:

<script>
  {var b = 1}
  function addone(a){
    return a+b
  }
  alert(addone(1))
</script>

let keyword defines JS variables

Variables defined through let are usually only visible in the code block in which it is declared (and any code block that contains this code block) [Click the Try button to enter the online editor, and then click Run (there will be no reaction, it will not be like the above) There is also a window pop-up in the example), you can observe the difference between let and var]:

<script>
  {let b = 1}
  
  function addtwo(a){
    return a+b
  }
  alert(addtwo(2))
 
</script>

Variables declared without keywords

Variables declared without any keywords will automatically be converted into global variables. In the example below, a global variable is declared inside the function, and then this variable will be accessed outside the function:

<script>
  function addthree(a){
    b = 3
    return a+b
  }
  c = addthree(2)
  alert(b)
 
</script>

 Original text:How to define variables in JS, three methods, three scopes

Disclaimer: Content is for reference only.

Guess you like

Origin blog.csdn.net/weixin_47378963/article/details/134599528