JavaScript

Suggestions for simple coding

  1. With link elements, use an HTML style attribute in your <a> tag. If you are using an external CSS3 file, enter your id to select an element to style or to use pseudo-classes such as :hover or :visited on 'a'
    				ul#thumbs a:hover li {
    					//statement
    				};
    			
  2. Likewise with input or textarea elements, use HTML inline style manipulation where you find it appropriate:
    				<input type="text" style="border: 1px solid blue">
    			

JavaScript array

When there are many values in an array, it may help to use an empty string to store all values. The following code shows how an empty string value on the left hand side of += can be filled in through a string of values:
			var aliasTable = ["a","b","c","d","e"];
			var empty = "";									//an empty string to hold values

			for(var i = 0; i < aliasTable.length; i++) {
				alert(empty += "There we have" + " " + " " + aliasTable[i] + ". ");
			}
		

When the loop ends, a dialog box displays a complete set of string values in a regular sequence

If you do not feel the need to complete a sequence, you can break the flow by using break. You need to specify an index value at which to stop the for loop:

			var aliasTable = ["a","b","c","quot;d"];
			var empty = " ";

			for(var i = 0; i < aliasTable.length; i++){
				if(aliasTable[i] == 'c'){break;}																		//Stop loop if 'c'
				else{
					alert(empty += "There we have" + " " + aliasTable[i] + ". ");			//Only the first two string values are returned from an array.
				}
			};
		

break can break out of any closing statement

JavaScript is an object-oriented language

Get familiar with object properties before you go on learning something more complicated in JavaScript. These properties are frequently used and yet their rules and syntax are easy to forget.

Do not mix up object properties with regular functions. Their syntax look alike. But objects are more loosely structured : each line of property/value is ended with a comma and no semi-colon is used after the last property value.

			var newmac = {						// Create an object called "newmac"
				topic: "customize your approach",		// Give	it a property topic and set it a string value "Customize your approach"	
				roundup : true;					// Give it a property roundup and set it a Boolean value true. No semi-colon after last property value 
			};

			alert(newmac.topic);				// access property topic with .
			alert(newmac["roundup"]);			// access property roundup with [" "]
			newmac.author = "Author";			// Create a new property .author by assignment
			alert(newmac["author"]);			// access new property .author
		

