10/13 - quick question about local Vs. global variables


#1

Very easy exercise, however I am curious about just one little detail in the code:

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

Are variables always done outside of brackets/curley braces, and if so, what defines a local Vs. a global variable? I mean, here, both are outside of any parentheses. Is the second local because it is directly followed by something, and the first has nothing afterwards? Or is the first considered global because it is entered before the second?

I guess it doesn't really matter but I'm just curious as to what makes the first global.

Also, in "real" javascript, would each have a seperate tag such as globalVar/localVar, making global and local variables easier to identify, or is it done as is presented in this exercise?

Thanks!


#2

In programming, scope is what defines where a variable is accessible or relevant. In most languages the { curly brackets } define a new scope. Things inside those brackets are usually not accessible from outside them and vice-versa. When you close the { curlies }, any variables in there essentially die. On the subject of order, the last assignment to a variable is considered the most up to date.

Saying;

var my_number = 7;
var my_number = 8;

console.log(my_number); // This will output 8

And,

var my_number = 6;
var scope_example = function() {
var my_number = 3;
console.log(my_number); //output of 3
}

scope_example(); // will output 3

console.log(my_number); // output of 6


#3

Correct just in JS only functions have their own scope.