Global vs. Local Variables


#1


https://www.codecademy.com/en/courses/javascript-beginner-en-6LzGd/2/2?curriculum_id=506324b3a7dffd00020bf661

So I understand why SCENARIO 2 creates the answers 14 and 7 but why does SCENARIO 1 create answers 14 and 14? Specifically, why does the outside answer in SCENARIO 1 still create an answer of 14? shouldn't it be 7 since it's pulling "my_number" from line 1? and shouldn't be able pull from within the function?

Thanks in advance for your help!


//SCENARIO 1

var my_number = 7; //this has global scope

var timesTwo = function(number) {
    my_number = number * 2;
    console.log("Inside the function my_number is: ");
    console.log(my_number);
}; 

timesTwo(7);

console.log("Outside the function my_number is: ")
console.log(my_number);

//__________________________Versus_____________________________

//SCENARIO 2

var my_number = 7; //this has global scope

var timesTwo = function(number) {
    var my_number = number * 2;
    console.log("Inside the function my_number is: ");
    console.log(my_number);
}; 

timesTwo(7);

console.log("Outside the function my_number is: ")
console.log(my_number);


Global/Local Variables code not working?
#2

HI the diif between the two come from these lines

#SCENARIO 1

my_number = number * 2;

#SCENARIO 2

var my_number = number * 2;

Like you can see one have the var the other doesn't so I'm not so sure.. But I think that the one that doesn't have the var use the global variable (my_number) to store

number * 2;

so that why when you print it.. it's the same output of the one inside the function so when you declare in a function a viariable with var it cannot be accesse outside the function.


#3

Hi Ryan,

What you are seeing is one of the differences of not using/using the var keyword.

Understanding scope - for complete knowledge

JavaScript follows lexical scoping i.e. scoping inside of a function. Variables created inside a function (that's a scope) A, are accessible in A, as well as functions inside A. But the variables are not accessible outside of the function A.

/* This is global/outermost scope - outside every function*/
var z = 100;  // accessible everywhere

function a(){
    var x = 5; // accessible in `a` and `b`

    function b(){
        var y = 5; // accessible only in `b`
        x = 10; // x accessible
        z = 20; // z accessible
    }
}

console.log(z); // 100
console.log(x); // ReferenceError! - not accessible

When you use the var keyword

var new_var = "Hello World!";

JavaScript creates a new variable in the current scope, simple enough.

When you DO NOT use the var keyword

new_var = "Hello World!";

If the variable has been declared using the var keyword, in the current or parent scope, this statement will update its value.

Follow the steps 1,2,3,4, inside out given in the code below:

// (3) z declaration found here 
var z = 100;

function a(){
    // (2) z declaration not found here
    // search in parent scope again

    function b(){
        //  (1)`z` declaration is not found in function `b`
        // so search in parent scope
        z = 20;
    }
    
    b();
}

a();

Coming to your question

As you can see here,

var my_number = 7; // this has global scope

var timesTwo = function(number) {
    my_number = number * 2;
    console.log("Inside the function my_number is: ");
    console.log(my_number);
};

this assignment operation lacks the var keyword:

my_number = number * 2;

so JavaScript will search for my_number declaration in the parent scope(s), and find this:

var my_number = 7;

the variable hence found will be updated.
Note that NO new variable is created inside of function timesTwo. The existing my_number variable, present in global scope, will be updated.


Can you now guess the answer to your question? :wink:


#4

@cssace98482

What you have to realise....

.is that, after starting your Browser you are entering the so-called

GLOBAL-scope . . .GLOBAL-bubble

and as you execute a FUNCTION, the code in the FUNCTION-BODY is executed in it's

LOCAL-scope . . . . LOCAL-bubble

=======================================

In this exercise you are declaring 2 variables in the GLOBAL-scope (outside of the NAP-function )

var tired = true;
var bored = false;

you can define a =function= which takes NO parameters
like

var nap = function() {
              //Begin of FUNCTION-BODY you are in the LOCAL-scope
          }

and from within the FUNCTION-BODY / LOCAL-scope you can reach out, into the GLOBAL-scope
where you can get access to Boolean VALUES of the variables tired and bored

============================

Now read the FUNCTION talk is in a separate POST

============================

Now you defined the nap =function= as having 2 parameters tired and bored
as these tired and bored parameters
are used as tired and bored LOCAL variables
you will NOT have access to the GLOBAL variables tired and bored

AND

as you are calling the nap =function= which has 2 parameters defined
you will have to provide 2 arguments,
otherwise the tired and bored varaibles within the LOCAL-scope are undefined

Conclusion::

Create the nap =function= with NO parameters.

Reference

google search
== the Book ==
javascript [your question] site:developer.mozilla.org
javascript logical operators site:developer.mozilla.org

== discussions / opinions ==
javascript [your question] site:stackoverflow.com

== guidance ==
www.crockford.com
http://javascript.crockford.com/code.html <==coding convention
http://javascript.crockford.com/survey.html
http://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript
https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
www.developer.mozilla.org/en-US/docs/Web/JavaScript/Guide
http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname?rq=1


10. Global vs Local Functions: Putting the Var in the Function
10) Global vs Local var - alternate solution
#5

@cssace98482,
Some more....

//not possible
//var window.global1 = "window_global";

window.global1 = "<window_global1>";

this.global2 = "<this in window-scope global2>";

var my_1st_function =function(global1) {
    //global1 is now a =local= VARIABLE
    // in this function-body
    console.log("output =local= global1:: ",global1);
    console.log("output =this=  global1:: ",this.global1);
    console.log("output =window= global1 ",window.global1);
};
my_1st_function("<function global1 argument>");

== discussion /opinions ==
http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work


#6

You guys are awesome thanks for the detailed answered!


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.