Home |
Last modified: 16-06-2020 |
Directory of d:\Temp\JavaScript.books
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
A simple setup is...
Next, create this basic text file, and aim your browser at Mongoose:
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:
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/
First, note that JavaScript is case-sensitive, so watch out for typos.
The code itself is surrounded by a <script> tag:
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:
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 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" must always be in lower-case. Functions that actually need to return a value must use... "return".
Here's an example of some JS code being called to respond to an event:
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?
To prompt the user:
To run a function every so often: setTimeOut();
To access an element in a page: document.getElementById
To avoid dumping error messages on the screen, use the familiar try/catch:
If you want to trigger an error on purpose:
JavaScript is an object-oriented language. See JavaScript and HTML DOM Reference for a list of methods/properties available in standard objects.
Here's how to search and replace some text between the BODY tags:
... and here's how to include and run this script once the page is loaded:
Here's how to search/replace text anywhere in an HTML document, not just in the BODY section (browser-dependent):
More information in JavaScript RegExp Object.
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:
And here's a working example:
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:
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.
Note: Each id must be unique.
Edit index.html:
Edit main.js:
To draw a circle and text:
How to write loops:
To handle user input, Paper needs a "tool":
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:
For variables, JS supports primitives (number, string, etc.) and objects (array, date, etc.)
ES6 introduced string templates (or string interpolation):
Use this for multiline strings:
Symbols are a new data type representing unique tokens:
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:
How to return value:
ES6 lets you define default args:
How to define a 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:
Anonymous function:
Arrow notation:
Calling function through this:
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:
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:
Lexical scoping in JavaScript applies to global scope, block scope, and function scope.
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:
To experiment with JavaScript:
"use strict"; ("It’s time to start using JavaScript strict mode")
To output infos, try console.log and alert()
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:
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:
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
Add "debugger;" in your js code to force the browser to stop and let you debug the code in eg. Visual Studio.
Check for syntax errors?
Syntax highlighting?
Code autocompletion?
Detect run-time errors?
"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."
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."