You have done this right, in a sense. What you first set up was a global variable
var msg = 'hello';
you then defined a function with scope to that variable
function change(){
msg = 'byebye';
}
and then you tested:
alert(msg);
However, what you never did was call your function. When you define a function you need to call it for its code to run, like this:
change();
alert(msg);
Some function tips
Use a closure
If you want to look at best practices for this situation, I would suggest not using the global namespace. You can do that with what is called a closure. It basically wraps the local scope of a function around your code. Child functions inside of this scope share scope.
(function(){
var msg = 'hello';
function change(){
msg = 'byebye';
}
change();
alert(msg);
})();//Wrapping the function in () and then using () on it will cause it to run the code without being called
Not only will this leave the global namespace alone, it will allow for the memory allocated to variables inside of the closure - the function we wrapped the code in - to be collected faster because they are out of scope once the closure's code is finished executing.
Note that with the function change declared in the closure, it will not be available to access in the global scope. If you wanted it available in the global scope it would not make as much sense to do it in this fashion.
Allow for the function to have the change passed in to it by argument
Inside of the () area for a function is where arguments can be passed in. In javascript, their type is dynamic. Using function change(newMessage) means that you can use the newMessage variable inside of the function. It is implicitly locally scoped. This will allow for all sorts of different messages, by passing in the new message change('byebye'); like this:
(function(){
var msg = 'hello';
function change(newMessage){
msg = newMessage;
}
change('byebye');
alert(msg);
})();
change();beforealert(msg);:) Example: jsfiddle.net/MUvdp