Articles

JavaScript Basics

THE CONTAINER

As soon as the browser encounters the <script> tag, it passes control to the interpreter of the called language. To place JavaScript instructions in an HTML page, use the <script> tag as follows:

<script language="javascript">
javascript statements
</script>

WHERE TO PUT THE SCRIPTS?

If you prefer to include the JavaScript code stored in another file, you can indicate it by the line like:

<script src="file_name.js"></script>

At first we will place the JavaScript instructions inside the container

<body>...</body>

For global functions for the whole document, we will most often place them in the container

<head>...</head>

COMMENTS

JavaScript comments

// JS comment on one line
/* JS comment on
multiple lines */

HTML Comments

<!--one-line HTML comment -->
<!-- HTML comment
on several lines -->

EXAMPLE

<HTML>
<HEAD>
<TITLE>
My 1st Program in JavaScript
</TITLE>
</HEAD>
<BODY>
<SCRIPT language="JavaScript">
// this is a comment
document.write("Hello friends...!")
</SCRIPT>
</BODY>
</HTML>

VARIABLES

  • Used to retain values
  • Identifier:
    [a-zA-Z_][a-zA-Z0-9_]*
  • Starts with a letter (min or maj) or _
    Then letter, number or _
  • Attention: distinction between lower and upper cases.

Example:

var counter = 0;
var total, index = 0, string = "text";

VISIBILITY OF VARIABLES

  • A variable can be said to be global if it is declared in the JavaScript tag and outside of any function.
    Then it can be used throughout the HTML page and inside any functions.
  • A variable is said to be local if it is declared inside a function.

THE EXPRESSIONS

String of characters:

  • “This is a string”
  • “String that contains a \” (quotation)”
  • “String that contains a \n (line break)”
  • ‘One more string’

String Operation

  • Concatenation: “This is ” + “a string”;
  • digit = parseInt(“19”);
  • For all of the following: c = “ABCDE”;
  • c.length is 5;
  • c.charAt(3) is D; indeed we start at 0;
  • c.indexOf(‘C’) is 2;
  • c.lastIndexOf() starts searching for the end;
  • c.substring(2,4) is “CD”;
  • c.toLowerCase() and c.toUpperCase();

THE OPERATORS

+ Addition

– Subtraction

* Multiplication

/ Whole division

% Modulo (integer division remainder)

Increment ++, Decrement – –
Ex: foo ++; or ++ foo;
foo = counter++;
toto = ++counter;

Negation –
Ex: toto = -10;

Note: The + operator is also used for strings and means concatenation (word collage).

Assignment
= or += or -= or *= or /= or %=
Ex: toto = 10;
foo = foo + 5;
foo += 5;

Comparison
== or != or > or < or >= or <= or === or !==
Ex: toto == 10;

Logic
&& (and) or || (or) or ! (not)

Concatenation of strings
string = “abc” + “def”;

Conditional operator
y = x > 0? x: -x;

THE IF…ELSE TEST

  • This instruction is used to carry out one or more instructions if the condition tested is TRUE ( true ).
  • If the condition tested is FALSE ( false ) the else keyword is used to execute one or more instructions.
if (tested condition)
{
instructions executed if condition true
}
else
{
instructions executed if condition is false
}

Example

if (X > Y )
{
alert("X greater than Y!");
}
else
if (X < Y )
{
alert("X less than Y!");
}
else
alert("X and Y are equal!");

THE WHILE LOOP

It allows repeating one or more program instructions as long as a condition is true. Its syntax: while (tested condition) { statement 1 ……… n-statement }

Example

var Y=5;
while ((Y % 5) < 4 )
{
Y+=3;
document.write(‘Value of Y = ‘ + Y);
}

THE SWITCH

<html>  
  <head>
    <title>
      Using the switch
    </title>
    <script language="JavaScript">
      < !--
      function checkDay(form) {
        var input = form.day.value.toUpperCase();
        var start = "You have entered a start day for
working week";
        var end = "You have entered a weekend day
open";
        var weekEnd = "You have entered a day for the end of
week";
        switch (enter) {
          "MONDAY"box: alert(start);
          break;
          "TUESDAY"box: alert(start);
          break;
          "WEDNESDAY"box: alert('You have entered a midweek day');
          break;
          "THURSDAY"box: alert(end);
          break;
          "FRIDAY"box: alert(end);
          break;
          "SATURDAY"box: alert(weekEnd);
          break;
          "SUNDAY"box: alert(weekEnd);
          break;
        default:
          alert('Invalid day');
        }
      }
    </script>
  </head>  
  <body>
    <form name="myForm">
      <b>
        Enter a weekday:
      </b>
      <br>
      <input type=TEXT value="" name="day">
      <input type=BUTTON value="Test" name="myButon" onClick='checkDay(this.form)'>
    </form>
  </body>
