JavaScript

global variable, local variable

Naranjito 2021. 1. 7. 13:43

1.

var a // global variable

funtion aaa(){

var a // local variable

}

 

2. 

var a // global variable

funtion aaa(){

var a //local variable

a // global variable because there is no var

 

3.

var a // global variable

funtion aaa(){

var a //local variable

alert(a) //it returns local because it calls the nearest one

 

4.

var a // global variable

funtion aaa(){

alert(a) //it returns global 

 

5. 

var a // global variable

funtion aaa(){

a // global

 

6.

var a // global variable

funtion aaa(){

var a //local

a // local because it affected by local var a

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="greeting.js"></script> //when the web browser encounters a tag called script, it checks if there is "greeting.js" attribute(src) or no
    //and then if there is any value in the attribute, reading the corresponding file
    //and then it has the same effect as putting it inside here<script></script>
    <title>Document</title>
</head>
<body>
    <script>
        function get_name(){
            return ['aaa123','bbb456','ccc789'];
        }

        members=get_name()
 
        for(var i=0;i<members.length;i++){
            document.write(members[i].toUpperCase()+"br />");

        }
        
        var grades={'aaa123':10,'bbb456':20,'ccc789':30}; //this is an object which is always nested with {}
        for(key in grades){
            document.write("<li>key"+key+"value"+grades[key]+"</li>")
        }

        var grades={
            'list' : {'aaa123':1  0,'bbb456':20,'ccc789':30}, //within the object grades, there is 'list'key and key contains value which is an another object
            'show' : function(){
                alert('hello world');
                alert(this); //this is a variable which is point to object which function belongs, in other words, this is grades

            }
        }
        alert(grades['show']());

        var vscope = 'global';//global variable which accessible throughout the javascript
        function fscope(){
            var vscope = 'local'; //local variable which can be accessed only inside {}
            //alert(vscope); //vscope returns 'local' because it recalled the nearest one
            //if there is no vscope variable, then this will be returned 'global'
            vscope = 'local'; //this is global variable because there is no var if there is no var vscope
            //if there is var vscope, then this is a local variable because it affected by local var vscope
            var lv = 'local variable'; //local variable
        }
        alert(lv); //cannot be executed because lv is local variable

        function fscope2(){
            alert(vscope);
        }
        


    </script>
</body>
</html>