Arrays

o      In many cases, variables will completely satisfy our data storage needs in JavaScript. However, in a large number of cases, we may wish to “group” variables into a collection of related items.

o      Take, for example, days of the week. In each day we perform a number of tasks, so we could want to record each task as a separate item under a group called, say, Monday’s Tasks.

o       In JavaScript, to achieve this we would store each task in a separate variable, and then group those variables together into an array.

o       An array is a special type of JavaScript object that can store multiple data values – unlike a variable, which can only store one data value at a time.

o       It could be helpful to think of an array as a row of mail boxes in an office, just as you might think of a variable as a single, solitary mail box.

o       The boxes in an array are numbered upwards, starting at box number 0 – note that counting begins at 0 here, just as we discussed in the previous chapter. The number assigned to each box is known as its index.

In order to use an array in JavaScript, you must first create it. There are a number of ways to create arrays in JavaScript. The simplest follows:

           arrDays = new Array();

This statement creates a new, empty array called arrDays. We can call arrays just like we can variables, but with a few minor adjustments.

o       If you already know how many elements a given array will have, you can declare this explicitly: 

 arrDays = new Array(7);

This modification creates an array with 7 empty boxes. However, arrays will expand and contract to the required size in JavaScript, so the cases where you will need to state the size of the array are rare.

o        More useful, however, is the ability to “fill” the boxes of an array when you create it. For example: 

 arrDays = new Array(“Monday”,”Tuesday”);

We now have an array with two elements. The first (element 0) has a value of “Monday”, while the second (element 1) has a value of “Tuesday”. We need not restrict ourselves to string values in arrays – Boolean, numerical and string values are allowed, as in arrays. It is even possible to assign other arrays to array elements – more on this later.

o       The most often-used way of creating an array is to use “square bracket” notation. Square brackets play a large role in the use of arrays, so this is often the easiest method to remember: 

 arrDays = [“Monday”,”Tuesday”];

This is identical to the previous example.

To access an array’s elements, we first call the array’s name, and then specify the number of the element in square brackets, like so: 

 alert(arrDays[0]);

Note the lack of quotes around the 0 here. This line of code is equivalent to:

 alert(“Monday”);

assuming the array is defined as in the previous examples.

o       Not only can we access the value of an array element using this notation, but we can also assign the value as we

arrDays[2] = “Tuesday”; arrDays[3] = “Wednesday”;

o   If you wish to add an element to an array without knowing the index of the last element, you can use the following code:

arrDays[] = “some other day”;

o       As we will see, arrays are actually just special JavaScript objects, and have properties and methods associated with them. The most important property that every array has is its length property:

how_many_days = arrDays.length;

o       As well as properties, arrays have very useful methods. If you wished to sort your array alphanumerically, you could use the array’s sort method thus:

         arrDays.sort();

Note that the sort method works on the actual array itself, overwriting the current values. So, if you had an array with each day of the week as an element, calling its sort method would mean that arrDays[0] was then equal to “Friday”, not “Monday”.

Project

o   Open your previous project file, and save it under the name chapter_15.html.

Clear all JavaScript code from your script tags.

o   Write a few JavaScript statements that will present the months of the year on the page in alphabetical order. You should use the following technique to achieve this:

o   Store the names of the months of the year in an array.

Use an array method to sort the array elements alphanumericall

o   Use a for loop to iterate through each array element in turn, and print the value of the element to the screen (hint, consider the use of array[i], where i is the for loop’s counter).

o   The above method (the use of a for loop to iterate through a series of array elements) is one of the first common programming techniques we have discussed in this course. Its usefulness cannot be overstated, as it allows us to perform repetitive tasks on a series of related elements without necessarily knowing what those elements might be when we wrote the code. It can be applied to form elements, cookies, page elements, pages, windows, and just about any other collection of object that you might wish to manipulate with JavaScript.