</html>

THE FOR LOOP

It is used to repeat actions a number of times.

for (x = 0; x < 20; x++) { 
document.write('Value of x=' +x+'<br/>');
}

This loop structure has 3 parameters:

  • initialization of the index (here: x=0)
  • loop end condition (here: x < 20)
  • action performed at each turn of the loop. (here: x++)

The other actions performed at each turn of the loop follow the for statement.

DISPLAY TEXT

DISPLAY TEXT

document.write()
<html>
<head><title>Example</title>
</head>
<body>
<script language="JavaScript">
document.write(‘Hello friends’);
</script>
</body>
</html>

DISPLAY THE CONTENTS OF VARIABLES

<script language="JavaScript">
var day = 30;
var month = 'September';
document.write(': Date = '+ day + ' ' +
month);
</script>

DISPLAY WITH THE ALERT() METHOD

This method opens a dialog box with an OK button.

<script language="JavaScript">
alert('JavaScript course.');
alert(2*5);
alert(‘Value=’+14);
</script>

READ INFORMATION WITH PROMPT()

This method opens a dialog box with an input zone and 2 buttons: OK and Cancel. It allows you to read information.

<script language="JavaScript">
month= prompt('What month is it? ',
'January');
alert('You answered: ' + month)
</script>
<html>
  
  <head>
    <script language="JavaScript">
      function Confirm() {
        annee = prompt('What year are we in? ', 1999);
        alert('You answered: ' + year);
        if (confirm('I'll say which button you pressed: '))
alert('On OK\n Continue with: ')
else alert('On Cancel\n Exit with Ok ! ');
}
'
    </script>
  </head>
  
  <body>
    <H1>
      TEST I/O
    </H1>
    <script language="JavaScript">
      Confirm();
    </script>
  </body>

</html>

Arrays: Basic Declaration

An array is an Array object. To declare an array, use the new statement:
var tab=new
Array; In JavaScript, as in most programming languages, the first element of the array starts at index 0.

var tab;
tab = newArray();
tab[0] = 'value1';
tab[1] = 'value2';
tab[2] = 'value3';
document.write(tab.length); // Returns '3'
  • concat(Array1, Array2[, Array3, …]): this method is used to
    concatenate (paste) multiple arrays to form a single array.
  • join(Array) or Array.join(): returns all the elements (values) of Array in the form of a character string.
  • pop(Array) or Array.pop(): deletes the last element of Array after returning its value.
  • Array.shift(): deletes the first element of Array after having returned its value.
  • Array.unshift(value1[, value2, …]): adds elements to the beginning of Array.
  • Array.push(value1[, value2, …]): adds elements to the end of Array.
  • Array.sort(): sorts all the elements of Array.
  • Array.reverse(): reverses the order of the elements of Array.
  • Array.splice(start, end, value): overwrites the values of elements in Array whose index is between start and end.
  • Array.slice(start, end): returns the elements whose index is between end and start.
  • Array.toString(): returns the description of Array.
  • Array.toLocaleString(): converts a date to characters.

Sort an array

The “sort” method is used to sort an array.

var array = new Array('8','3','5');
or var array = ['8','3','5']; //no Array
array.sort(); // Sort the array ('3','5','8')

Reverse elements of an array

The “reverse” method reverses all the elements of an array.

array = New Array('a','b','c');
array.reverse(); // Reverse the array ('c','b','a')

Concatenate two arrays

The concat method makes it very easy to concatenate two arrays.

array1 = new Array(1,2,3);
array2 = new Array(4,5);
array = array1.concat(array2); // Created the array (1,2,3,4,5)

Join the elements of an array

The join method joins the elements of an array with a character (or not).

array = new Array('value1','value2','value3');
document.write(array.join("_")); // Returns 'value1_value2_value3

The principle of associative arrays is simple when you understand that of arrays: rather than numbering the elements, you will associate them with a name, replacing the index with a character string.

Declare and initialize the array if it is associative.

Method 1:

var rectangle = {length: 5, width: 3, area: 15};

Method 2:

var rectangle = new Array();
rectangle["length"] = 5;
rectangle["width"] = 3;
rectangle["area"] = rectangle["length"] * rectangle['width'];

Associative array demo

Creating associative arrays using different methods and accessing elements. Create an associative array with a literal.

var x = { "one": 1, "two": 2, "three": 3 };
for(var i in x)
{
document. writeln(i + "=" + x[i]);
}
Result:
one=1 two=2 three=3
var myTab = new Array();
myTab['language'] = 'javascript'; myTab['website'] = 'programmeranalyst.com'; myTab['course'] = 'tables';
document.write(myTab.length); // Returns 0

Note: the length property does not apply to associative arrays

Possible solution:

var size = 0;
for(var key in myTab){
size++;
}
document.write(myTab['course']); // displays "tables"

ASSOCIATIVE MULTIDIMENSIONAL ARRAY

var newTab = new Array();
newTab['language'] = new Array('javascript','php');
newTab['type'] = new Array('executed','interpreted');
newTab['side'] = new Array('client side','server side');
document.write('The language ' +
newTab['language'][1] + ' is a language ' +
newTab['type'][1] + ' ' +
newTab['dimension'][1]); // Displays "The php language is a server-side interpreted language"

ANOTHER EXAMPLE

<html>
  
  <head>
    <title>
      Testing
    </title>
  </head>
  
  <body>
    <script type="text/javascript">
      < !--
      var employee = new Array();
      employee[0] = new Array();
      employee[0]["name"] = "Descartes";
      employee[0]["firstname"] = "John";
      employee[0]["residence"] = "Cahors";
      employ[1] = new Array() employee[1]["name"] = "Amora";
      employee[1]["firstname"] = "Celeste";
      employee[1]["residence"] = "Dijon";
      for (var i = 0; i < employee.length; i++) {
        document.write("<dl><dt>job
ye " + (i + 1) + "<\/dt>");
        for (var property in employee[i]) document.write("<dd>" + property + ":
" + employee[i][property] + "<\/dd>
");
        document.write("<\/dl>");
      }
      //-->
      
    </script>
  </body>

</html>

Iteration

for(var value in myTab){
document.write(value + ' : ' + myTab[value] +
'<br/> ');
}
// Display
language: javascript
website: analyst-programmer.com
lesson: paintings

FUNCTIONS

Syntax
function myFunction(x, foo)
{… Directions; …
return result value;
}

There are also functions related to objects
(methods), example:
document.write(),Date.getDate(),

Defined objects: Math, Date

Example

<html>
  
  <head>
    <SCRIPT language="JavaScript">
      function calculateTotal(qty, price) { // function definition
        return qty * price;
      }
    </SCRIPT>
  </head>
  
  <body>
    <script>
      alert("Total = " + calculationTotal(100, 12.5));
    </script>
  </body>

</html>

IMAGES

  • var img = new Image();
  • img. height = 80;
  • img. width = 100;
  • img.src = ‘filename’;

SOME OBJECTS

<html>
  
  <head>
  </head>
  
  <body>
    <Script language="JavaScript">
      document.write("The Properties of the window Object are: " + "<BR>");
      for (var prop in window) document.write(prop + "<BR>");
    </script>
  </body>

</html>

Date Example

<html>
  
  <head>
  </head>
  
  <body>
    <Script language="JavaScript">
      var today = new Date();
      //getDate returns the day of the Month, getMonth()
      returns Month of the year(0 = January, 1 = February, etc..) alert('The current date is: ' + today.getDate() + '/' + (today.getMonth() + 1) + '/' + today.getYear() + ' and Current time is: ' + today.getHours() + 'h:' + today.getMinutes() + 'min');
    </script>
  </body>

</html>

JAVASCRIPT EVENTS

  • onAbort
    Loading an image was interrupted
  • onBlur
    The mouse leaves a form area
  • onClick
    We click on a form or a link
  • onChange
    We change a text zone or element selection
  • onFocus
    The mouse enters a form area
  • onLoad
    Load the page in the browser
  • onMouseOut
    The mouse leaves an image area
  • onMouseOver
    The mouse hovers over a link or form
  • onReset
    We empty a form
  • onSelect
    We select an element in a form
  • onSubmit
    We send a form
  • onUnload
    We leave the page

Examples

<html>
  
  <head>
    <SCRIPT language="JavaScript">
      function verif() //write the function
      {
        if (document.email.email.value == "") alert("Your email address is missing!!");
        else document.email.submit();
      }
    </script>
  </head>
  
  <body>
    <form name="email">
      <input type="text" name="email" size="30">
      <input type="button" onClick="verif();" value="Send">
      <input type="reset" value="Empty">
    </form>
  </body>

</html>
<html>
  
  <head>
    <SCRIPT language="JavaScript">
      function analyze() {
        var x = document.response.display.value;
        document.response.display.value = 2 * x;
      }
    </script>
  </head>
  
  <body>
    <form name="answer">
      <input type="button" value="double the number entered" onClick="parse()">
      <input type="text" name="display" size="28" value="">
    </form>
  </body>

</html>