Introduction to Programming Page 2 |
Variables: The Tupperware of Programming
No matter what language you're working with, you'll always use variables. Variables are like saved documents on your computer, each one storing information. When you name a variable you are actually declaring or defining it. The values stored in them can then be applied to functions (I'll get to them later on). In JavaScript, for example, variables can hold letters, numbers, and Boolean (true or false) values. If you want to access the information that a variable has stored in it, all you have to do is call the variable's name. The process of naming a variable is unique to the programming language, but a few universal rules hold true. First, never give a variable the same name as a function; this can cause confusion. You can easily lose track of which is doing what. Second, make sure the names are descriptive. Stay away from abstract names so that when you or someone else goes back over the code, the purpose of the variable isn't misunderstood.
You may have to define variables before defining the function that you call them in, depending on the language you're using. In JavaScript, it's always good practice to go ahead and define them beforehand to prevent having to root through a bunch of code to see what isn't defined. They can be defined between the head tags or in the body.
Scope of variables
The scope of a variable refers to when and where a variable can be used, and they fall into two groups: local and global. Local variables are used most often in user-defined functions. If you try to call a local variable outside of its specific function, you will either get an error or the computer will evaluate the global variable instead (if the local variable has the same name as a global variable). The scope of a global variable is anywhere at any time. They exist outside of any functions regardless of whether they are called in one. A great example of these two types of variables is the var command used in JavaScript.You can create new variables with var. If you had a function named "Squiggly" and you used var to define the variable "Gobbledygook" within it, Gobbledygook would be a local variable, and would only be relevant inside Squiggly. Now, if you used var to define a variable called "Gibberish,", just by itself with no association to a function, it would be a global variable. It's not specific to one function but rather can be applied to any function at any time. An important thing to note is that global variables take precedence over local variables. So, if you call Gobbledygook within Squiggly, but there is also a global variable with the same name being applied to the function, the value of the global variable will be evaluated instead. Take a look here for details about this.
BreBru.com Information Technology HTML