JavaScript

From Things and Stuff Wiki
(Redirected from JS)
Jump to navigation Jump to search


todo; sort this mess

General

1995


Learning

  • A Survey of the JavaScript Programming Language - This document is an introduction to the JavaScript Programming Language for professional programmers. It is a small language, so if you are familiar with other languages, then this won't be too demanding. Douglas Crockford, 2002
  • JavaScript Quiz is meant for recruiters to present to front-end developer candidates. The intent is to weed out some "Just use jQuery" applicants, but allow those that know JavaScript to pass fairly easily.

Online courses

  • Codecademy: Javascript- In this track you will get started programming with the basic concepts of Javascript like variables, functions, loops, and conditionals. These concepts are shared across programming languages, so you will be able to bring what you have learned to projects in any language. After finishing this track, you’ll be able to create programs, games, and have a foundation for learning JavaScript frameworks.

Screencasts

Books

  • JSbooks - The best free JavaScript resources

Videos

Articles

Games

Specs

ECMAScript 5

  • Wikipedia:ECMAScript
  • ECMAScript wiki - for the ongoing specification work of Ecma TC39, the technical committee tasked with standardization of the ECMAScript programming language. Most of the wiki is world-readable, meaning that anyone can view the pages. Certain sections are restricted to members of the technical committee.

ECMAScript 6


  • https://github.com/google/traceur-compiler - a JavaScript.next-to-JavaScript-of-today compiler that allows you to use features from the future today. Traceur supports ES6 as well as some experimental ES.next features.

CommonJS

  • CommonJS - JavaScript spec does not define a standard library that is useful for building a broader range of applications. The CommonJS API will fill that gap by defining APIs that handle many common application needs, ultimately providing a standard library as rich as those of Python, Ruby and Java. The intention is that an application developer will be able to write an application using the CommonJS APIs and then run that application across different JavaScript interpreters and host environments.
  • Wikipedia:CommonJS - is a project with the goal of specifying an ecosystem for JavaScript outside the browser (for example, on the server or for native desktop applications).

WebAPI

Engines

  • http://en.wikipedia.org/wiki/JavaScript_engine - a computer program that executes JavaScript (JS) code. The first JS engines were mere interpreters, but all relevant modern engines utilize just-in-time compilation for improved performance. JS engines are developed by web browser vendors, and every major browser has one. In a browser, the JS engine runs in concert with the rendering engine via the Document Object Model (DOM). The use of JS engines is not limited to browsers. For example, the Chrome V8 engine is a core component of the popular Node.js runtime system.

V8

  • V8 JavaScript engine - Google’s open source high-performance JavaScript and WebAssembly engine, written in C++. It is used in Chrome and in Node.js, among others. It implements ECMAScript and WebAssembly, and runs on Windows 7 or later, macOS 10.12+, and Linux systems that use x64, IA-32, ARM, or MIPS processors. V8 can run standalone, or can be embedded into any C++ application.

JavaScriptCore

  • https://trac.webkit.org/wiki/JavaScriptCore - the built-in JavaScript engine for WebKit. It currently implements ​ECMAScript as in ​ECMA-262 specification. JavaScriptCore is often referred with different names, such as ​SquirrelFish and ​SquirrelFish Extreme. Within the context of Safari, Nitro and Nitro Extreme (the marketing terms from Apple) are also commonly used. However, the name of the project and the library is always JavaScriptCore.


Rhino


JSVM

  • https://github.com/jawb/JSVM - Javascript virtual machine is one instruction set machine to parse and execute an assembly like code. This machine is written to be used by students studying compilers and willing to test and debug generated byte code in a simple manner.

Deno

  • Deno - Next-generation JavaScript Runtime Secure by default Native support for TypeScript and JSX Testing, linting, formatting, and more out of the box High performance async I/O with Rust and Tokio Backwards compatible with Node.js and npm

Run-time

Node.js

See Node.js

Nexus.js

  • https://github.com/voodooattack/nexusjs - a multi-threaded JavaScript run-time built on top of JavaScriptCore (Webkit) with a focus on high performance and dynamic scaling above all else.Nexus.js uses an asynchronous, non-blocking I/O model, and a thread-pool scheduler to make the most of modern hardware concurrency. Nexus.js is Promise-based and embraces ES6 in full; and as a result, it is not compatible with Node.js APIs.


Development

Code formatting

  • Superhero.js - Creating, testing and maintaining a large JavaScript code base is not easy — especially since great resources on how to do this are hard to find. This page is a collection of the best articles, videos and presentations we've found on the topic.
  • JavaScript The Right Way - An easy-to-read, quick reference for JS best practices, accepted coding standards, and links around the Web]
  • idiomatic.js - Principles of Writing Consistent, Idiomatic JavaScript. This is a living document and new ideas for improving the code around us are always welcome. Contribute: fork, clone, branch, commit, push, pull request.


Documentation

  • JsDoc Toolkit is an application, written in JavaScript, for automatically generating template-formatted, multi-page HTML (or XML, JSON, or any other text-based) documentation from commented JavaScript source code.


Syntax

Comments

// this is a comment
/* this is
a multiline
comment */

Operators

=
  assignment
==
  equivalency comparison
===
  strictly equak with no type conversion
condition ? expr1 : expr2
typeof
  returns string indicating the type of unevaluated operand

Statements

varname1 = 42
  declare a global and local variable with the value 42. not strict mode compliant!
var test123
  declare variable without value, i.e., 'undefined'

const newtest321 = 666
  declare an immutable variable

if...else

if (condition1)
  statement1
else if (condition2)
  statement2
else if (condition3)
  statement3
...
else
  statementN

loop

for
for ([initialExpression]; [condition]; [incrementExpression])
  statement
for (i=0; i<=101; i++) { doThis(); }
for...in
for (variable in object) {
  statements
}
for (x in arrayThing.length) {
  soemthing;
}
for...of
for (variable of object)
  statement
while
while (condition)
  statement
var i = 100;
while (i>0) { something; i=i-1; }
do...while

Guaranteed to run once.

do
  statement
while (condition);
var i = 0;
do { i=i+1; smoething; } while (i<10)
break

Stop a loop.

break;

try...catch

Variables, values, objects, literals, functions

var varname1 [= value1 [, varname2 [, varname3 ... [, varnameN]]]];
  defines a local variable, optionally initializing it to a value.

Null

Undefined

Booleans

Strings

var sentence = "This is a sentence";
var sentence = new String("This is a sentence");

A newline character is written like \"\\n\".

var test = "Dave said \"I\'m testing \& stuff\" to Phil."
var x = 'some string';
alert(x.charAt(0)); // alerts 's'

alert(x.substring(0,1));

var my_car="Cat";
var where_is_a=my_car.indexOf('a');
alert('The a is at position '+where_is_a+'.');
var where_is_mytool="home/mytool/mytool.cgi";
var mytool_array=where_is_mytool.split("/");
alert(mytool_array[0]+" "+mytool_array[1]+" "+mytool_array[2]);
String.length
  string length
String.charAt
  Returns the specified character from a string.
String.indexOf(searchValue[, fromIndex])
  where searchValue is in string
String.lastIndexOf(searchValue[, fromIndex])

String.substring
  Returns a subset of a string between one index and another, or through the end of the string.

String.split([separator][, limit])
  split a String object into an array of strings by separating the string into substrings.

Numbers

Objects

members
Object.keys
this
inheritance

Douglas Crockford;

Object.GetPrototypeOf(object)
  Returns the prototype (i.e. the internal Prototype) of the specified object.
object literal
var o = {};

var myObject = {
  sProp: 'some string value',
  numProp: 2,
  bProp: false
};

see example;

Object.prototype
  Represents the Object prototype object.
constructor
new constructor[([arguments])]
  creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
var o = new Object();
function UserObject(newUserName,newUserUID) {
  // Property members
  this.userName = newUserName;
  this.userTitle = "Newbie";
  this.userUID = 0;

  // Method member created using prototype
  UserObject.prototype.notify = function() {
    alert("Username is " + this.userName + " and UID is " + this.UID);
  }
}

var user1 = new UserObject("Milk", 4);
user1.notify;
Object.constructor
  Returns a reference to the Object function that created the instance's prototype.
function Tree(name) {
  this.name = name;
}

var theTree = new Tree("Redwood");
console.log( "theTree.constructor is " + theTree.constructor );

// the above example displays the following output:
theTree.constructor is function Tree(name) {
   this.name = name;
}
function Constructor(...) {
  this.membername = value;
}
Constructor.prototype.membername = value;
Object.create
Object.create(proto [, propertiesObject ])
  Creates a new object with the specified prototype object and properties.
var o;

// create an object with null as prototype
o = Object.create(null);

o = {};
// is equivalent to:
o = Object.create(Object.prototype);
var a = {a: 1}; 
// a ---> Object.prototype ---> null

var b = Object.create(a);
// b ---> a ---> Object.prototype ---> null
console.log(b.a); // 1 (inherited)

var c = Object.create(b);
// c ---> b ---> a ---> Object.prototype ---> null

var d = Object.create(null);
// d ---> null
console.log(d.hasOwnProperty); // undefined, because d doesn't inherit from Object.prototype
Classes

Functions

function statement declares a function that is named and hoisted.

testFunction(milk,5);

function testFuncton(passedName,passednumber) {
  document.write("Hello" + passedVariableName);
  return passednumber *3;
}

function operator defines a (usually anonymous) function inside an expression.

var x = function(y) {
  return y * y;
};

Function constructor creates a function using the Function object.

var multiply = new Function("x", "y", "return x * y;");

Optional arguments using conditional operator;

optionalArg = (typeof optionalArg === "undefined") ? "defaultValue" : optionalArg;
Invocation
fun.call(thisArg[, arg1[, arg2[, ...]]])
  Calls a function with a given this value and arguments provided individually.

es5;

// this:
hello("world")
 
// desugars to:
hello.call(undefined, "world");
fun.apply(thisArg[, argsArray])
  Calls a function with a given this value and arguments provided as an array (or an array like object).

fun.bind(thisArg[, arg1[, arg2[, ...]]])
  Creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
Callbacks
function someAction(x, y, someCallback) {
   return someCallback(x, y);
}
monad
function calcProduct(x, y) {
   return x * y;
}
 
function calcSum(x, y) {
   return x + y;
}
// alerts 75, the product of 5 and 15
alert(someAction(5, 15, calcProduct));
// alerts 20, the sum of 5 and 15
alert(someAction(5, 15, calcSum));
Closures
Anonymous


  • https://en.wikipedia.org/wiki/Immediately-invoked_function_expression - or IIFE, pronounced "iffy", is a JavaScript programming language idiom which produces a lexical scope using JavaScript's function scoping. Immediately-invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function. This concept has been referred to as a self-executing anonymous function, but Ben Alman introduced the term IIFE as a more semantically accurate term for the idiom, shortly after its discussion arose on comp.lang.javascript.
Monads

Arrays

var names = new Array();
names[0] = "Milk";
...
var ages = new Array(24,25,33,45,62)
Array.length

Array.push

Array.sort

Array.reverse

Array.indexOf
  Returns the first index at which a given element can be found in the array, or -1 if it is not present.

Array.slice(begin[, end])
  Returns a shallow copy of a portion of an array.

Array.join(separator)
  convert array to string

Array.forEach(callback[, thisArg])
  Executes a provided function once per array element.

Array.reduce(callback[, initialValue)]

Date

Date.getDate
  Returns the day of the month (1-31) for the specified date according to local time.
Date.toString
Date.toLocaleDateString
Date.toUTCString
Date.toLocaleString
Date.toISOString

RegExp

Math

Math.round(x)
Math.max
Math.random()

XMLHttpRequest

onreadystatechange;

0	UNSENT                open()has not been called yet.
1	OPENED                send()has not been called yet.
2	HEADERS_RECEIVED      send() has been called, and headers and status are available.
3	LOADING	Downloading;  responseText holds partial data.
4	DONE	              The operation is complete.

open method;

void open(
  DOMString method,
  DOMString url,
  optional boolean async,
  optional DOMString user,
  optional DOMString password
);
var myRequest = new XMLHttpRequest();

myRequest.onreadystatechange = function() {
  if myRequest.readyState == 4 {
    alert(myRequest.responseText);
  }
}

myRequest.open("GET", "http://example.com",true);
myRequest.send

Data types

Patterns

Combinators

.extend

Delegation

Generators

Promises

DOM

  • DOM Scripting Task Force - An autonomous working group of the Web Standards Project. Our mission is to bring scripting up to parity with XHTML and CSS as a useful and necessary tool for building accessible, user-centric, standards-based web sites.

Chrome Developer Tools;

window
   in console to see DOM tree, or set breakpoint for first line

Guides

Interfaces

window

window.alert(message);
  Displays a popup box with text and OK button
result = window.confirm(message);
  Displays a popup box with text and OK and cancel buttons which return true and false.
result = window.prompt(text[, value]);
  Displays a dialog with a message prompting the user to input some text.
var windowObjectReference = window.open(strUrl, strWindowName[, strWindowFeatures]);
window.scrollY aka window.pageYOffset
  returns the number of pixels that the document has already been scrolled vertically.
window.scrollX
window.innerHeight
window.innerWidth
window.status = string;
var value = window.status;
  set the windows statusbar text
window.getComputedStyle

timers

window.setInterval
  Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
window.clearInterval(intervalID)
  Clear setInterval timer
window.setTimeout
  Calls a function after a specified delay
window.clearTimeout
  Clears setTimeout timer

history

window.history

location

window.location

window.location.hash

navigator

window.navigator
  Returns a reference to the navigator object, which can be queried for information about the application running the script.
window.navigator.appName
  "Netscape", etc.

nodes

var dupNode = node.cloneNode(deep);
Node.appendChild

document

document.styleSheets
  Returns a list of stylesheet objects for stylesheets explicitly linked into or embedded in a document.
document.readyState
document.write
  add text to document
document.writeln
  add text to document with new line
document.getElementsByTagName('body')
document.getElementById('yourid').style.backgroundColor = "#f3f3f3";
document.getElementsByClassName('body')
document.URL
  get not set address
var element = document.createElement(tagName);

var text = document.createTextNode(data);

elements

document.createElement
element.id
  gets or sets the element's identifier (attribute id).

element.classList
  returns a token list of the class attribute of the element.
element.className
  gets and sets the value of the class attribute of the specified element.
element.innerHTML
  sets or gets the HTML syntax describing the element's descendants.
element.clientHeight
  returns the inner height of an element in pixels, including padding but not the horizontal scrollbar height, border, or margin.

element.offsetParent
  reference to the object which is the closest (nearest in the containment hierarchy) positioned containing element.
element.offsetHeight
  height of an element relative to the element's offsetParent.

element.scrollTop 
  scrollTop gets or sets the number of pixels that the content of an element is scrolled upward.
element.onclick = functionRef;
  The onclick property returns the onClick event handler code on the current element.

element.onblur = function;

console

console.log
  Outputs a message to the Web Console.
console.info
  Outputs an informational message to the Web Console. In Firefox, a small "i" icon is displayed next to these items in the Web Console's log.

Events

onload
  finishes loading a window or all frames within a FRAMESET. BODY and FRAMESET
onunload
  when the user agent removes a document from a window or frame. BODY and FRAMESET
onclick
  when the pointing device button is clicked over an element
ondblclick
  when the pointing device button is double clicked over an element
onmousedown
  when the pointing device button is pressed over an element
onmouseup
  when the pointing device button is released over an element
onmouseover
  when the pointing device is moved onto an element
onmousemove
  when the pointing device is moved while it is over an element
onmouseout
  when the pointing device is moved away from an element
onfocus
  when an element receives focus either by the pointing device or by tabbing navigation. A, AREA, LABEL, INPUT, SELECT, TEXTAREA, and BUTTON.
onblur
  when an element loses focus either by the pointing device or by tabbing navigation.
onkeypress
  when a key is pressed and released over an element
onkeydown
  when a key is pressed down over an element
onkeyup
  when a key is released over an element
onsubmit
  when a form is submitted. It only applies to the FORM element.
onreset
  when a form is reset. It only applies to the FORM element.
onselect
  when a user selects some text in a text field. This attribute may be used with the INPUT and TEXTAREA elements.
onchange
  when a control loses the input focus and its value has been modified since gaining focus. This attribute applies to the following elements: INPUT, SELECT, and TEXTAREA.

Templating

See JS scripts#Templating

Data binding

Drag and Drop

Forms

Media


Firefox

Cookies

document.cookie = cookieName + "=" + excape(cookieValue) + ";expires=" + expirationDate.toUTCString();
if(document.cookie.length > 0) // true if cookie present
// then check specific cookie name
cookieValueStart = document.cookie.indexOf("="); document.cookie.substring(cookieValueStart +1);
document.cookie = cookieName + "=; expires =Thu, 01-Jan-70 00:00:01 GTM";

Security

non strict mode;

  • ADsafe makes it safe to put guest code (such as third party scripted advertising or widgets) on a web page. ADsafe defines a subset of JavaScript that is powerful enough to allow guest code to perform valuable interactions, while at the same time preventing malicious or accidental damage or intrusion. The ADsafe subset can be verified mechanically by tools like JSLint so that no human inspection is necessary to review guest code for safety. The ADsafe subset also enforces good coding practices, increasing the likelihood that guest code will run correctly.
  • Caja Compiler is a tool for making third party HTML, CSS and JavaScript safe to embed in your website. It enables rich interaction between the embedding page and the embedded applications. Caja uses an object-capability security model to allow for a wide range of flexible security policies, so that your website can effectively control what embedded third party code can do with user data.

Modules

AMD

  • RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

