- Writing JavaScript
- Naming Rules and Conventions
- A Weakly Typed Language Means That JavaScript Is Smart
- Summary
Naming Rules and Conventions
All the rules for naming functions and variables discussed previously in the section on case sensitivity apply. If you name your variables or functions beginning with any letter in either uppercase or lowercase or with an underscore or dollar sign, the name is considered legitimate. For the most part, in naming variables, avoid using dollar signs as the first character because they can be confusing to Basic programmers, who might associate the dollar sign with a string variable, or PHP programmers, who begin all variables with a dollar sign.
You cannot have spaces in the names that you use for variables or functions. Many programmers use uppercase letters or underscores to make two words without a space. For example, the following are legitimate variable names where a space might be used in standard writing:
Bill_Sanders= "JavaScript guy";
BillSanders= "JavaScript guy";
Free$money="http://www.congame.html";
Whether to use an underscore or a cap to begin a new word in a variable or function name is your own preference.
Reserved Words
Reserved words are those in JavaScript that have been reserved for statements and built-in functions. If you use a reserved word for a variable or function name, JavaScript might execute the statement or function for the reserved word and not your variable or function. For example, if you use the reserved break for a variable name, JavaScript might attempt to jump out of a loop. Table 2.1 shows a list of current and future JavaScript reserved words.
Table 2.1 Reserved Words
abstract |
final |
public |
boolean |
finally |
return |
break |
float |
short |
byte |
for |
static |
case |
function |
super |
catch |
goto |
switch |
char |
if |
synchronized |
class |
implements |
this |
const |
import |
throw |
continue |
in |
throws |
debugger |
instanceof |
transient |
default |
int |
true |
delete |
interface |
try |
do |
long |
typeof |
double |
native |
var |
else |
new |
void |
enum |
null |
volatile |
export |
package |
while |
extends |
private |
with |
false |
protected |
|
You should also try to avoid words that you will find used in statements, methods, and attributes. For example, name and value are attributes of forms and should be avoided. As you learn more JavaScript, try to avoid the new words that you learn as names for variables and functions.