Your variable is a global variable so it can be accessed or set from anywhere in your code. In a web browser there are many global variables which are objects with functions. These are good mainly for storing data.
A function on the other hand can be used to execute a block of code or return an object.
For example, you can define a function to extract text from a string. This function will parse the R(red)G(green)B(blue) parts from a string representing a color in either Hexadecimal, RGB or RGBA format.
function getRGB(color) {
var Rhex, Ghex, Bhex;
var R8bit = null;
var G8bit = null;
var B8bit = null;
var IsHex = false;
if (color.match(/rgba?\((\d{1,3}),\s(\d{1,3}),\s(\d{1,3})/)) {
Rhex = RegExp.$1;
Ghex = RegExp.$2;
Bhex = RegExp.$3;
}
else if (color.match(/^\s*#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\s*$/i)) {
Rhex = RegExp.$1;
Ghex = RegExp.$2;
Bhex = RegExp.$3;
IsHex = true;
}
else if (color.match(/^\s*#?([0-9a-f])([0-9a-f])([0-9a-f])\s*$/i)) {
Rhex = RegExp.$1 + RegExp.$1;
Ghex = RegExp.$2 + RegExp.$2;
Bhex = RegExp.$3 + RegExp.$3;
IsHex = true;
}
else {
return (NaN);
}
if (IsHex) {
R8bit = parseInt(Rhex, 16);
G8bit = parseInt(Ghex, 16);
B8bit = parseInt(Bhex, 16);
} else {
R8bit = parseInt(Rhex);
G8bit = parseInt(Ghex);
B8bit = parseInt(Bhex);
}
return [R8bit, G8bit, B8bit];
}
Now I can use that function from another function, for example to darken or lighten the color by increasing or decreasing the RGB components of the color:
function darken(color) {
var rgb = getRGB(Color);
return [Math.Max(rgb[0]-1,0), Math.Max(rgb[1]-1,0), Math.Max(rgb[2]-1,0)];
}
Or to lighten a color:
function lighten(color) {
var rgb = getRGB(Color);
return [Math.Min(rgb[0]+1,255), Math.Min(rgb[1]+1,255), Math.Min(rgb[2]+255,0)];
}
I can also declare variables and functions inside of a function:
function myColorHelper(e)
{
var el = $(e);
var myColor= function() { return el.css("color"); };
var myrgb = function() { return getRGB(mycolor);};
var makeDarker = function() {
var darker = darken(myrgb());
el.css("color", "rgb(" + darker[0] + ", " + darker[1] + ", " + darker[2]);
};
var makeLighter = function() {
var lighter = lighten(myrgb());
el.css("color", "rgb(" + lighten[0] + ", " + lighten[1] + ", " + lighten[2]);
};
}
Plugins and frameworks are full of functions which allow us to use functionality in our code. For example, I could use jQuery with these functions to darken or lighten the color of an element on a webpage.
var helper = myColorHelper($('#myElement'));
helper.makeLighter();
helper.makeDarker();