o   To reinforce this generalism, if you have not used the array.length value in your loop, consider its use now. To prove that you have created a more generic loop, try the code with an array of days instead of an array of months, and see if you have to change any of the looping code.

Read More

Looping

o   The letters ij and k are traditionally used by programmers to name variables that are used as counters. For example, at different stages of the program, i may contain the numbers 1, 2, 3 etc.

o   In order to achieve a “counting” effect, you will need to increment or decrement the value of your counting variable by a set value. Here are some examples:

i = i + 1; 

i = i – 1; 

i = i + 35; 

incr = 10 i = i + incr;

o To keep things concise, we can use the following shortcuts:

i++;  // equivalent to i = i + 1;

i–; // equivalent to i = i + 1;

o   Counting in JavaScript, like many other programming languages, often begins at zero

In many cases, this makes a lot of sense, as we will see. However, it can often cause confusion. Consider starting at 0 and counting up to 10. In that case, we may have actually counted 11 items:

 0                               (1)

1                               (2)

2                               (3)

3                               (4)

4                               (5)

5                               (6)

6                               (7)

7                               (8)

8                               (9)

10               (11!)

o   If you wanted to give an instruction to someone to perform a repetitive action, you might say that you wanted them to continue the action for a certain number of times. If someone were performing an action 300 times, for example, they might do something like the following to ensure that their count was accurate:

o   Write the number 1 on a bit of paper.

o   After each action, erase the number on the bit of paper and increment it by 1.

o   Before each action, check the number on the bit of paper. If it is less than or equal to 300, perform the action.

o   Alternatively, they might decide to start counting at 0. In this case, the procedure would be identical, but the check before each action would be to make sure that the number was strictly less than 300.

o   In JavaScript, we say almost the same thing. The following code will display the numbers 1 to 100 on the page:

 for( i = 1; i <= 100; i++ )

  {

  document.write(“<p>” + i “ </p>”);

  }

   The for statement tells the browser that we are about to perform a loop. The layout here is very similar to a conditional statement, but in this case we have much more information in the brackets. Where our conditional had one JavaScript statement to describe its action, a for loop has three:

o  An initialiser – this sets up the initial counting condition, in this case i = 1.

o     A conditional – this is identical to our conditional statements earlier, and must return true or false. If it returns true, the loop continues, otherwise it exits.

o     An incrementer – this defines the action to be performed at the end of each loop. In this case, i is incremented by a value of 1.

o      The key difference between a conditional and a for loop is that the condition is constantly being changed and re-evaluated. It is possible to create an infinite loop by making the conditional non-reliant on the count value – for example:

for(i=0; 5 > 4; i++ )

 will always perform the script in the braces, and will probably cause errors in the browser.

o     Note too that it is very common to start counting at zero in JavaScript. The reason for this is that it is often desirable to count how many times an operation has been performed.

Consider the following: 

for(i=1; 1 < 2; i++ )

o   In this case, the loop will run once, but the value of i will be 2, as after the first run, i will be incremented to 2, and will then fail the test and so the loop will exit. If we use the following: 

 for(i=0; 1 < 1; i++ )

 Then the loop will run once, and the value of i afterwards will be 1, as we might hope.

Project 

o   Open your previous project file, and save it under the name chapter_14.html. o Clear all JavaScript code from your script tags.

Write a series of statements to produce a multiplication table as follows:

o   The following exercise is more of an HTML example, but demonstrates an important facet of using JavaScript (or, indeed, any programming language) to produce well-formatted text.

o   Modify your previous code to make your page’s content appear in the centre of the page. Put your multiplication table in an HTML table to make sure that the equals signs, multiplication signs and so forth line up in neat columns:

o   The following exercise is more of an HTML example, but demonstrates an important facet of using JavaScript (or, indeed, any programming language) to produce well-formatted text.

o   Modify your previous code to make your page’s content appear in the centre of the page. Put your multiplication table in an HTML table to make sure that the equals signs, multiplication signs and so forth line up in neat columns:

