

Here are some practical examples of scoping, which you can also find in the companion code in the scope1.html file: Function parameters are scoped locally to the function as well. This effectively means that the values of those variables cannot be accessed outside the function. Variables defined within a function are scoped solely within that function. In the context of a webpage-or a document, as you might think of it-you can access and use a global variable throughout. A globally scoped variable can be accessed throughout your JavaScript program. Variables are globally scoped when they are used outside a function. Consider this example, where the variable x first holds an integer but then, through another assignment, it changes to hold a string: var x = 4 Ī variable’s scope refers to the locations from which its value can be accessed. You can also change the type of data being held within a variable through simple reassignment. It’s not necessary to declare whether a given variable will hold an integer, a floating point number, or a string. Variables in JavaScript are not strongly typed. These can be initialized on the same line, too: var x = 1, y = "hello", zeta = 14 Variable types You can declare multiple variables on the same line of code, as follows: var x, y, zeta For more information about keywords or reserved words in JavaScript, refer to Chapter 3. Whereas the first three variable names are invalid because characters are used that aren’t valid at all (or aren’t valid in that position, as is the case with the first example), the last variable name, var, is invalid because it uses a keyword. The following variable names are invalid: var 1stCounter Variables cannot contain spaces or other punctuation, with the exception of the underscore character (_). Variable names can contain uppercase and lowercase letters as well as numbers, but they cannot start with a number. The following are all valid variable declarations: var x Variables are declared in JavaScript with the var keyword. This section formalizes the use of variables in JavaScript. You’ve seen several examples of declaring variables throughout the previous chapters of this book. Variables store data that might change during the program’s execution lifetime.

Variables should be familiar to programmers in just about any language.
