Global vs local variables


#1

Hello my friends, I'm not understanding anything ! HELP..

var my_number = 7; //this has global scope

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

Oops, try again. Make sure you used the 'var' keyword inside the function


#2

Why did you change the name of the variable from my_number to timesTwo? Just press reset and add the var at the explained position. This exercise is not difficult from the coding aspect. The interesting thing is that the output changes when you add the var and I guess the reason is explained in the exercise.


#3

Hi, moderator. I'd like to thank you, but I missed sthg else! :blush:

var my_number = 7; //this has global scope

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

Oops, try again. Make sure you used the 'var' keyword inside the function!

I did'nt ??????????????????????????????????????????????????


#4

Now you changed both to my_number ...
As said just press reset and add one var before my_number inside the function. That's all.


#5

WOWWW. You GREAT!!! :relaxed:


#6

As said the idea behind this exercise is not something difficult concerning coding. But the introduction in local and global variables and far more interesting than adding a var is the fact what it does. Because without the var you have one global variable my_number that you access inside the function and outside of it. And by using var inside of the function you create a second variable with the same name which leads to the effect that inside of the function you change the inner one and outside of it you change the outer one and although they share the same name there is no connection between them. This might be a little hard to grasp and is probably the reason why the exercise itself is pretty easy.


#7

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

this is my code it is not working


#8

What is the error message? Did you try to reset the code and just add the var or refreshed the page?


#9

yes i refreshed it and it works now thank you


#10

my code is
var my_number = 7; //this has global scope

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

error message: SyntaxError: missing before statement


#11

This part seems to be ok, also don't over complicate this par all you need to do is to add a var on line 4 not need to rename the variable or anything. The interesting part is what follows doing so not the coding itself.


#12

Thanks! It's now working! n_n :heart_eyes: