Introduction to JavaScript

Introduction

JavaScript is C-style, object-oriented, clear-text, ie. non-binary, code embedded in an HTML page that is run on the client host. It has nothing to do with Java, ie. no need to install the Java Virtual Machine/JVM on the client host, but the web browser obviously has to support JavaScript and have this option enabled (some users disable this.)

Along with Java applets, ActiveX widgets, and Flash, JavaScript is the only way to execute code on the client host, but, for security reasons, has voluntarily a very basic set of instructions.

Basically, you will use JavaScript for light things like animation (eg. showing a calendar to enable the user to input a date with point-and-click) or checking inputs typed in a form (saving yourself a round-trip to the server, in case some fields are either missing or wrong.) JS is often used to make web pages event-driven.

Combined with the DOM (Document Object Model, an object model), JavaScript can be used to manipulate items in a page, which is the whole idea of AJAX.

Setup

A simple setup is...

  1. your favorite text editor with at least JavaScript syntax highlighting and ideally, code autocompletion
  2. the stand-alone Mongoose web server
  3. either Google Chrome or Firefox as the browser

Next, create this basic text file, and aim your browser at Mongoose:

<html>
        <head>
        </head>
        <body>
                <script type="text/javascript">
                        alert("hello");
                </script>
        </body>
</html>

Note: "<script language="javascript>" is deprecated. Use "<script type="text/javascript">" instead.

As you write more JavaScript code, it's better to keep it in a separate file. Here's the above rewritten accordingly:

"use strict";
 
//mycode.js
function myfunc(){
        alert("hello");
}
 
//index.html
<html>
        <head>
                <script type="text/javascript" src="mycode.js"></script>
        </head>
 
        <body>
                <script>
                        myfunc();
                </script>
        </body>
</html>

Programming

First, note that JavaScript is case-sensitive, so watch out for typos.

The code itself is surrounded by a <script> tag:

<script type="text/javascript">
    <!--
        //UNSAFE! document.write("Hello World!");
        if(document.getElementById("theid") != null){
            document.getElementById("theid").innerHTML="Hello World!";
        }
    //-->
</script>

The comments are optional, and can be used to make sure that older browsers that don't know JavaScript do not display JS code. If you prefer to keep JavaScript code into an external file, just make sure its extension is set to ".js", and add the SRC attribute:

<script type="text/javascript" src="hello.js">
</script>

It's generally best to load JS code in the <HEAD> section of the page, to make sure that it is available before the user does anything.

As a basic debug feature, use console.log(), and enable the JavaScript console in your browser.

How to tell browser to cache jQuery and update when necessary?

Variables

Variables are either global (if declared outside any function) or local (declared inside a function). Note that a variable that is declared inside a routine still requires the "var" argument for its scope to be local:

function newFunction()
{
    var loop=1;
    total=0;
}

Functions

"function" must always be in lower-case. Functions that actually need to return a value must use... "return".

Events

Here's an example of some JS code being called to respond to an event:

<a href="" onMouseOver="popupFunc();">

Common events are onClick, onChange, onFocus, onBlur, onMouseOver, onMouseOut, onSelect, onSubmit, onResize, onLoad, onUnload.

Should I use "<input type="button" onclick="show_alert()" value="Show alert box" />" OR "<input type='button' id='mybutton'/>" + JS elsewhere?

Prompting the user

To prompt the user:

Running a function regularly

To run a function every so often: setTimeOut();

Accessing elements in a page

To access an element in a page: document.getElementById

Error handling

To avoid dumping error messages on the screen, use the familiar try/catch:

try
  {
  //Run some code here
  }
catch(err)
  {
      //Handle errors here
      alert(err.description);
  }

If you want to trigger an error on purpose:

try
  {
    throw "Err1";
  }
catch(er)
  {
  if(er=="Err1")
    {
    alert("Error! The value is too high");
    }
  }

Objects

JavaScript is an object-oriented language. See JavaScript and HTML DOM Reference for a list of methods/properties available in standard objects.

Updating contents through regular expressions

Here's how to search and replace some text between the BODY tags:

//test.js
function myscript() {
    input = new RegExp("change me","gi");
    output = 'CHANGE ME';
    document.body.innerHTML = document.body.innerHTML.replace(input,output);
}

... and here's how to include and run this script once the page is loaded:

<html>
<head>
        <!--Note: "src" syntax differs in IE and Opera; In IE, remove "file://localhost/"
        <script type="text/javascript" src="file://localhost/C:/test.js"></script>
        </script>
</head>
<body OnLoad="myscript();">
change me
</body>
</html>

Here's how to search/replace text anywhere in an HTML document, not just in the BODY section (browser-dependent):

function myscript() {
    doco = document.documentElement.outerHTML;
    input = new RegExp("body","gi");
    output = 'BODY';
    document.documentElement.outerHTML = doco.replace(input,output);
}

More information in JavaScript RegExp Object.

Displaying a date picker

jQuery's DatePicker is pretty good and free. Here's how to localize it so that it returns date as DD/MM/YYYY, uses Monday as the first day of the week, and translates the day + month names:

  1. Go to http://jqueryui.com/download/
  2. Click on "Components >  Toggle All" to uncheck all the options
  3. Go to Widgets > Datepicker, and select this one item
  4. Scroll down to Download
  5. Open the jquery-ui-1.9.0.custom.zip file, and extract the relevant localization file:
    jquery-ui-1.9.0.custom\development-bundle\ui\i18n\
  6. On your web server, create a .\js directory where you will copy the file

And here's a working example:

<head>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css" />
    <link rel="stylesheet" href="/resources/demos/style.css" />
 
    <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
    <script src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
    <script src="js/jquery.ui.datepicker-fr.js"></script>
 
    <script>
                $(function() {
                      $('#datepicker').datepicker({showOn: 'button',
                            buttonImage: 'images/calendar.gif', buttonImageOnly: true});
                });
    </script>
</head>
 
<body>
 <p>Date: <input type="text" id="datepicker" /></p>
 </body>

Reading Notes: "JavaScript: The Definitive Guide, 6th Ed."

Chapter 1 Introduction

To experiment with JavaScript:

"use strict"; ("Itís time to start using JavaScript strict mode")

To output infos, try console.log and alert()

Chapter 2 Lexical Structure

Chapter 3 Types, values, and Variables

Chapter 4 Expressions and Operators

Object = collection of properties (property = name + value)

Object types = objects, arrays, and functions

Types:

Note that primitive values (undefined, null, booleans, numbers, and strings) and objects are immutable, ie. they can't change, while objects and arrays are mutable. "immutable" means that a new variable will be silently created and the old one emoved by the garbage collector; It will not trigger an error.

Classes are subtypes of the object type: Function, Array, Date, RegExp, Error

Methods = functions assigned to properties of an object. "this" refers to object on which method is defined.

Only objects really have methods, but primitive data types (numbers, strings, boolean) behave as if they had methods.

Arithmetic: JS doesn't raise errors for over/underflow or division by zero. Check for Infinity, -Infinity, "negative zero" (negz), and NaN ("not a number").

Functions are true values and can be treated like regular objects:

myobj.mymethod = function(){ ...}

Event handlers can be registered.

$() : function often used by jQuery

Unlike HTML, JavaScript is case-sensitive: Make it a habit to write HTML to match case used in JS.

Global object ("this"): includes globally defined symbols (properties, functions, etc.) available to a JS program

Window object: on client-side JS, global object for all JS code contained in browser window. "window" property = "this". Core global properties + few globals

Variables are visible within the function in which they are defined, so watch for "hoisting".

Declaring a global variable means defining a property of the global object; if you use "var", it is nonconfigurable, ie. cannot be deleted with the "delete" operator:

var myvar = 1;
delete myvar; //won't work

When not using strict mode, assigning a value to an undeclared variables automatically creates a global variable.

Caution: In a function, it doesn't matter where a variable is declared: it's available anywhere, even before it's used!

Why is variable not declared with "var" deletable while "var" variables isn't?

"===" tests for strict equality, and "!==" for strict unequality.

Learn more about eval()

If ... throw new Error("boom") : jumps to nearest try/catch/finally

Testing and debugging

Add "debugger;" in your js code to force the browser to stop and let you debug the code in eg. Visual Studio.

Tools

Check for syntax errors?

Syntax highlighting?

Code autocompletion?

Detect run-time errors?

"JSLint vs JSHint"

"Browser Independent JavaScript debugger?"

Google Chrome: Wrench icon > Tools > Developer Tools

"JSHint is a tool to detect errors and potential problems in JavaScript code and can be used to enforce coding conventions."

JSLint (same as JSHint)

Firefox:

"Jslibs is a standalone JavaScript development runtime environment for using JavaScript as a general-purpose scripting language. Jslibs uses SpiderMonkey library that is Gecko's JavaScript engine (SpiderMonkey is used in various Mozilla products, including Firefox). The latest version of jslibs uses the new TraceMonkey/JaegerMonkey library with tracing/method JIT enabled. jslibs provides a set of native modules that contains various general purpose classes and functions."

"Microsoft's F12 Developer Tools is a suite of tools to help you build and debug your webpage" (specific to Internet Explorer)

"Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications." It is an event-based framework for creating network applications so it can be used to write server-side applications in JavaScript. SAID TO BE BUGGY

"JsFiddle is a playground for web developers, a tool which may be used in many ways. One can use it as an online editor for snippets build from HTML, CSS and JavaScript."

Jsconsole.com

Rhino ("open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users.")

"V8 is Google's open source JavaScript engine. V8 is written in C++ and is used in Google Chrome, the open source browser from Google."

"envjs: good-enough browser/DOM environment, written in JavaScript, that (currently) runs on top of Rhino; capable of running JavaScript libraries like jQuery, Prototype, and MochiKit (at the very least)."

"GLUEscript (Glueing Libraries Using EcmaScript) is the successor of wxJavaScript. The new name covers the goal of this project: create a JavaScript engine which can be used as a general purpose language (like Perl for instance)."

"Jls is a general-purpose JavaScript platform. It aims to provide an extensible tooling framework. Jls can be used for various purposes including client-side, server-side or desktop scripting. Jls comes in two parts: a low level set of native libraries and a set of JavaScript libraries."

"JSDB is JavaScript for databases, a scripting language for data-driven, network-centric programming on Windows, Mac, Linux, and SunOS. JSDB works with databases, XML, the web, and email. It is free and open-source. Use it as a JavaScript shell, to run CGI programs, or as a web server."

"Aptana Studio is an open source integrated development environment (IDE) for building Ajax web applications. Based on Eclipse, it supports JavaScript, HTML, DOM and CSS with code-completion, outlining, JavaScript debugging, error and warning notifications and integrated documentation." "Aptana is dog slow. It has been buggy and slow since it first came out many years ago and has not improved in that respect. Avoid."

"JetBrains WebStorm is a commercial IDE for JavaScript, CSS & HTML built on JetBrains' IntelliJ IDEA platform."

"IntelliJ IDEA is a commercial Java IDE by JetBrains. It is often simply referred to as "IDEA" or "IntelliJ"."

"These days, most use Chrome's Developer Tools =] (built-in)"

"JavaScript support has improved a lot in Visual Studio 2008"

"NetBeans is an integrated development environment (IDE) for developing primarily with Java, but also with other languages, in particular PHP, C/C++, and HTML5. It is also an application platform framework for Java desktop applications and others."

Q&A

 

Resources

Books

Forums

Other