Introduction to JavaScript

TO READ

Directory of d:\Temp\JavaScript.books

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, offers a very basic set of instructions voluntarily.

Basically, you will use JavaScript for light tasks 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.

JQuery? https://en.wikipedia.org/wiki/JQuery

Node.js? https://en.wikipedia.org/wiki/Node.js

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>

IDE

Webstorm https://www.jetbrains.com/webstorm/

Komodo Edit https://www.activestate.com/komodo-edit

Visual Studio Code https://code.visualstudio.com/

Atom IDE https://ide.atom.io/

Brackets http://brackets.io/

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: "Learning JavaScript- 3rd ed." - Brown (O'Reilly Media, 2016)

Comments in JS like in C/C++ : // or /* */ ; Comments in HTML : <!-- this is an HTML comment... -->

Keep HTML, CSS, and JS separate.

To output data to the console: console.log('main.js loaded');

While we could have put the <script> tag in the head, there are performance and complexity reasons for putting it at the end of the body.

To open the console in Chrome: (menu) > More Tools > Developer tools (or CTRL+SHIFT+I)

Console can also be used to enter JavaScript directly, thereby testing things out.

jQuery: extremely popular client-side scripting library. Here's how to add it:

<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="main.js"></script>

jQuery provides the following feature to wait until the browser has loaded the HTML, and then run this function:

$(document).ready(function() {
    'use strict';
    console.log('main.js loaded');
});

HTML5 brought a standardized graphics interface to draw graphics primitives like squares, circles, and polygons. To make it easier to use canvas, use a graphics library such as Paper.js.

index.html
<body>
<canvas id="mainCanvas"></canvas>
</body>

Note: Each id must be unique.

main.css
#mainCanvas {
    width: 400px;
    height: 400px;
    border: solid 1px black;
}

Edit index.html:

<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.9.24/paper-full.min.js"></script>
<script src="main.js"></script>

Edit main.js:

$(document).ready(function() {
        'use strict';
 
        paper.install(window);
        paper.setup(document.getElementById('mainCanvas'));
        var c = Shape.Circle(200, 200, 50);
        c.fillColor = 'green';
        paper.view.draw();
});

To draw a circle and text:

var c = Shape.Circle(200, 200, 80);
c.fillColor = 'black';
 
var text = new PointText(200, 200);
text.justification = 'center';
text.fillColor = 'white';
text.fontSize = 20;
text.content = 'hello world';

How to write loops:

for(var y=25; y<400; y+=50) {
    c = Shape.Circle(x, y, 20);
    c.fillColor = 'green';
}

To handle user input, Paper needs a "tool":

var tool = new Tool();
//Asynchronous event: Wait for use to click on canvas
tool.onMouseDown = function(event) {
    var c = Shape.Circle(event.point.x, event.point.y, 20);
    c.fillColor = 'green';
};

Useful development tools:

Until ES6/JS6 is widely used, transcompilation (also called transpilation) is required to convert ES6 code into ES5.

Git required to run terminal?

Node (npm) required?

Grunt/Gulp build tools required?

Visual Studio required? "Many npm packages have a dependency on Visual Studio build tools. You can get a free version of Visual Studio from the product download page."

"React (a.k.a. React.js or ReactJS) is a JavaScript library for building user interfaces. It is maintained by Facebook and a community of individual developers and companies."

Is transpilation from ES6 to ES5 still recommended?

Declaring and initializing variables and constants:

let targetTempC, room1 = "conference_room_a";
const ROOM_TEMP_C = 21.5;

For variables, JS supports primitives (number, string, etc.) and objects (array, date, etc.)

ES6 introduced string templates (or string interpolation):

let currentTemp = 19.5;
const message = `The current temperature is ${currentTemp}\u00b0C`;

Use this for multiline strings:

const multiline = "line1\n" +
"line2\n" +
"line3";

Symbols are a new data type representing unique tokens:

const RED = Symbol();

Use "null" but leave "undefined" to JavaScript.

Objects are defined thusly:

const obj = {};

Let’s add a property color to obj :

obj.size; // undefined

obj.color; // "yellow"

obj["not an identifier"] = 3;

obj["not an identifier"]; // 3

Another way to define objects:

const sam1 = {

name: 'Sam',

age: 4,

};

Objects can also contain functions:

sam3.speak = function() { return "Meow!"; };

How to call it:

sam3.speak(); // "Meow!"

How to remove a member:

delete sam3.speak;

numbers, strings, and booleans have corresponding object types ( Number , String , and Boolean ):

const s = "hello";

s.toUpperCase(); // "HELLO"

What JavaScript is doing is creating a temporary String object (which has a function toUpperCase , among others). As soon as the

function has been called, JavaScript discards the object.

Arrays are not homogeneous; each individual element can be of any type.

const a2 = [1, 'two', 3, null];

const a4 = [ // array containing objects

{ name: "Ruby", hardness: 9 },

{ name: "Diamond", hardness: 10 },

{ name: "Topaz", hardness: 8 },

];

 

Arrays have a property length , which returns the number of elements in the array:

const arr = ['a', 'b', 'c'];

arr.length;

// get the first element:

arr[0]; // 'a'

// the index of the last element in arr is arr.length-1:

arr[arr.length - 1]; // 'c'

JavaScript Object Notation (JSON), a JavaScript-like data syntax used quite frequently, does not allow trailing commas.

Date is one of the more problematic aspects of the language. Originally a direct port from Java (one of the few areas in which JavaScript

actually has any direct relationship to Java), the Date object can be difficult to work with, especially if you are dealing with dates in

different time zones.

const halloweenParty = new Date(2016, 9, 31, 19, 0); // 19:00 = 7:00 pm

halloweenParty.getDay(); // 1 (Mon; 0=Sun, 1=Mon,...)

Regex:

// extremely simple email recognizer

const email = /\b[a-z0-9._-]+@[a-z_-]+(?:\.[a-z]+)+\b/;

// US phone number recognizer

const phone = /(:?\+1)?(:?\(\d{3}\)\s?|\d{3}[\s-]?)\d{3}[\s-]?\d{4}/;

To convert string to number:

const numStr = "33.3";

const num = Number(numStr); // this creates a number value, *not* an instance of the Number object. If the string can’t be converted to

a number, NaN will be returned

const c = parseFloat("15.5 kph"); // the " kph" is ignored; parseFloat // always assumes base 10

const n = b ? 1 : 0;

const arr = [1, true, "hello"];

arr.toString(); // "1,true,hello"

let funds = 50; // starting conditions

while(funds > 1 && funds < 100) {

// place bets

// roll dice

// collect winnings

}

if(funds > 1) {

    console.log("There's money left! Keep playing!");

} else {

console.log("I'm broke"!);

console.log("Time to quit.")

}

let remaining = totalBet;

do {

let bet = rand(1, remaining);

let face = randFace();

bets[face] = bets[face] + bet;

remaining = remaining - bet;

} while(remaining > 0);

const hand = [];

for(let roll = 0; roll < 3; roll++) {

hand.push(randFace());

}

Control flow:

if then, while/do while, for/for in/for of, break/continue/return/throw, switch, etc.

When you don’t provide the parentheses, you’re simply referring to the function just like any other value, and it’s not invoked. Try the following in a JavaScript console:

getGreeting(); // "Hello, World!"
getGreeting; // function getGreeting()
const o = {};
o.f = getGreeting;
o.f(); // "Hello, World!"

How to return value:

function getSentence({ subject, verb, object }) {
return `${subject} ${verb} ${object}`;
}

ES6 lets you define default args:

function f(a, b = "default", c = 3) {
return `${a} - ${b} - ${c}`;
}

How to define a method:

const o = {
name: 'Wallace', // primitive property
bark() { return 'Woof!'; }, // function property (method)
}

Inside a function body, a special read-only value called this is available. Normally, the this keyword relates to functions that are properties of objects. When methods are called, the this keyword takes on the value of the specific object it was called on:

const o = {
name: 'Wallace',
speak() { return `My name is ${this.name}!`; },
}

Anonymous function:

const f = function() {
// ...
};

Arrow notation:

const f3 = function(a, b) { return a + b; }
// OR
const f3 = (a,b) => a + b;

Calling function through this:

const bruce = { name: "Bruce" };
const madeline = { name: "Madeline" };
 
// this function isn't associated with any object, yet
// it's using 'this'!
function greet() {
return `Hello, I'm ${this.name}!`;
}
 
greet(); // "Hello, I'm !" - 'this' not bound
greet.call(bruce); // "Hello, I'm Bruce!" - 'this' bound to 'bruce'
greet.call(madeline); // "Hello, I'm Madeline!" - 'this' bound to 'madeline'

apply is identical to call except the way it handles function arguments. call takes arguments directly, just like a normal function. apply takes its arguments as an array:

update.apply(bruce, [1955, "actor"]);
// bruce is now { name: "Bruce", birthYear: 1955,
// occupation: "actor" }
update.apply(madeline, [1918, "writer"]);
// madeline is now { name: "Madeline", birthYear: 1918,
// occupation: "writer" }

apply is useful if you’ve got an array and you want to use its values as arguments to a function. The classic example is finding the minimum or maximum number in an array.

bind allows you to permanently associate a value for this with a function. Imagine we’re passing our update method around, and we want to make sure that it always gets called with bruce as the value for this , no matter how it’s called (even with call , apply , or another bind ). bind allows us to do that:

const updateBruce = update.bind(bruce);

Lexical scoping in JavaScript applies to global scope, block scope, and function scope.

console.log('before block');
{
    console.log('inside block');
    const x = 3;
    console.log(x): // logs 3
}
console.log(`outside block; x=${x}`); // ReferenceError: x is not defined

Note:  there’s little practical use for standalone blocks

It’s quite common to intentionally define a function in a specific scope so that it explicitly has access to that scope. This is usually called a closure (you can think of closing the scope around the function). Let’s look at an example of a closure:

let globalFunc; // undefined global function
{
    let blockVar = 'a'; // block-scoped variable
    globalFunc = function() {
        console.log(blockVar);
    }
}
globalFunc(); // logs "a"

 

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."

IDE

https://ourcodeworld.com/articles/read/200/top-7-best-free-web-development-ide-for-javascript-html-and-css

https://codelite.org/

 

"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