o   The following exercise is more of an HTML example, but demonstrates an important facet of using JavaScript (or, indeed, any programming language) to produce well-formatted text.

o   Modify your previous code to make your page’s content appear in the centre of the page. Put your multiplication table in an HTML table to make sure that the equals signs, multiplication signs and so forth line up in neat columns:

Read More

Conditionals

o       Up until now, our JavaScript projects have been unable to alter their behaviour spontaneously. When a page loads with our JavaScript embedded within, it is unable to do anything other than what we expect, time and again.

o       The only difference we have seen is in the use of a prompt box to alter what is shown on a page. However, the page essentially does the same thing with the text provided, regardless of what text is typed in.

o       What would be really handy would be to give JavaScript a mechanism to make decisions. For example, if we provided a prompt box asking the visitor for their name, it might be nice to have a list of “known names” that could be greeted differently from any other visitors to the site.

o      Conditional statements give us that ability, and are key to working with JavaScript.

o     A conditional statement consists of three parts:

o     A test (often with a comparison operator, or comparator) to see if a given condition is true or false.

o     A block of code that is performed if and only if the condition is true.

o     An optional block of code that is performed if and only if the condition is false.

These three parts are represented in JavaScript as follows:

  if ( conditional_test )

  {

  JavaScript statement;

  JavaScript statement;

  JavaScript statement;

  …   } else

  {

  JavaScript statement;

  JavaScript statement;

  JavaScript statement;

  …

  }

o     Everything from the first closing curly bracket (or brace) is optional, so the following is also a valid conditional prototype: 

 if ( conditional_test )

  {

  JavaScript statement;

  JavaScript statement;

  JavaScript statement;

  …   }

o     In this case, if the conditional_test does not return true, nothing happens.

o   An example of  complete conditional statement is as follows:

 if ( var_1 > var_2 )

  {

  alert(“Variable 1 is greater”);

  } else   {

  alert(“Variable 2 is greater”);

 }

  Note that the above condition is not necessarily always correct. Consider the case where var_1 is equal to var_2.

In that case, the above code will produce the message that “Variable 2 is greater”, since var_1 > var_2 returns false. In this case, we want to add an additional condition to the else branch of code: 

if ( var_1 > var_2 )

  {

  alert(“Variable 1 is greater”);

  } else

if ( var_1 < var_2 )

  {

  alert(“Variable 2 is greater”);

 }

o In this case, equality will produce no output, as neither of the conditions will return true. For completeness, we could add a final else branch to the statement:

 if ( var_1 > var_2 )

  {

  alert(“Variable 1 is greater”);

  }  else

if ( var_1 < var_2 )

  {

  alert(“Variable 2 is greater”);

 }

else   {

  alert(“The variables are equal”);

 }

o      Note that in this case, we don’t have to check for equality in the final branch, as if var_1 is neither greater than nor less than   var_2, then – numerically at least – the two must be equal.

o     We can continue adding as many else if statements as required to this stack.

If you only have one statement following your conditional test, the braces may be omitted:

 if ( var_1 > var_2 )

  alert(“Variable 2 is greater”);

However, if you later want to add further statements to this conditional branch, you will have to add braces around the block, and this can lead to confusion. It is recommended that you use braces to enclose all blocks of conditional code. o Consider the following block of code:

 if ( var_1 > 4 )   {

  var_2 = var_1;

 }

else   {   var_2 = 4;   }

o     This code is rather long, but achieves comparatively little – var_2 is equal to var_1 or 4, whichever is greater. o A more compact way of writing this could be:

Read More

Alert, Prompt and Confirm

o    So far, we have seen brief examples of alertprompt and confirm dialogue boxes to request a response from the user, and to pause all code in the background until the request is satisfied.

o    All of these boxes are the result of methods of the window object. This object is the highest level object that JavaScript can deal with in a browser. As such, all other objects on a page (with a few exceptions) are actually properties of the window object.

