Home > Web Front-end > JS Tutorial > body text

JavaScript variable scope analysis (code example)

青灯夜游
Release: 2018-10-23 17:32:59
forward
1953 people have browsed it

What this article brings to you is JavaScript variable scope analysis (code example). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Variables are divided into two types: local variables and global variables

Let’s look at the following example:

var myVariable = 'global';
myOtherVariable = 'global';

function myFunction(){    
    var myVariable = 'local';    
    return myVariable;
}

function myOtherFunction(){    
    myOtherVariable = 'local';    
    return myOtherVariable;
}


console.log(myVariable); //{行1}    global
console.log(myFunction()); //{行2}   local

console.log(myOtherVariable); //{行3}   global
console.log(myOtherFunction()); //{行4}   local
console.log(myOtherVariable); //{行5}  local
Copy after login

Line 1 outputs global because it is a global variable;

Line 2 outputs local, because myVariable is a local variable declared in the myFunction function, so the scope is only in myFunction;

Line 3 outputs global, because we initialized the global variable myOtherVariable in the second line ;

Line 4 outputs local. In the myOtherFunction function, there is no modification of the keyword var, so the global variable myOtherVariable is referenced here and copied loacl;

Local is output in line 1. This is because in The value of myOtherVariable has been modified in line 4;

The above is the detailed content of JavaScript variable scope analysis (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template