-
Notifications
You must be signed in to change notification settings - Fork 52
JavaScriptBasics
##Chapter 02 - JavaScript Basics
It is time to begin exploring the JavaScript language itself. A good place to begin is by exploring the type system.
If you already know a good deal about programming then you will probably find a discussion of the type system inherently interesting. Newcomers to the topic, however, may have a hard time understanding exactly why they need to know about the type system. Isn't there something more interesting or exciting that we can talk about first?
Well, yes, there are more exciting places to begin. But in the end, no programmer can thrive without knowing core topics like a language's type system. It is shere folly to hope for success as a JavaScript programmers without understanding the type system. As a result, I will plunge you into the depths of the subject, and hope that you can keep your head above water.
The point, of course, is that no one can learn to be a good programmer without working on it many hours a day. Only the most disciplined can focus on a subject such as the type system for days on end. So my hope is that you work on other projects that hold you interest, and then come back to your study of the type system on a daily basis, preferrably when you are feeling rested and disciplined.
NOTE: This document is based on the current version of JavaScript. References will be made to the next version, called ECMAScript 6, but this is not the place to discuss that specification.
Blank lines between functions. Use white space to make code more readable.
- WhiteSpace here: http://javascript.crockford.com/code.html
- WhiteSpace here: http://www.mediawiki.org/wiki/Manual:Coding_conventions/JavaScript
##The Type System
Type systems are, oddly enough, fundementally about storage and memory management. The core question we are asking looks like this: When you declare a variable, how does the system store it in the computer's memory? Ultimately, it is best if you know exactly how data is stored in memory, but for now you need only understand the core containers used by JavaScript for storing the data you use in your program. These containers are called types. For instance the number type is used to store numbers. The boolean type is used to store the values true and false.
JavaScript is dynamically typed. If you come from a strongly typed language such as C# or Java, the JavaScript type system may seem simplistic or even poorly constructed. Though it has some serious flaws, the JavaScript type system is both more powerful and more complex than it might seem it first. Nevertheless, a good understanding of JavaScript types is needed by anyone who wants to master the language.
There are two halves to the JavaScript type system:
- Primitive Types
- Objects
We can start by taking a look at the primitive types. In this chapter there will also be some superficial discussion of Objects. In depth discussion of Objects appear in other chapters. In particular:
###JavaScript Primitive Types {#javaScriptSimpleTypes}
There are only five simple (primitive) types in the JavaScript language:
- Number
- Boolean
- String
- Null
- Undefined
A sixth type will be part of the next version of JavaScript:
- Symbol (Coming in ECMAScript 6)
Number, Boolean and String are the work horses of the language. You will use these simple types over and over again.
To create a Number simply write the word var followed by an equal sign and either an integer or a floating point number and a semicolon:
var x = 3;
To create a String, repleat the above operation but assign the variable to a string:
var myString = "Some String";
You can use the typeof operator to determine the type of a variable. Given the following declaration:
var myInt = 3;
Then the following would return the string number:
typeof myInt; // Returns number
The act of assigning myInt to the value 3 sets the type of myInt. There is no way to explicitly declare the type of the variable, but we can use the typeof operator to confirm that assigning 3 to myInt did in fact set the type of the variable to number.
There is no equivalent of the C# Integer, Float or Double types. In JavaScript, we just have the number type, regardless of whether the variable is assigned to a simple integer, or a more complex value such as a floating point number:
var myInt = 5;
var myDouble = 3.05;
Both myInt and myDouble are instances of the JavaScript number type.
The following are considered bad form because the contain what are called "hanging decimal points":
var myDouble = 3.;
var myDouble = .3;
Instead, write something like this:
var myDouble = 3.0;
var myDouble = 0.3;
Here is another example:
var myString = "A String";
var type = typeof myString; // Sets type = string
You can use either single or double quotes:
var myString = 'A string';
var myString = "A string";
Both are legal. This makes it easy to embed quotes in a string:
var myQuote = "He said: 'By golly, I think it's alive!'";
If you want some direction here, I suggest using double quotes for strings, as it makes embedding apostrophe's easier. But there is no functional difference between single and double quotes. This is definitely one of the nice features of the JavaScript language.
Here is a basic example from a program called PrimitiveTypes.js:
var aNumber = 3;
var aString = 'string';
var aBoolean = true;
var aNull = null;
var aUndefined = undefined;
var foo;
console.log(typeof aNumber);
console.log(typeof aString);
console.log(typeof aBoolean);
console.log(typeof aNull);
console.log(typeof aUndefined);
console.log(typeof foo);
If you have installed nodejs and type **node PrimitiveTypes.js" the output of this program is as follows:
number
string
boolean
object
undefined
undefined
##Null and Undefined
There are however two other primitive types, called null and undefined. They are designed to help you know the state of an object.
Note that the type of aNull is object. As mentioned above, the purpose of the null type is to help you know the state of an object. It therefore makes (at least some) sense that the type itself should be an object.
Note that the type of the unassigned variable foo is undefined. Do you see how that works? We don't assign foo to anything: var foo;. When we ask to see its type, the system tells us that foo is undefined. You will see that a lot, especially when you are starting out with JavaScript. The lessson here is simple: when you see that a variable is undefined, that usually means that you haven't assigned any value to it
It is probably best to only use undefined in your program when you want to test if a variable has a value assigned to it. Trying to use it in any other way can be problematic.
The most common use of null is to initialize a variable that you want to assign to an object at some point in the future:
var myObject = null;
You might sometimes also want to pass null into a function or return null from a function:
var myFunc = function(value) {
if (value !== null) {
// handle value here
}
}
var myFunc = function(value) {
if (value < 3) {
return null;
} else {
// Write code here
}
}
To test for undefined we write this:
if (typeof value == 'undefined') {
// handle undefined value here
}
And finally, to end on a humorous note, we can run one of my favorite tests in the JavaScript language:
console.log(undefined == null)
Because it intuitively obvious that the above will return false, it should come as no surprise to learn that it returns true. The most galling aspect of this absurdity is that there is a logical explanation for it: undefined is derived from the type null. Or is it the other way around? When things are this chaotic, can it possible matter? Just for the record, it is not the other way around, but when the JavaScript language decides to degenrate into incoherence, they have a special way of doing it that reminds me that given the right circumstance, anyone with a room temperature IQ or above could create one of the most popular and important computer languages in the world. The moral, of course, is that you should never give up: you simply don't know what fate might have in store for you!
On a more serious note, there is an important lesson here: JavaScript has serious design flaws. The langauge can be used to write good code, but you must step in and actively craft a coherent architecture for your program. If you just "go with the flow" of the JavaScript language, the result will be disaster. You have to impose order on the chaos that is JavaScript. This is a difficult task, but it can be done.
###Null vs Undefined
The difference between null and undefined is a subtlety of the JavaScript language that we probably could have done without. Perhaps there will be a day when I see why it is useful, but right now, I would say that language would have been better without undefined. The single keyword null would have been enough for my purposes.
###Immutable
You may have read that JavaScript primitive types are immutable. If you are a beginner, and have read about immutable JavaScript types, my suggestion is that you simply forgot that you read it. You should also skip the rest of this section. I say this because the subject is arcane in the extreme. It is not necessary for beginners to understand what it means to say that a primitive type is immutable.
Consider the following example:
var myString = "My String";
myString = "A new string";
The code shown above is entirely valid. It behaves exactly as you would expect it to behave.
You cannot, however, write the following code:
var myString = "Fury";
myString[0] = "B";
That code does not behave as expected because JavaScript strings are immutable. The variable **myString ** is not immutable, however, the value assigned to it is immutable.
###No Properties for Primitive Types {#primitiveProperty}
If you access a "property" of a primitive type you are actually setting off a complex chain of events. Again, this is a subject that beginners need not understand. In fact, even intermediate JavaScript developers are probably better off not knowing about this subject. It can cause a developer to fret about performance when such concerns are simply not warranted.
Consider the following code:
var myString = "My String";
var length = myString.length;
The above code looks simple enough, but behind the scenes a bit of sleight of hand takes place. The variable myString is converted from a primitive type into an object and then back into a primitive type. The following is pseudo code showing something of what happens behind the scene:
myString = new String(myString); // Create a String object from the primitive type.
var length = myString.length; // Access a property of the String object.
var myString = myString.value(); // Magically convert back to a primitive type.
It is always upsetting for developers to know that this thing kind of thing is taking place. My strong suggestion, however, is that you just ignore it. Other languages, such as C#, do similar things, and 99.99 percent of the time it works out just fine. Only in very rare circumstances does it end up actually be the source of significant performance proplems in your code.
I realize how snobby this sounds, but I will say it anyway: It is usually amateur programmers who worry about this kind of thing. I'm referring to programnmners who think they are lot smarter than they really are. Unless you have reached the stage in your career where you are no longer flattered or irritated by the constant and overwhelming sound of people telling you how brilliant you are, then you probably aren't ready to worry about problems like this.
##Writing Code
We have said enough about the type system for now. Let's move on to a discussion of how to write and structure your code. For now we will focus on the basics. In later chapters you can dig into the details.
There are two fundamental, low level, building blocks for programs:
statements
expressions
An expression returns a value. It can be evaluated. Consider this statement:
int x = 3 + 2;
It contains an expression that looks like this: 3 + 2. We know that 3 + 2 returns 5, so it is an expression, it returns a value:
3 + 2
Consider this assignment statement:
int x = 3;
Here 3 is an expression that returns a value; it yields the value 3.
A function call is usually an expression:
var x = foo();
Even if foo() returned void, it still can be thought of as an expression:
foo();
Despite the call above, expressions don't usually stand on their own, though they can in many cases. They usually make up part of a statement. Statements do stand on their own. They are the smallest complete portion of a program. For instance:
int x = 3;
This is a statement because it is complete. It performs a single action in a discreet, stand alone line of code. It stands on its own and it does something. It performs an action. It assigns the value 3 to the variable x. Expressions such as 3 or 2 + 3 make no or little sense on their own:
3
2 + 3
They don't really do anything but produce a compiler error. We typically assign expressions to variables to make statements:
var x = 2 + 3;
int x = 2 + 3;
Statements end in semicolons in most curly brace languages.
The statements I'm showing here are all assignment statements. These are a classic kind of statement, but they are not at all the only kind of statement. Other kinds of statements include for statements, which are clearly not assignments:
for (int x = 3; x < 7; x++) {
};
And if statements don't look like assignments:
if (x > 3) {
console.log(x);
};
I'm showing you these statements just so you don't oversimplify your understand of statements. They can take many shapes and forms. More than I wish to discuss in this context. We have just looked at three kinds: assignments, for statements and if statements.
- Statements on Wikipedia: http://en.wikipedia.org/wiki/Statement_%28computer_science%29
- Expressions on Wikipedia: http://en.wikipedia.org/wiki/Expression_%28computer_science%29
- Expressons in C#: https://msdn.microsoft.com/en-us/library/ms173144.aspx
- Statemetns in C#: https://msdn.microsoft.com/en-us/library/ms173143.aspx
- General C# topic: https://msdn.microsoft.com/en-us/library/ms173142.aspx
In the Wikipedia, they talk about evaluation rather than yielding a value, but I think they are saying the same thing, just in different terms. Expressions can be evaluated, they yield a value.
The folks who write the C# guides are really good. For instance: "Expressions can consist of a literal value, a method invocation, an operator and its operands, or a simple name. Simple names can be the name of a variable, type member, method parameter, namespace or type." The parts in bold describe the types of expressions discussed above. Here is an example of type of expression not covered above, the kind not in bold in this paragraph:
var x = y;
Here y is an expression. It is a simple name for a variable.
There are tricky areas, such as this:
foo();
It stands on its own and it returns a value. It could be thought of as an expression and a statement. But the following is clearly a statement, and not an expression:
var x = 3 + 2;
These concepts aren't really that hard, yet I think it is good for students of computer science to learn to speak in such terms. It gives us a language we can use to describe what we are doing when we write code. Also, the terms are used all the time in text books, and we want to be able to read standard texts.
##Semicolons
Placement of semicolons in JavaScript can be confusing. The general rule is to put a command after an assignment statement. One variation on this:
var foo;
The above requires a semicolon because there is an implicit assignment to undefined. It is really saying:
var foo = undefined;
When we call a function, we often put a semicolon after it:
myFunction();
I believe the assumption is that the function returns something, even if it does not:
var result = myFunction();
When we declare a function like this, we don't use a semicolon:
function myFunction() {
}
If we declare it anonymously and assign it to a variable, we do use a semicolon:
var myFunction = function() {
};
In many computer languages, this is an experssion:
2 + 2
This is a statement:
var x = 2 + 2;
We usually put semicolons after statements, but not after expressions. Hence we write:
var x = (2 + 2) - (2 * 3);
In the above we don't put a semicolon after 2 + 2 or 2 * 3, we put it after the whole statement. As Michael points out, these are assignment statements.
One thing you never want to do:
function getPerson() {
return
{
firstName: "George",
lastName: "Washington"
};
}
In this case, JavaScript will automatically insert a semicolon after return:
function getPerson() {
return;
{
firstName: "George",
lastName: "Washington"
};
}
Then our code produces an error, like this:
C:\Temp\Bar.js:5
lastName: "Washington"
^
SyntaxError: Unexpected token :
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
It inserts the semicolon without telling you, and in an attempt to help you. Hence we always write:
function getPerson() {
return {
firstName: "George",
lastName: "Washington"
};
}
Notice that the opening curley brace is on the same line as the return statement.: return {
From a purely syntactical point of view, it is easy to declare variables in JavaScript. For instance, you can just write the name of a variable and assign it a value:
x = 3;
This is not, however, a good strategy.
In general, when declaring variables in JavaScript, you want to make sure that they do not become part of the global object. What is the global object? That depends, but when you are inside a browser, there is an object called window that is the global object. The window object is huge; it contains many properties. When you declare a variable as shown above, it becomes part of the global object.
There are several problems with putting variables in the global object.
- The global object is big and complex enough already, without you further polluting it by adding additional properties.
- Sometimes a library will intentionally place a variable in the global namespace. If you by chance add your own variable with the same name, then you will overwrite the variable from the library, and potentially break code. Of course, this can work in reverse. You might declare something in the global namespace, and a library will overwrite it, hence breaking your code. In either case, you want to avoid putting variables in the global namespace.
Ultimately, your code should place only one variable in the global namespace, and it should use a name that you know will be unique when you do so. Learning to do that is, unfortunately, non-trivial. You will, however, learn how to get started in this section. At least one viable final solution will be provided in the chapter on the JavaScript module pattern. Each step along the way is valuable. In other words, the information you learn in this portion of the text will contain much valuable and useful information. It is not that you will replace the information in this chapter with the information in the modules pattern chapter. Rather, the modules pattern builds on, and includes, the information found in this chapter.
###Declare Variables with var {#useVar}
The first time you use a variable, you should declare it by using the keyword var.
Beginners sometimes write something like this:
myObject = new MyObject();
myObject.run();
This is an error because the keyword var is not used when myobject is declared. As a result, your new object will likely end up in the global name space; that is probably not what you want. To fix the problem, write:
var myObject = new MyObject();
myObject.run();
Note the use of the var keyword.
It is very easy to omit the keyword var when declaring a variable for the first time. As a result, you should be sure to run JsHint over all the JavaScript code you create:
###Declare Variables inside Objects or Functions
Consider the following code:
var count = 3;
function addCount(x) {
return x + count;
}
In this code the variable cound becomes a global variable, which is probably not what you want. Instead, declare your code like this:
function addCount(x) {
var count = 3;
return x + count;
}
Now var is part of addCount, and is not added to the global name space. Of course, addCount itself is in the global namespace, but we are not yet ready to address that issue.
Note that the following code also puts count in global namespace:
function addCount(x) {
count = 3;
return x + count;
}
The error here is that the keyword var is omitted. As a result, count becomes a property of the global object.
###Don't Declare a variable Twice {#declare}
Never redeclare a variable two times. The following example declares the variable param1 as an argument to method foo, and then declares a variable with the same identifier (param1) inside the body of foo.
function foo(param1) {
var param1 = 2;
}
Never use == or !=. Instead, use === and !==. The problem here is that == can return true when you are comparing two different types of objects. For instance:
3 == '3'; // returns true
3 === '3'; return false;
Here is code that demonstrates this point:
function getEqual01() {
return '3' == 3;
}
function getEqual02() {
return '3' === 3;
}
function fillList() {
$("#myList").append("<li>" + getEqual01() + "</li>");
$("#myList").append("<li>" + getEqual02() + "</li>");
}
The first example shown here returns true, the second false.
###For Loops
for (var i = 0; i < 5; i++) {
console.log(i);
}
###While Loops
var count = 0;
while (count < 5) {
console.log(count++);
}
###For and While Loop Example Program
Here is a short program you can run with node to test them both. To run the program, create a file index.js with the following contents. Then type:
node index.js
Below is the code:
/**
* @author Charlie Calvert
*/
var app = {
basicForLoop : function() {
for (var i = 0; i < 5; i++) {
console.log(i);
}
},
basicWhileLoop : function() {
var count = 0;
while (count < 5) {
console.log(count++);
}
}
};
console.log('\nHere is the for loop:');
app.basicForLoop();
console.log('\nHere is the while loop:');
app.basicWhileLoop();
The code shown above can be found in the examples code repository found on GitHub. While there, you might also check out the example of nested for loops:
Branching is the area of computer science that covers both if and switch statements.
###If Statements
var app = {
isEven: function(input) {
if (input % 2 === 0) {
console.log('Your input of ' + input + ' is even');
} else {
console.log('Your input of ' + input + ' is odd');
}
}
};
app.isEven(2);
app.isEven(3);
app.isEven(4);
app.isEven(5);
The output from this program looks like this:
g:\JsObjects\JavaScript\Syntax\Branching01>node index.js
Your input of 2 is even
Your input of 3 is odd
Your input of 4 is even
Your input of 5 is odd
###Switch Statements
Switch statements look a bit like a long series of if..else statements. We pass a variable or expression to the switch keyword, and then a block of one or more statements is executed if the passed variable matches a case that we have set up. In effect, we are saying: "If this particular identifier matches our expression, then execute the statements associated with this case, else try to match the next case."
Here for instance, is the way a series of if else statements might look:
if (stateAbbreviation == 'AL') {
DoSomething();
} else if (stateAbbreviation == 'CA') {
DoSomethingElse();
} etc...
Here is how a switch statement would handle the same task:
Alabama = 'AL',
California = 'CA',
Texas = 'TX',
Washington = 'WA';
var statePopulation = function(stateAbbreviation) {
var result = 0;
switch (stateAbbreviation) {
case 'AL':
result = 4800736;
break;
case 'CA':
result = 38053956;
break;
case 'TX':
result = 25901361;
break;
case 'WA':
result = 6830038;
break;
default:
result = -1;
}
console.log('The population of ' + stateAbbreviation + ' is ' + result);
};
var runState = function() {
statePopulation(Alabama);
statePopulation(California);
statePopulation(Texas);
statePopulation(Washington);
statePopulation('Unknown');
}
You can have multiple case statements match a single set of statements that you want to execute:
case 'CA':
case 'TX':
result = stateIsBig;
break;
If you (usually accidentally) leave out a break statement, then something similar to what we see above occurs. In other words, the code just falls through to the next example:
case 'TX':
result = 25901361;
case 'WA':
result = 6830038;
break;
In the above code, since there is no break in the Texas case, then result will be set to 6830038 if either Texas of Washington is passed in.
Notice also that there is an optional default case that is executed if none of the other options are matched.
###Comparing switch and if..else Statements
As a general rule, switch statements will execute more quickly than a set of if..else statements. However, these kinds of performance issues rarely have serious consequences unless the code in question is being executed inside a loop. Even if your program does have performance problems, it is unlikely that the bottle neck will be fixed by substituting a switch statement for a series of if..else statements. Again, if you are in a big loop, then maybe it will be a bottle neck, but probably not.
The better argument, in my opinion, is for the readability of switch statements. A big block of if..else statements can be hard to parse. The switch statement, on the other hand, lends itself to neat, easy to read formatting.
Links:
###Object Maps
After all our talk about if..else and switch statements it is worth noting that JavaScript provides a third mechanism that is arguable a much better solution to this kind of problem. Consider the following example:
var funcBranch = function(stateAbbreviation) {
var stateMap = {
'AL': 4800736,
'CA': 38053956,
'TX': 25901361,
'WA': 6830038
}
console.log('The population of ' + stateAbbreviation + ' = ' + stateMap[stateAbbreviation]);
};
In this code we create a small object called stateMap. We can then pull out the value we want by simply writing the following simple expression:
stateMap[stateAbbreviation]
If, for instance, stateAbbreviation were equal to 'WA', then this expression would return 6830038. This code is concise, easy to read, and it performs well.
Note that you could perform more complex operations by setting up an object that contains functions:
var stateMap = {
'AL': function() {
return 4800736 /100;
},
'CA': function() {
return 38053956 / 100;
},
etc...
}
This makes the solution functionally equivalent to a switch statement, since each option can consist of a series of statements. For instance you could write something like this:
var funcBranch2 = function(stateAbbreviation) {
var stateMap2 = {
'AL': function() {
return 4800736 /100;
}(),
'CA': function() {
return 38053956 / 100;
}(),
'TX': function() {
return 25901361 / 100;
}(),
'WA': function() {
return 6830038 / 100;
}()
}
console.log('The population of ' + stateAbbreviation + ' = ' + stateMap2[stateAbbreviation]);
};
If that is just too esoteric for your tastes, then you can write:
var funcBranch2 = function(stateAbbreviation) {
var stateMap2 = {
'AL': function() {
return 4800736 /100;
},
'CA': function() {
return 38053956 / 100;
},
'TX': function() {
return 25901361 / 100;
},
'WA': function() {
return 6830038 / 100;
}
}
var bar = stateMap2[stateAbbreviation];
console.log('The population of ' + stateAbbreviation + ' = ' + bar());
};
It's really just a question of when you want the function to execute. The first case saves you a bit of code, but it is arguable going to a bit hard for some people to read.
The example program is on GitHub, in JsObjects:
JsObjects/JavaScript/Syntax/Branching01
###Sorting
Here is code for sorting an array called presidents by first name:
var sort = function(){
presidents.sort(function (a, b) {
if (a.firstName > b.firstName) {
return 1;
} else if (a.firstName < b.firstName) {
return -1;
} else {
return 0;
}
});
};
See this example:
Use jQuery to designate the name of your event handler:
$('#mainCanvas').click(doMouseDown);
Then you can capture the mouseDown event like this, where you need special code to handle the behavior in FireFox:
var doMouseDown = function(event) {
var mouseDownRawX = null;
var mouseDownRawY = null;
// Fix for FireFox which does not define offsetX
if (typeof event.offsetX === 'undefined') {
var elementOffset = $(this).offset();
mouseDownRawX = event.pageX - elementOffset.left;
mouseDownRawY = event.pageY - elementOffset.top;
} else {
var mouseDownRawX = event.offsetX;
var mouseDownRawY = event.offsetY;
}
You can use bind to bind a function to an object, or rather to an object's scope. Suppose you have function func and object obj. You can make a copy of func seem to be a part of obj with bind so that the this variable used by func belongs to obj, even if func originally had a this variable bound to some other object.
totem = 'bird';
var showBind = function()
{
showDebug(this.totem);
}
function MyFunction()
{
this.totem = 'bear';
}
var showBindAgain = function()
{
var myFunction = new MyFunction();
xshowBind = this.showBind.bind(myFunction);
xshowBind();
}
var showDebug = function(data)
{
$('#debug').append('<li>' + data + '</li>');
}
In the code shown above, if you called showBind(), and then called showBind() a second time from showBindAgain(), the first time it would print fish, and the second time it would print bear.
You can try this out by clicking the buttons below. Click these buttons call showBind() and showBindAgain() from a live copy of the JavaScript shown above:
If you would prefer an isolated example away from the text on this page, you can also try this code here:
Try visiting this page in Chrome:
chrome://flags/
All the major browsers have good debuggers in them, but I probably prefer the one that ships with Chrome.
Load your page in the browser, and press F12 to bring up the Chrome Debugger and Development Tools. If you click around a bit, you can have the debugger in one window and your browser in another window, which can be a good strategy.
We have talked some about debugging strategies with these tools before, but digging into them is very wise. The Resources pagecan help you find JavaScript or HTML files which are badly broken due to syntax issues. The Scripts page allows you to set break points in JavaScript files. The Elements page helps you study an HTML file.
See also these pages:
The insertAdjacentHTML method has been part of some implementations of JavaScript and the DOM for some time, but it is finally being standardized in HTML 5. When you click the button shown below, the following code gets executed:
<script type="text/javascript">
function TestInsertAdjacent()
{
var adjacentText = document.getElementById('AdjecentText');
adjacentText.insertAdjacentHTML('afterbegin', '[Rufus]:');
}
</script>
Code like this can be placed in a separate file with .js extension, it can be embedded in the midst of an HTML file, or it can be placed in the <head> section at the top of an HTML file. This code will modify the next paragraph by placing an arbitrary string ([Rufus]:) at the beginning of the first sentence, that is, after the opening <p> tag:
This is a p element with the IDAdjacentText. Push the button below to modify it
There are four places where it can insert text:
- beforebegin
- afterbegin
- beforeend
- afterend
The after and before phrases refer to after and before a tag. Suppose you have an element like this:
<p>This element</p>
The statement can insert text before the first <p> tag, after that tag, or before the closing <p> tag, or after it.
If you want to learn more about the DOM, go to this page: https://developer.mozilla.org/en/Gecko_DOM_Reference.
Here is the code for the button:
<input name="insertAdjacentButton" type="button" value="Insert Adjacent Text" onclick="TestInsertAdjacent()">
You can indent your code with tabs or with spaces, but not with both. Choose either tabs or spaces, and stick with your decision. There are many tools you can use to help you fix these kinds of problems. For instance, simply selecting Source | Format in Eclipse should clean up this issue. Both Eclipse and NotePad++ contain options that allow you to see the content of your white space, so you can tell when you are mixing up the two characters on the same line.
Functions that take the form of an assignment should end with a semicolon:
var changeList = function() {
("#MyList").append("<li>List Item</li>");
};
If you declare a function like the following example, there is no assignment, and hence no statement, and hence no need for a semicolon:
function changeList() {
("#MyList").append("<li>List Item</li>");
}
You should, of course, always end a statement with a semicolon:
("#MyList").append("<li>List Item</li>");
It would be wrong to write this:
("#MyList").append("<li>List Item</li>")