Difference between revisions of "JavaScript"

From Media Design: Networked & Lens-Based wiki
Jump to navigation Jump to search
 
(25 intermediate revisions by the same user not shown)
Line 2: Line 2:
  
 
[[Category:JavaScript]]
 
[[Category:JavaScript]]
== Links ==
+
== History ==
  
* Nice blog post from 2020 on what simple modern javascript in a browser can do: https://jvns.ca/blog/2020/06/19/a-little-bit-of-plain-javascript-can-do-a-lot/
+
Originally designed for the Netscape browser, the name "JavaScript" was chosen to associate with the "Java" programming language developed by Sun which, in 1995, was the first real option for making "live" code run over the web. ''Other than the name, there is no relation between JavaScript and Java.'' The formal name for JavaScript now is ECMAScript, but as this sounds more like a skin condition than a programming language, the name JavaScript has persisted.
 +
 
 +
The introduction of highly interactive "web apps" like Google Maps has helped to reduce some of the differences between browsers in their implementation of JavaScript (which made early JavaScript development quite a nightmare). Traditionally popular JavaScript frameworks like prototype and [[JQuery]] have helped to smooth over differences between browsers and led to many techniques (such as using CSS selectors in Javascript code, and "functional" style programming) more popular and better incoporated into "vanilla" javascript.
 +
 
 +
'''Node''' (2009) is an implementation of javascript designed to run '''outside of the browser''' aka '''server-side'''. Together with its related package manager '''npm''', Node has made a huge impact on the ecosystem of javascript development and '''npm''' serves as a foundation for all kinds of javascript development workflows (whether or not the final "target" of a project is a (node) server and/or in the browser).
  
== Intro ==
+
In 2021, javascript is a vibrant but complex development ecosystem. Important related projects & development communities are [[webpack]] and [[typescript]], and frameworks like [[angular]] and [[react]].
  
Originally designed for the Netscape browser, the name "JavaScript" was chosen to associate with the "Java" programming language developed by Sun which, in 1995, was the first real option for making "live" code run over the web. ''Other than the name, there is no relation between JavaScript and Java.'' The formal name for JavaScript now is ECMAScript, but as this sounds more like a skin condition than a programming language, the name JavaScript has persisted.
+
== Data types ==
  
The popularity of "live" web apps based on JavaScript like Google Maps has helped to reduce some of the differences between browsers in their implementation of JavaScript (which made early JavaScript development quite a nightmare). Also, JavaScript frameworks such as ["Prototype"] help to smooth over the remaining differences and other difficulties (such as [[EventHandling]]).
+
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
  
== From Python ==
+
== Variables ==
  
* Curly braces ({}) instead of colons and indentation (:)
+
* https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Variables
* Indentation: still important for readability!
 
* Semi-colons at ends of lines (though optional, good to get into the practice of using)
 
* "var", "let" and "const" to announce a variable (technically optional but important to be explicit about scope)
 
* "function" defines functions, also the new "splat" style ( => )
 
* Implicit type conversion ("hello" + 7 = "hello7")
 
  
 
== Functions ==
 
== Functions ==
  
<source lang="python">
 
def hello (x):
 
    print "Hello", x
 
 
hello("Bob")
 
</source>
 
  
 
<source lang="javascript">
 
<source lang="javascript">
 
function hello (x) {
 
function hello (x) {
    console.log("Hello", x);
+
  console.log("Hello", x);
 
}
 
}
 +
hello("Bob");
 +
</source>
 +
 +
In practice, javascript functions are often defined "anonymously", as "callbacks" to events like mouse clicks.
 +
 +
<source lang="javascript>
 +
let div = document.getElementById("button");
 +
 +
div.addEventListener("click", function (event) {
 +
  console.log("HEY somebody clicked", event);
 +
});
 +
</source>
 +
 +
