Science Library - free educational site

Javascript basics

JavaScript is a client-side computing programme (or script), invented by Brendan Eich, and first released in 1995. Client-side means everything happens on the computer in front of the user. Other client-side scripts you will use on your websites are HTML and CSS. JavaScript has till recently found application as an interpreted language, but just-in-time (JIT) compilation is being progressively used on browsers. JavaScript has been standardized in the ECMAScript language specification.

The other type of programme is 'server-side', which works by interacting with the server online. Examples of server-side programmes are: PHP, .NET, Ruby on Rails, ASP, ColdFusion. MySQL is a 'structured query language' allowing data to be input, edited and extracted from a database on a server.

Effective web applications can be made by combining (rather cleverly I might add) client-side and server-side technologies. For example, JavaScript handles a client's inputs on a page (such as checking for completeness of a form), and when everything is ready, the programme sends the data to a database on a server. It can then reload the page (or reset the information on the page without reloading, using AJAX). This data, or any other data, can then be returned to the browser page on the client's device, and displayed and manipulated by client-side programmes.

These days of highspeed internet connections, this often happens so smoothly and seamlessly the client is unaware of the complexity of the action on his or her screen.

JavaScript basic scripts

JavaScript <script> tags inform the browser that everything between the tags is to be interpreted as JavasScript code and executed accordingly.

<script>
alert("This JS script works on my computer!");
</script>

Note that in the above example, all the JavaScript commands are placed inside special tags (<script>...</script>), which separate your JS code from the HTML or PHP code. In the past, it was necessary to declare the javascript by including type="text/javascript" in the first script tag. This is a declaration of the type, so the browser is clear about how the following code is structured. In modern browsers this is no longer necessary.

The 'alert' inside the tags is a function. Functions can be custom-made or built in already to browsers, so they know what to do when they come across one with this name. The function 'alert' brings up a pop-up window on the screen containing the message inside the parentheses and quote marks.

Including JS files

It is good practice to separate structure (the basic HTML page) from its styling (CSS) and function (JS), by including external CSS and JS files. An included JS file should not have opening and closing <script>...</script> tags, since the HTML file calling the script has already opened the them.

// To pull a JavaScript <script> file from an on-site folder, or from another site, use the following script :

<script src="path/yourscript.js">
</script>

There is a need to consider the timing of the download of external JS files. The sequence may be important, and it may be advantageous (or necessary) to prevent the script from running till after the whole page has been downloaded and parsed. There are two attributes which control the behaviour and timing of external JS file downloads and execution:

<script defer src="path/yourscript.js"> </script>

<script async src="path/yourscript.js"> </script>

The defer attribute appears in script tag. It signals the browser to download the file, but not to attempt to run the code until after the page has rendered. If there is more than one defer flagged scripts, then the scripts will be executed in the sequence they appear, and before the DOMContentLoaded event. Best practice is to place all scripts with defer attributes at the end of the file, and not use both defer and DOMContentLoaded events, to avoid clashes.

The async attribute does the opposite of defer: it loads and begins to execute the JS file immediately. They execute before the load event, but may execute after the DOMContentLoaded event. It is safest to use the async attribute only with files which do not modify the DOM as they load.

Browsers which do not permit JavaScript

Because in the early days of JavaScript, unscrupulous webmakers saw it fit to create invasive functions, such as pop-ups and annoying flashing items, JavaScript gained a bad reputation. For this reason, browsers began to offer the option of switching off JavaScript. However, this was throwing the baby out with the bathwater, and vital functionality was being lost from the user experience.

If the browser in question has been set to reject JavaScript, everything between the tags will be ignored. To get around this problem, the user can be notified that his or her browser is blocking JavaScript functionality, which may be essential for good operation of the site:

<noscript> <META HTTP-EQUIV="Refresh" CONTENT="0;URL=http://www.sciencelibrary.info/inc/no_js.php"> </noscript>

In the above example, pages on www.sciencelibrary.info will launch an application contained in a file called appropriately no_js.php, which advises the user that the page will not work properly without JavaScript enabled, and explains how to re-enable their browser to return to full functionality.

JavaScript Syntax

As opposed to PHP, Javascript does not always require a semi-colon at the end of a command line. A line return is sufficient to inform the script that the next string is a new instruction. However, if two commands are on the one line (not recommended practice), a semi-colon is necessary.

Operators

There are two types of operators in JavaScript: aristhmetic and assignment.

Arithmetic Operators

Logic and mathematical operations can be performed in JavaScript, as in most scripting languages, by using these operators:

a = 6; b = 4;

OperatorOperationExampleReturns
*multiplicationa*b24
/divisiona/b1.5
+additiona+b10
-subtractiona-b2
++incrementa++7
--decrementa--5
%modulusa%b2

