10. Global Vs. Local Variables - Question


#1


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


I understand the Global vs. Local, but I did have a question on just the Global. If I don't put a var in the function, then I'm using the Global myNumber variable. And since I'm using the Global myNumber variable, if I put a number like 2 as the parameter, then the it updates the Global from 7 to 4, right?


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(2);

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


#2

yes, you understand it right. This line:

my_number = number * 2;

updates the global variable, if you would use the var keyword it would be a local variable


#3

Think of a room with a two-way mirror, except this one allows us to look out, but not in. The occupants of the room can see everyone outside, but those outside cannot see in. What we see outside is 'global'. What the outside cannot see is 'local', everything inside the room.

Information can be passed into the room (through the glass) for processing, and the result passed back out of the room through a return slot. The workings inside, everyone outside is oblivious of. That is except for reference objects, arrays, objects and functions. They cannot be shown through the glass so a pipeline to them has to be put in place. The inside and the outside are looking at the same object, even though it be by a different name in the room. It's the one object being manipulated in the room, and the outside can watch, although from their side only.


#4

2 posts were split to a new topic: 10. global vs local


#5

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