Most array objects take a variable name and an index value (in square brackets). Make sure both of these elements are present in your array declaration. If you omit a variable name, for example, a return value may not be what you would expect:

			var aliasTable = ['a','b','c','d','e'];
			var empty = [];
			var primes = aliasTable.length-1;			//Access the last numeric index value of an array (what we really wanted is the last string value)

			for(var i = 0; i < aliasTable.length; i++{
				if(aliasTable[i] == "d"){break;}
			else{
				alert(empty += "There we have" + " " + aliasTable[i] + "&" + " " + primes + ". ");
			}
		
Let this sink in:

To call the last numeric index value of an array:

			var prime = aliasTable.length-1;
		

To call the last string value of an array:

			var prime = prime["aliasTable.length-1"]
		

Notice that when you use a push() method, you are adding an element to the end of your array. In all logic, to call that element, you must call the last indexed element using name[name.length-1]. If you simply call that method by assignment, Javascript returns a numeric value indicating the position of an element in an array:

			var aliasTable =  ['a','b'','c','d','e'];
			var empty =  [];
			var primes = aliasTable[7];
			var car =  aliasTable.push("Brunswick");		// add a 6th element to your array by assignment

			for(var i = 0; i < aliasTable.length)
				if (aliasTable[i] == "Horowitz") {break;} 
			else { 
				alert(empty += "There we have" + " " + aliasTable[i] + " " + "&" + " " + primes + " " + "&" + " " + car + ".");
			}

		

Insert an element with position specifiers

Insert using insertAdjacentHTML:

			var current = document.getElementById("p1");
			current.insertAdjacentHTML("afterend","<p><em>Element</em></p>");
			
		

Original paragraph : "This is a sentence"

New paragraph:

This is a sentence

Element

Calling arguments

You can pass as many arguments to a function call as you like, but remember that a function always calls the first argument first, and then proceeds to call the second argument and so forth. This means that if you do not pass the third and fourth arguments, JavaScript will take only the first two. If you leave your parameter undefined, then JavaScript returns undefined whether you call an argument or no argument for that parameter

A simple example:
			function makeTea(cups, tea) {
				console.log("Brewing " + cups + " cups of " + tea);
				
			}
			makeTea(3);		//Only the first argument matches the parameter "cups". No argument for the parameter "tea", so it returns undefined for that parameter.
		

Appending arguments to an array with concat() method

  • This method requires a so-called "dummy"
  • The dummy is your fallback plan when straightforward assignment of the right-hand side operand to the left-hand variable is not going to work
  • The purpose of the dummy is to save a value returned by a function (it's kind of "double-checking" to see if data has been properly stored)
The dummy saves data:
			var myArray = ['a','b','c'];			// 3 arguments
			myArray = myArray.concat('d','e');		// Add values to the dummy myArray
			alert(myArray);					// This time the change has been registered: 'a','b','c','d','e'
		
Simple examples:

a = a + b            a += b            a = a.b            a = a.b()

Pass new data to some function:

			var a = "Test me";
			var b = " a new function"
			a = a + b;			// Save result of a + b  
			alert(a);			// Pass data to function
		

Make a copy and preserve the original:

			var a  = "Test me";								
			a = a + "," + "but don't overdo it";		// Make a copy of the original & add data
			alert(a);					// Alert:"Test me but don't overdo it"
		

Add an element to your array

Now it should be easy enough to understand why you need to identify the name of a variable that references another variable in which data is properly stored. The name of your array object does not need to be the same as the name of your reference variable. A second name will do just fine to fulfill the function of a dummy.
				var firstArray = ['Fiat','Ford','Mustang'];			//Your array elements correspond to index values 0,1,2
				var secondArray = firstArray;					// Your array object is assigned to a reference variable named 'secondArray'
				secondArray[3] = 'Renault';					// Use reference variable to index a new array object
				alert(firstArray);						// Your array object now contains four elements instead of three
				alert(secondArray[3]);						// You can choose to alert just the new element
			

Date object

A standard Date() object is comprised of a year, a month and a day. But JavaScript includes UTC format for more precise date objects. For details, see the table below:

UTC format for date objects:

JavaScript formatMeaning
getUTCMonth()current month - 1
getUTCDate()current day in one digit
getUTCFullYear()current year in four digits
getUTCHours()current hour in one digit
getUTCSecondscurrent second in one digit

To display an ISO8601 format:

2015-7-17TO7:31:36Z

Write:

		var dt = new Date();			// Date object including all standard units of time

		var mnth = dt.getUTCMonth();
		mnth++;					// Leave this out and we'll get one month behind

		var day = dt.getUTCDate();			
		if(day < 10) day="0" + day;			// Display a first 0 digit for all days less than ten

		var yr = dt.getUTCFullYear();				

		var hrs = dt.getUTCHours();			// Display a first 0 digit for all hours less than ten (eg. 01, 02, 03)

		var min = dt.getUTCMinutes();
		if(min < 10) min = "0" + min;			// Display a first 0 digit for all minutes less than ten

		var secs = dt.getUTCSeconds();
		if(secs < 10) secs = "0" + secs;  		//Display a first 0 digit for all seconds less than ten

		var newdate = yr + "-" + mnth + "-" + day + "T" + hrs + ":" + min + ":" + "secs" + "Z";
		document.writeln(newdate);			
	
Bibliography
  1. Flanagan, David, JavaScript : The Definitive Guide
  2. Powers, Shelley, JavaScript Cookbook
  3. Van Lancker, Luc, HTML5 et CSS3 : Maîtrisez les standards des applications Web