o     Because of this ubiquity, its presence is assumed even if it is omitted. Thus, where we technically should write:

 window.document.write(“…”);

 it is equally valid to write:

 document.write(“…”);

 as we have been doing.

o     Similarly, instead of writing:

 window.alert(“…”);

we can happily write:

 alert(“…”);

o    The prototypes of the three methods are:

        window.alert( message ); window.confirm( message ); window.prompt( message, default_response );

o    Alert will always return a value of “true” when it is cleared by clicking “ok”.

o    Confirm will return either “true” or “false” depending on the response chosen to clear the box.

o    Prompt will return either the value typed in, “null” if nothing is typed in, and “false” if the box is cancelled.

Project

o   Open your previous project file, and save it under the name chapter_10.html.

o   Clear the previous redirection code, and ensure that the script tags have been returned to the head section of the document.

o   Add a new statement to the script on the page that will display the following message before the rest of the page is shown:

 Welcome to my website! Click OK to continue.

o Check your page in your browser.

 o   We will use alertconfirm, and prompt throughout this course. Take a moment to try each of them in turn on this page, each time stopping to review your changes.

 o   Use the write method of the document object to check the return values of each method. For example:

          document.write(alert(“hello world”));

Read More

About Comments

o   Repeat after me : Comments are important. Comments are importantComments are important.

o   Adding comments to your code is always good practice. As the complexity of your scripts grows, comments help you (and others) understand their structure when you come to view the code at a later date.

o   A lot of code created quickly is said to be “write only” code, as it suffers from an inherent lack of structure or commenting. Debugging such code, or reusing it months later, becomes maddeningly impossible as you try to remember what a certain line was supposed to do, or why using certain values seems to stop your code from working.

o   Comments are completely ignored by JavaScript and have no effect on the speed at which your scripts run, provided they are properly formed.

o   Comments can slow the loading of your page, however – many coders keep a “development” copy of their code fully commented for editing, and remove all comments from their code when they finally publish it.

o   There are two types of comment in JavaScript – single line comments, and multi-line comments.