A common application of ++ is the count in a loop.

++i will increase the value of the variable i with each iteration of the loop. If the initial value i = 1, by setting a conditional for the loop as:

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

The loop will run up to 10 times before exitting.

Assignment Operators

Assignment operators assign values to variables.

a = 5;

OperatorOperationExampleReturns
a = xassigns the value x to variable aa=1212
a += xincrements current value of a by xa += 16
a += 'string'concatenates the string to variable aa+= ' plus VAT'5 plus VAT
a -= xsubtracts value x from current value of aa-=14
a *= xmultiplies current value of a by xa*=210
a /= xdivides current value of a by xa/=22.5
a %= xreturns a modulus xa%=21

Example 1:

var valueA = 6;

var valueB = 15;

var valueC = --valueA + valueB; //outputs 20

var valueD = valueA + valueB; //outputs 20

In Example 1, valueA is decremented in the statement var valueC = --valueA + valueB;, and this value (5) is used in any subsequent statement.

Example 2:

var valueA = 6;

var valueB = 15;

var valueC = valueA-- + valueB; //outputs 21

var valueD = valueA + valueB; //outputs 20

In Example 2, valueA is decremented in the statement var valueC = valueA-- + valueB; after the calculation of valueC.

Error Handling

onError

Every element on a webpage can trigger JavaScript functions when specified events occur. These events can be mouse actions (onClick, onHover, ...).

A useful way to control and safeguard the effective running of a script is to create a custom function to be called when an error is detected:

onerror = errorFunction();

document.write(Welcome to this error!)

//the string is missing quotation marks, so will trigger an error

function errorFunction(message, url, line) {

msg = "There has been an error.\n"

msg = "Error: " + message + "\n"

msg = "On page: " + url + "\n"

msg = "In line: " + line + "\n\n"

alert(msg);

return true

}

Standard cross-browser onerror handling

HTML:

JS: object.addEventListener("error", Text);

JS: object.onerror=function(){Text};

Try...Catch

A more flexible system for handling errors uses the keywords try and catch. These keywords allow the script to control how errors are handling for individual sections of code rather than the previously described global onerror techniques.

try

{

// code routine no. 1

}

catch(err)

{

// code routine no. 2

}

finally

{

// code routine no. 3

}

The catch(err) is run only if try encountered an error. finally is optional, and is run in every case, regardless of whether try encountered an error or not.

Redirecting a page in JavaScript

Often, it is necessary to redirect the URL from one page to another. This can be accomplished in JS by simply writing a condition which, if true, will execute this code:

window.location = "http://www.newurl.com";

Some Terms:

  • API
  • Application Programming Interface: the set of routines, protocols and tools used in constructing software applications. API is used for programming GUI (graphical user interface) components, and specifies how the various software components of a complex programme should interact.

  • ECMA
  • European Computer Manufacturers Association. JavaScript 1.1 was submitted to the EMCA in 1997 to "standardise the syntax and semantics of a general purpose, cross-platform, vendor-neutral scripting language. The result was EMCA-262, known as ECMAScript.

  • ECMAScript
  • ECMAScript is an ISO/IEC standard for client-side web scripting languages. It is used in JavaScript, Microsoft's JScript, and ActionScript. The description which appears in the ECMA-262 edition 5.1, June 2011, documentation:

    "ECMAScript was originally designed to be a Web scripting language, providing a mechanism to enliven Web pages in browsers and to perform server computation as part of a Web-based client-server architecture. ECMAScript can provide core scripting capabilities for a variety of host environments, and therefore the core scripting language is specified in this document apart from any particular host environment."

    ECMA-262 edition 5.1, June 2011.pdf

Content © Renewable-Media.com. All rights reserved. Created : June 1, 2014 Last updated :March 10, 2016

Latest Item on Science Library:

The most recent article is:

Trigonometry

View this item in the topic:

Vectors and Trigonometry

and many more articles in the subject:

Subject of the Week

Environment

Environmental Science is the most important of all sciences. As the world enters a phase of climate change, unprecedented biodiversity loss, pollution and human population growth, the management of our environment is vital for our futures. Learn about Environmental Science on ScienceLibrary.info.

Environmental Science

Great Scientists

Archimedes

c. 287 - 212 BCE

Archimedes was a Greek, living in Magna Graecia. He is considered one of the greatest mathematicians and engineers of the ancient world, and the source for many fascinating stories and anecdotes.

Archimedes
Vitruvian Boy

Quote of the day...

The difficulty lies not so much in developing new ideas as in escaping from old ones.

ZumGuy Internet Promotions

Umwelt.Science