"AMD format comes from wanting a module format that was better than today's "write a bunch of script tags with implicit dependencies that you have to manually order" and something that was easy to use directly in the browser. Something with good debugging characteristics that did not require server-specific tooling to get started. It grew out of Dojo's real world experience with using XHR+eval and and wanting to avoid its weaknesses for the future."

ES6

UMD

Loading

<script type="text/javascript">
  document.write("Hello world!");
</script>
<script src="javascript/project.js"></script>

Async

Offline

Compilers


Dialects

  • altJS - One web, many languages. We catalog a range of projects that use the JavaScript/ECMAScript platform to bring language diversity, scientific research opportunities, and choice to the web: Compile-to-JavaScript languages (altJS), JavaScript enhancements (security, static typing), Ports of existing languages (Java, C, Ruby, etc.), Tools for compiler writers

CofeeScript

  • CoffeeScript is a programming language that transcompiles to JavaScript. The language adds syntactic sugar inspired by Ruby, Python and Haskell to enhance JavaScript's brevity and readability, and add more sophisticated features like list comprehension and pattern matching.
  • IcedCoffeeScript is a superset of CoffeeScript. The iced interpreter is a drop-in replacement for the standard coffee interpreter; it will interpret almost all existing CoffeeScript programs.

Coco

  • Coco is a CoffeeScript dialect that aims to be more radical and practical. On its way to hide JavaScript's bad parts, CoffeeScript has accumulated own quirks: horrible variable scope, awkward ranges, confusing and/or pointless keywords, verbose file extension, and so on. Coco tries to amend them, entwining good parts of both.

LiveScript

  • LiveScript is Coco but much more compatible with CoffeeScript, more functional, allows you to write expressive code devoid of repetitive boilerplate. While adding features to assist in functional style programming, LiveScript also deeply supports imperative and object oriented programming, and has an optional class system with inheritance, calls to super, and more.

Kal

Narrative JS

LLJS

  • LLJS is a typed dialect of JavaScript that offers a C-like type system with manual memory management. It compiles to JavaScript and lets you write memory-efficient and GC pause-free code less painfully, in short, LLJS is the bastard child of JavaScript and C. LLJS is early research prototype work, so don't expect anything rock solid just yet. The research goal here is to explore low-level statically typed features in a high-level dynamically typed language. Think of it as inline assembly in C, or the unsafe keyword in C#. It's not pretty, but it gets the job done.

DubJS

  • DubJS is a dialect of JavaScript for making web apps with minimal effort. It comes with a strong core framework, and is designed for building any kind of web app, whether it be an entirely dynamic single-page app, a pre-generated static site,1 or something in between. It's focus is client-side development, and as such can be used in combination with your favourite server-side tools.

LispyScript

  • LispyScript - A javascript With Lispy Syntax And Macros! An inherent problem with Javascript is that it has no macro support, unlike other Lisp like languages. That's because macros manipulate the syntax tree while compiling. And this is next to impossible in a language like Javascript. In LispyScript we write Javascript in a tree structure. If you know Javascript and a Lisp like language, then using LispyScript will be a breeze. Even if you don't know a Lispy Language, all you need to learn is to write code in a tree structure.

haxe JS

Lua

  • Colony compiles JavaScript to Lua 5.1 source code, that requires only a small support library. Colony can be used in any Lua application supporting the debug library (enabled in Lua 5.1 by default). Colony is experimental.
  • ljs - Lua VM implemented in Javascript
  • lua.js - node.js, lua to javascript compiler, nee lua2js-experiment

Tampermonkey

  • Tampermonkey is a tool that provides Greasemonkey script support for Google Chrome and Chromium Browser. It's API is fully compatible to Greasemonkey, including GM_registerMenuCommand, GM_xmlhttpRequest with cross domain support and access to the unsafeWindow object.

Continuum

  • Continuum is a JavaScript virtual machine built in JavaScript. It assembles bytecode from sourcecode and executes it in an ES6 runtime environment. The code of the VM is written in ES3, which means it can run in browsers as old as IE6 (though currently it's only regularly tested in IE8+ and there's probably some kinks to work out in older IE's).

Wisp

Other


asm.js

  • asm.js - This specification defines asm.js, a strict subset of JavaScript that can be used as a low-level, efficient target language for compilers. This sublanguage effectively describes a sandboxed virtual machine for memory-unsafe languages like C or C++. A combination of static and dynamic validation allows JavaScript engines to employ an ahead-of-time (AOT) optimizing compilation strategy for valid asm.js code.