JavaScript

From Things and Stuff Wiki
Jump to navigation Jump to search


todo; sort this mess

General

1995

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

Learning

Online cources

Screencasts

Books

  • JSbooks - The best free JavaScript resources

Articles

Videos

Games

Specs

ECMAScript 5

ECMAScript 6

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

Paradigms and patterns

Code formatting

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

Patterns

Structure

Syntax

Comments

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

Operators

=
  assignment
==
  equivalency comparison
===
  strictly equak with no type conversion
typeof
  returns string indicating the type of unevaluated operand

Statements

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

Primitives

Values, variables and literals

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

varname1 = 42
  declare a global and local variable. not strict mode compliant!
var test123
  declare variable without value; undefined

const newtest321 = 666
  declare an immutable variable

Javascript Objects

Null

Undefined

Boolean

String

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.

Number

Array

var names = new Array();
names[0] = "Milk";
...
var ages = new Array(24,25,33,45,62)
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.

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

Object

Object.prototype
Object.constructor
Object.keys
function userObject(newUserName,newUserUID) {
  // Properties
  this.userName = newUserName;
  this.userTitle = "Newbie";
  this.userUID = 0;

  // Methods
  userObject.prototype.notify = function() {
    alert("Username is " + this.userName + " and UID is " + this.UID);
  }
}

var user1 = new userObject("Milk",001);
user1.notify;

RegExp

Math

Math.round(x)
Math.max

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

Function

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

testFunction(milk,5);
Anonymous

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

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.

https://developer.mozilla.org/en-US/docs/DOM/event.metaKey

window

window.prompt
  Displays a dialog with a message prompting the user to input some text.
window.open
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
window.setInterval
  Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
window.setTimeout
  executes a code snippet or a function after specified delay.

history

window.history

location

window.location

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.

document

document.write
  add text to document
document.writeln
  add text to document with new line
document.readyState
document.getElementsByTagName('body')
document.getElementById('yourid').style.backgroundColor = "#f3f3f3";
document.getElementsByClassName('body')
document.URL
  get not set address

element

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;
element.innerHTML
  sets or gets the HTML syntax describing the element's descendants.

Interfaces

Drag and Drop

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

Object Orientated

Classes

Loading

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

Async

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

Engines

JSON

  • JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
  • http://en.wikipedia.org/wiki/JSON
  • https://developer.mozilla.org/en/JSON
  • Getting Started with JSON - You send data in a JSON format between different parts of your system. API results are often returned in JSON format, for example. JSON is a lightweight format which makes for easy reading if you're even the least bit familiar with JavaScript.
  • JSON-LD (JavaScript Object Notation for Linking Data) is a lightweight Linked Data format that gives your data context. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on the already successful JSON format and provides a way to help JSON data interoperate at Web-scale. If you are already familiar with JSON, writing JSON-LD is very easy. These properties make JSON-LD an ideal Linked Data interchange language for JavaScript environments, Web service, and unstructured databases such as CouchDB and MongoDB.

Tools

  • jq is like sed for JSON data – you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.

Offline

Repos

  • JSAN - JavaScript Archive Network

CDN

Testing

  • QUnit is a powerful, easy-to-use JavaScript unit test suite. It’s used by the jQuery, jQuery UI and jQuery Mobile projects and is capable of testing any generic JavaScript code, including itself!.

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.

JS based

CofeeScript

  • CoffeeScript is a programming language that transcompiles to JavaScript. The language adds syntactic sugar inspired by Ruby, Python and Haskell[1] 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, and more feature rich. LiveScript aims for increased expressiveness and code beauty. 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.

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