A newer compact "arrow" notation using the symbols "=>" is increasingly popular. (If you are doing things with classes, there's a subtle but important difference: An arrow function does ''not'' redefine the special symbol ''this'' -- which makes arrow functions convenient when writing callbacks in an object method (no more ''that'' variables needed).)
  
hello("Bob");
+
<source lang="javascript">
 +
div.addEventListener("click", (event) => {
 +
  console.log("HEY somebody clicked", event);
 +
});
 
</source>
 
</source>
  
Line 55: Line 65:
 
</source>
 
</source>
  
== Debugging ==
+
== Promises & Asynchronous programming ==
  
Joe Hewitt's [[Firebug]] was the breakthrough Firefox addon that provided a "commandline" for Javascript (F12). Still very much in active development (thanks in part to some development resources from IBM). Recently, Firefox and Chrome have caught up with their built-in web consoles (Firefox: Web Console (Shift-Ctrl-K)).
+
Promises and new structures like async + await offer an alternative to working with callbacks.
  
== JQuery ==
+
* [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises Using promises]
 +
* [https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await async & await]
  
http://jquery.org
+
== Array methods: forEach() & map() ==
  
* Smooths over browser differences (Event-handling, AJAX)
+
<source lang="javascript">
* Incredibly elegant: CSS selectors to "query" the page & manipulate specific content with code
+
const array1 = ['a', 'b', 'c'];
* Pre-fab widgets & behaviors (Draggable, Resizable, Droppable)
 
  
== JQuery: Hello world ==
+
array1.forEach(element => console.log(element));
  
<source lang="html4strict">
+
// expected output: "a"
<html>
+
// expected output: "b"
<head>
+
// expected output: "c"
<script src="jquery.js"></script>
 
<script>
 
$(document).ready(function () {
 
    console.log("Hello world");
 
});
 
</head>
 
<body>
 
</body>
 
</html>
 
 
</source>
 
</source>
  
== JQuery: Styles Plus ==
+
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
  
<source lang="html4strict">
+
== Fetch API & making HTTP requests ==
<html>
 
<head>
 
<script src="jquery.js"></script>
 
<script>
 
$(document).ready(function () {
 
    $("p.foo").css({'background': 'pink'});
 
});
 
</head>
 
<body>
 
<p class="foo">Hello</p>
 
<p>World</p>
 
</body>
 
</html>
 
</source>
 
  
== Extreme Functions ==
+
Loading external data was added to javascript via the XMLHTTPRequest object, spawning a set of practices called "AJAX". Modern browsers now support the so-called "Fetch API" that makes loading files relatively straightforward (and finally remove the need for libraries like jquery). As fetching is essentially asynchronous (it takes time, your code continues at some point in the future when it's done rather than directly), the API uses Promises. Note that there are two stages to a fetch: (1) The request itself, and (2) retrieving the "body" of the results as typically either JSON (the popular alternative of XML) or text.
  
Javascript functions can be defined "in-place" and be "anonymous".
+
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
  
Traditional for loop:
 
 
<source lang="javascript">
 
<source lang="javascript">
var words = "Once upon a time, in a galaxy far far away".split(" ")
+
fetch('http://example.com/movies.json')
 
+
  .then(response => response.json())
for (var i=0; i<words.length; i++) {
+
  .then(data => console.log(data));
    console.log(words[i]);
 
}
 
 
</source>
 
</source>
  
Using jQuery's each:
+
Or avoiding callbacks with await...
 
<source lang="javascript">
 
<source lang="javascript">
var words = "Once upon a time, in a galaxy far far away".split(" ")
+
async function getdata () {
$(words).each(function (i, w) {
+
  let resp = await fetch('http://example.com/movies.json');
    console.log(w);
+
  let data = await resp.json();
});
+
  console.log("we got data", data);
 +
}
 
</source>
 
</source>
  
There are situations where using each is important! (For making proper closures)
+
== From Python ==
  
== JQuery: Events ==
+
* Curly braces ({}) instead of colons and indentation (:)
 
+
* Indentation: still important for readability!
<source lang="html4strict">
+
* Semi-colons at ends of lines (though optional, good to get into the practice of using)
<html>
+
* "var", "let" and "const" to announce a variable (technically optional but important to be explicit about scope)
<head>
+
* "function" defines functions, also the new "splat" style ( => )
<script src="jquery.js"></script>
+
* Implicit type conversion ("hello" + 7 = "hello7")
<script>
 
$(document).ready(function () {
 
 
 
    $("p").click(function () {
 
        $(this).css({background: "aqua"});
 
    });
 
 
 
});
 
</head>
 
 
 
<body>
 
    <p class="foo">Hello</p>
 
    <p>World</p>
 
</body>
 
 
 
</html>
 
</source>
 
  
 
== Resources ==
 
== Resources ==
Line 152: Line 120:
 
"Core" Documentation from mozilla.org
 
"Core" Documentation from mozilla.org
  
* [http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide Core JavaScript Guide]
+
* https://developer.mozilla.org/en-US/docs/Web/JavaScript
* [http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference Core JavaScript Reference]
+
* Nice blog post from 2020 on what simple modern javascript in a browser can do: https://jvns.ca/blog/2020/06/19/a-little-bit-of-plain-javascript-can-do-a-lot/
  
 
Online Tutorials
 
Online Tutorials
Line 160: Line 128:
 
* http://www.webteacher.com/javascript/
 
* http://www.webteacher.com/javascript/
 
* http://www.cs.brown.edu/courses/bridge/1998/res/javascript/javascript-tutorial.html
 
* http://www.cs.brown.edu/courses/bridge/1998/res/javascript/javascript-tutorial.html
 
== Javascript from Python ==
 
 
* [http://code.google.com/p/python-spidermonkey/ python-spidermonkey]... javscript meets python
 
 
== Bestest Javascript html5 video player wrapper==
 
*[http://mediaelementjs.com/ mediaelement.js]
 
 
== From * to Javascript ==
 
https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS
 

Latest revision as of 19:58, 17 February 2021

Scripting language built into web browsers.

History

Originally designed for the Netscape browser, the name "JavaScript" was chosen to associate with the "Java" programming language developed by Sun which, in 1995, was the first real option for making "live" code run over the web. Other than the name, there is no relation between JavaScript and Java. The formal name for JavaScript now is ECMAScript, but as this sounds more like a skin condition than a programming language, the name JavaScript has persisted.

The introduction of highly interactive "web apps" like Google Maps has helped to reduce some of the differences between browsers in their implementation of JavaScript (which made early JavaScript development quite a nightmare). Traditionally popular JavaScript frameworks like prototype and JQuery have helped to smooth over differences between browsers and led to many techniques (such as using CSS selectors in Javascript code, and "functional" style programming) more popular and better incoporated into "vanilla" javascript.

Node (2009) is an implementation of javascript designed to run outside of the browser aka server-side. Together with its related package manager npm, Node has made a huge impact on the ecosystem of javascript development and npm serves as a foundation for all kinds of javascript development workflows (whether or not the final "target" of a project is a (node) server and/or in the browser).

In 2021, javascript is a vibrant but complex development ecosystem. Important related projects & development communities are webpack and typescript, and frameworks like angular and react.

Data types

Variables

Functions

function hello (x) {
  console.log("Hello", x);
}
hello("Bob");

In practice, javascript functions are often defined "anonymously", as "callbacks" to events like mouse clicks.

let div = document.getElementById("button");

div.addEventListener("click", function (event) {
  console.log("HEY somebody clicked", event);
});

A newer compact "arrow" notation using the symbols "=>" is increasingly popular. (If you are doing things with classes, there's a subtle but important difference: An arrow function does not redefine the special symbol this -- which makes arrow functions convenient when writing callbacks in an object method (no more that variables needed).)

div.addEventListener("click", (event) => {
  console.log("HEY somebody clicked", event);
});

Loops

words = "Once upon a time, in a galaxy far far away".split()

for w in words:
    print w
var words = "Once upon a time, in a galaxy far far away".split(" ")

for (var i=0; i<words.length; i++) {
    console.log(words[i]);
}

Promises & Asynchronous programming

Promises and new structures like async + await offer an alternative to working with callbacks.

Array methods: forEach() & map()

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

array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Fetch API & making HTTP requests

Loading external data was added to javascript via the XMLHTTPRequest object, spawning a set of practices called "AJAX". Modern browsers now support the so-called "Fetch API" that makes loading files relatively straightforward (and finally remove the need for libraries like jquery). As fetching is essentially asynchronous (it takes time, your code continues at some point in the future when it's done rather than directly), the API uses Promises. Note that there are two stages to a fetch: (1) The request itself, and (2) retrieving the "body" of the results as typically either JSON (the popular alternative of XML) or text.

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));

Or avoiding callbacks with await...

async function getdata () {
  let resp = await fetch('http://example.com/movies.json');
  let data = await resp.json();
  console.log("we got data", data);
}

From Python

  • Curly braces ({}) instead of colons and indentation (:)
  • Indentation: still important for readability!
  • Semi-colons at ends of lines (though optional, good to get into the practice of using)
  • "var", "let" and "const" to announce a variable (technically optional but important to be explicit about scope)
  • "function" defines functions, also the new "splat" style ( => )
  • Implicit type conversion ("hello" + 7 = "hello7")

Resources

"Core" Documentation from mozilla.org

Online Tutorials