o   Single line comments begin with two forward-slash characters (//), and end with a new line:

// this is a comment

 alert(“hello”); // so is this

o   Single line comments in JavaScript can also use the HTML comment format that you may be familiar with:

 <!– this is a comment

 alert(“hello”);

o   Note two things: firstly, this use of the HTML comment format does not require a closing –> tag. Secondly, this is only a one line comment, unlike its use in HTML, which comments all lines until the closing comment tag.

o   You can add multiple-line comments by enclosing the comment block between /* and */. For example:

/* all of this text is going to be ignored by JavaScript. This allows us to write larger comments without worrying about having to individually “comment out” each line */ 

alert(“Hello World”);

/* a one line, “mult-line” comment */

o   As well as adding narrative to your script, you can use comments to remove code from your pages without having to delete the code. For example:

// this was the old message

// alert(“Hello World”); // and this is the new message alert(“Hello everyone!”);

o   This can be very useful if you are trying to track down an error in your code – you can “comment out” each suspect line in turn until you manage to get your code working again.

Project

o   Open your previous project file, and save it under the name chapter_7.html

o   Add the single line comment

This is my first comment

to the beginning of your script.

Add a multi-line comment to your script, replacing your previous single line comment. The multi-line comment should describe what your script does at present. 

Read More

Hiding Scripts from Older Browsers

    • Very old browsers don’t understand JavaScript. There are very few such browsers in use today, but two factors force us to continue to consider environments that may not be able to cope with our JavaScript code.
    • Firstly, all modern browsers allow users to control whether JavaScript code will be run. In many cases, users will not have any say over their company policy, and may not even know that their work machine has had JavaScript disabled.
    • Secondly, not all of your visitors will be using browsers that can make any use of JavaScript. Braille displays, screen readers and other non-visual browsers have little use for many JavaScript tricks. In addition, search engines like Google will ignore any JavaScript you use on your pages, potentially hiding important content and causing your pages to remain unindexed.
    • Browsers that don’t support JavaScript are supposed to ignore anything between the opening and closing script tags. However, many break this rule and will attempt to render your code as HTML, with potentially embarrassing consequences.
    • However, we can use the fact that <!– denotes a single line comment in JavaScript but a multi-line comment in HTML to ensure that our code is seen by a JavaScript-savvy browser, but ignored as commented-out HTML by anything else:

               <script>

      <!– hide  from older browsers

     … your code

     // stop hiding code –> </script>

o   This prevents older browsers from displaying the code, but what if we want to replace this with some comment. For example, let’s say we had a bit of code that displayed the time of day and greeted our user by name. Without JavaScript and using the method above, there would simply be a blank on the page where the greeting should have been.

o   We can use the <noscript> tag to cause our code to “fail gracefully” where JavaScript has been disabled or is unavailable. The contents of this element will be ignored where JavaScript is understood, and displayed anywhere else.

For example:

<noscript>

    <h1>Welcome to our site!</h1>

</noscript>

<script>

<!– hide  from older browsers

… code to customise header

// stop hiding code –>

</script>

Project 

o   Open your previous project file, and save it under the name chapter_8.html.

o   Add two lines to your code to ensure that it will not confuse older browsers or browsers where the user has disabled JavaScript.

o   Add a noscript element to explain what your JavaScript does.

    It is generally considered “bad form” to instruct your user to “upgrade to a better browser”, as this can insult many people

   who use assistive devices – consider this form of advice to be similar to the advice that tells a blind person “to get some

    glasses”.

o   Instead where possible you should use the noscript element to provide content that adequately replaces the scripted content

    with a suitable replacement. For example, if you use your JavaScript to build a navigation panel on your page, the noscript element should contain a plain HTML list that does the same job.

Read More

Automatically Redirecting the User

o   We have already briefly seen the use of browser redirection in chapter 4.

o   To formulate the idea more completely, in order to redirect the user to a different page, you set the location property of the document objects.

o   As we saw in chapter 6, we can use the assignment operator here. For example:

 document.location = “http://www.bbc.co.uk/”; document.location = “chapter_4.html”;

Project

o   Open your previous project file, and save it under the name chapter_9_redirect.html.

o   Save another copy of the file, this time called chapter_9.html.

o   Make sure both files are saved in the same folder, and that you have chapter_9.html open in your editor.

o   Remove all script from between the script tags, except for your browser hiding lines. Make sure that the script tags are still in the head section of the page.

o   Now, add a single statement to this script that will automatically redirect the user to the page

chapter_9_redirect.html as soon as the page is loaded into a browser.

o   Finally, add a header tag to the body section of the page containing the text “You can’t see me!”.

o   Close this page, don’t check it in a browser yet, and open the page chapter_9_redirect.html in your editor.

o   Remove all JavaScript from this page (including your script tags) and ensure that only HTML remains on the page.

o   Add a header tag to the body section of the page containing the text “But you can see ME!”.

o   Save this page, and load the page chapter_9.html into your browser.

                Experiment with various positions for the script tags on chapter_9.html to see if you can make the header appear before the    redirection.

Read More

Comparisons

o       Comparison operators compare two values with each other. Most commonly, they are used to compare the contents of two variables – for example we might want to check if the value of var_1 was numerically greater than that of var_2.

o        When you use a comparison operator, the value that is returned from the comparison is invariably a Boolean value of either true or false. For example, consider the following statements:

var_1 = 4; var_2 = 10;

var_3 = var_1 > var_2;

           In this case, the value of var_3 is false. Note that the Boolean value of false is not the same as the text string “false”:

var_4 = false;  // Boolean value var_5 = “false”;  // Text string o Common comparison operators are given below:

Comparison

Function

x == y

Returns true if x and y are equivalent, false otherwise

x != y

Returns true if x and y are not equivalent, false otherwise

x > y

Returns true if x is numerically greater than y, false otherwise

x >= y

Returns true if x is numerically greater than or equal to y, false otherwise

x < y

Returns true if y is numerically greater than x, false otherwise

x <= yReturns true if y is numerically greater than or equal to x, false otherwise

o       To reverse the value returned from a comparison, we generally modify the comparison operator with a ! (a “bang”). Note that in many cases this is not necessary, but can aid comprehension:

var_1 !> var_2; var_1 <= var_2;

                    both of these are equivalent, but one may make more semantic sense in a given context than the other.

Project

o   Open your previous project file, and save it under the name chapter_12.html.

o   Ensure that your two variables both have numerical values in them and not strings.

o   Use an alert box to display the result of a comparison of your two variables for each of the comparison operators listed above.

o   Substitute one of the numerical values for a text string and repeat the procedure. Note the differences.

Read More

Assigning Values to Properties

o   While objects and methods allow us to do things on a page, such as alter the content or pop up dialogue boxes to interact with theuser,     in many cases we will want to alter the value of one of an object’s properties directly. These cases are akin to painting our piano green.

o   Given our discussion on methods so far, we might expect to be able to alter our object’s properties by using a method – for example, the following would seem logical:

 piano.paint(“green”);

o   In many cases, that is exactly what we will do. However, there are two drawbacks here. The first is that, within this course, the majority of objects that we discover are built into and defined by our browser. If we rely on using a method to alter an object’s property, we are also relying on the fact that the method exists in the first place.

o   A much more direct way to solve this problem is to access the object’s properties directly. For example:

piano.colour  =  “green”;

o   Here we are no longer using a method to perform an action, we are using what is known as an operator. In this case, the operator has the symbol “=”, and is known as the assignment operator.

o   Within JavaScript, we can use this operator to great effectiveness. For example, we could alter the title element of a document (the text that is displayed in the top bar of the browser’s window) dynamically. This could be done when a user clicked on a part of the page using an event handler (more later on this), or could be set to automatically update each minute to show the current time in the page title. The code we would use for this task is simple:

document.title  =  “a new title”;

o   There are many assignment operators in JavaScript. Some of the more common are shown in the table below:

 Assignment  Function
x = ySets the value of x to y
x += ySets the value of x to x+y
x -= ySets the value of x to x-y
x *=ySets the value of x to x times y
x /=ySets the value of x to x divided by y

o   Not all assignment operators work with all types of values. But the addition assignment operator works with both numbers and text. When dealing with numbers, the result will be the sum of the two numbers. When dealing with text (technically called strings), the result will be the concatenation of the two strings:

document.title += “!”;

will cause the symbol “!” to be appended to the end of the current document title.

Project

o   Open your previous project file, and save it under the name chapter_6.html

o   Remove any existing JavaScript from your script tags, but leave the tags in place ready for some new JavaScript.

o   Use your text editor to change the value of the title element of the page as follows, then load your page into a browser and view the result:

<title>With a little help from</title>

o   Now, add a statement to our script element to add the following text to the end of the current title:

”JavaScript for Beginners!”;

o   Reload the page in your browser and note the title bar of the window.

o   If the display looks odd, consider your use of spaces…

o   All we have so far is an example that does nothing more than HTML could manage. Let’s introduce a new method of the window object to help us to add a little more dynamism and interaction to the script. Change the value of the title tag as follows:

<title>Chapter 6: Assigning Values to Properties</title>

o   Now, remove your previous JavaScript statement and insert the following:

document.title =     window.prompt(“Your title?”, “”);

o Reload your page and consider the result.

o   We have come across the window object before. Our demonstration of the alert method in chapter 4 could have been more properly written as:

window.alert(“message”);

In many cases, we can omit certain parts of our object/property/method hierarchy when writing our code. We will discuss this again later.

o   To understand what is going on with our prompt method, we can write down a method prototype. This is a way of describing a method’s arguments in such a way that their effect on the method is more self explanatory. A prototype for the prompt method of the window object might look like the following:

window.prompt( message, default_response );

o   So, we can see that the first argument defines the text that appears as the question in the prompt dialogue box. The second argument is a little less clear. Try your code with different values and see what difference your changes make.

o   Finally, we note that this prompt method somehow takes the information typed into the box and passes it to our JavaScript assignment. Say someone typed “Hello World” into the box. It would have been as if our assignment had actually been:

document.title = “Hello World”;

o   When this sort of passing of values occurs, it is said that the method has returned the value passed. In this case, we would say that “the prompt method has returned the value ‘Hello World’”, or that “the return value of the prompt method was ‘Hello World’”.

o   Return values will become very important when we deal with event handlers later on.

Read More

Objects, Properties and Methods

12 Apr  Admin

o   Generally speaking, objects are “things”. For example, a piano is an object.

o   Properties are terms that can describe and define a particular object. Our piano, for example, has a colour, a weight, a height, pedals, a keyboard and a lid.

o      Note from the above that an object’s properties can be properties themselves. So we have the case where a piano lid is a property of the piano, but is also an object in its own right, with its own set of properties – for example, the lid has a colour, a length, and even a state of either open or closed.

o     If objects are the nouns of a programming language and properties are the adjectives, then methods are the verbs. Methods are actions that can be performed on (or by) a particular object. To continue our piano example, you could play a piano, open its lid, or press the sustain pedal.

o      Many programming languages have similar ways of referring to objects and their properties or methods. In general, they are hierarchical, and an object’s relationship with its properties and methods, as well as with other objects, can often be easily seen from the programming notation.

o      In JavaScript, we use a “dot notation” to represent objects and their properties and methods. For example, we would refer to our piano’s colour in the following way:

 piano.colour;

o     If we wanted to instruct JavaScript to play the piano, we could write something as simple as:

 piano.play();

o     A clear example of object hierarchy could be seen if we decided to open the lid of the piano:

 piano.lid.open();

o     Or even more so if we wanted to press the sustain pedal of the piano:

 piano.pedals.sustain.press();

o     Note that in some of the examples above, we have brackets () after each set of words, and in some we don’t. This has to do with making sure that JavaScript can understand what we say.

o     JavaScript works with objects throughout its existence in a web browser. All HTML elements on a page can be described as objects, properties or methods. We have already seen a few of these objects in our previous introductory chapter:

 document.write(…); document.location;

o   In these examples, document is an object, while write is a method and location is a property.

o      In these lines, we see a clue about the use of brackets in these statements. We use brackets to signify to JavaScript that we are talking about an object’s method, and not a property of the same name.

o     Brackets also allow us to pass certain extra information to an object’s method. In the above example, to write the text “Hello world!” to a web page document, we would write the following JavaScript:

 document.write(“Hello World”);

o     Each method can do different things depending on what is put in the brackets (or “passed to the method as an argument”, to use the technical term). Indeed, many methods can take multiple “arguments” to modify its behaviour. Multiple arguments are separated by a comma (,).

o     A JavaScript instruction  like those shown here is referred to as a JavaScript statement. All statements should end in a single semi-colon (;). JavaScript will often ignore missed semi-colons at the end of lines, and insert the semi-colon for you. However, this can cause some unexpected results. Consider the following:

document.write(“<h1>Hello World! </h1>”);

o     In many other languages, this would be acceptable. However, JavaScript will often interpret something like this as the following: 

document.write(“<h1>;Hello World!; </h1>”);

o     This interpretation will generate an error, as JavaScript will complain if you end a statement without ensuring that any terms between quotes have matching pairs of quotes. In this example, the first line’s “statement” is cut short, and JavaScript will fall over.

o    For this reason, it is recommended that all your statements should end with semi-colons.

Read More