Some simple question on global vs local variables


#1

So just to be sure, in this exercise about global vs local (see below, in bold), it is not explicitly stated, but when we put the var before the my_number inside the timesTwo function, it redefines the variable but only inside the function. This I get it. But when we remove this var before my_number in the timesTwo function, it redefines it entirely and globally, even outside the function where it is updated, right?

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


#2

if you don't use the var keyword, you updated your global variable from line 1


#3

Right, thanks! Took me a while to figure that out, bc so far I thought the code in functions could not alter code outside it.


#4

that depends on your definition of altering, in javascript a global variable inside a function can update a global variable


#5

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