Jump to content

JavaScript: Difference between revisions

5,399 bytes added ,  2 June 2020
No edit summary
(22 intermediate revisions by the same user not shown)
Line 3: Line 3:


==Usage==
==Usage==
For basic dom manipulation, see [https://htmldom.dev/ https://htmldom.dev/].
===Inputs===
====Showing an input image====
<syntaxhighlight lang="javascript">
const myInput = document.getElementById("myInput");
const myImage = document.getElementById("myImage");
myInput.addEventListener('change', function() {
    if (myInput.files.length !== 1) {
        return;
    }
    let image = myInput.files[0];
    const reader = new FileReader();
    reader.onload = function(e) {
        myImage.src = e.target.result;
    };
    reader.readAsDataURL(image);
});
</syntaxhighlight>
===Canvas===
===Canvas===
===Picture===
===Video===
===Video===
Your HTML:
<syntaxhighlight lang="html">
<video id="myVideoElt" controls>
</video>
</syntaxhighlight>
Your JS:
<syntaxhighlight lang="javascript">
const myVideo = document.getElementById("myVideoElt");
// Create a new source
const newSource = document.createElement("source");
const myVideoUrl = "https://interactive-examples.mdn.mozilla.net/media/examples/flower.webm";
newSource.setAttribute("src", myVideoUrl);
myVideo.appendChild(newSource);
myVideo.play();
</syntaxhighlight>
===Regular Expressions (Regex)===
===Regular Expressions (Regex)===
[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions Reference]
[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions Reference]
Line 51: Line 92:
}
}
</syntaxhighlight>
</syntaxhighlight>
===Promises===
Added in ES2015 (ES6)<br>
See [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise Promises]<br>
In general, a function returns a promise if it needs to perform asyncronous tasks.<br>
<syntaxhighlight lang="javascript">
function myFunc() {
  // Do syncronous things here
  return new Promise((resolve, reject) => {
    // Do asyncronous things here
    // Return data
    resolve(myData);
    // Or if we have an error
    reject(myError);
  });
}
myFunc()
  .then(data => {
    console.log(data);
  }).catch(err => {
    console.error(err);
  });
</syntaxhighlight>
===Async-await===
Added in ES2017<br>
See [https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await Async_await]<br>
Async functions return implicit promises. They allow you to use keyword <code>await</code> to get results from other promises or functions.


==Compilation==
==Compilation==
Line 76: Line 146:
==Data Structures==
==Data Structures==
JavaScript traditionally has arrays and objects (hashmap) data structures.<br>
JavaScript traditionally has arrays and objects (hashmap) data structures.<br>
ES2015 (ES6) adds several collections including: Map, Set, WeakMap, WeakSet
ES2015 (ES6) adds several collections including: Map, Set, WeakMap, WeakSet<br>
[https://www.sitepoint.com/es6-collections-map-set-weakmap-weakset/ ES6 Collections]


===Arrays===
===Arrays===
Line 94: Line 165:
===Objects===
===Objects===
Objects are maps in JavaScript. They are typically implemented as hashmaps by the JS engine.<br>
Objects are maps in JavaScript. They are typically implemented as hashmaps by the JS engine.<br>
Note that you can only use numbers and strings as keys.
Note that you can only use numbers and strings as keys.<br>
Learn more about the implementation at [https://v8.dev/blog/hash-code https://v8.dev/blog/hash-code]<br>
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
let my_map = {};
let my_map = {};
my_map["my_key"] = "my_value";
// or my_map["my_key"]
my_map.my_key = "my_value";
"my_key" in my_map;
 
// Loop over keys
for (let key in a) {
  console.log("Key:", key);
}
</syntaxhighlight>
 
===Map===
[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map MDN Map] 
[https://www.ecma-international.org/ecma-262/10.0/index.html#sec-map-objects ES2019 (ES10) Map Specification] 
This is your typical hashmap.
 
<syntaxhighlight lang="js">
let myMap = new Map();
 
let keyObj = {};
 
// Set value
myMap.set(keyObj, 'value associated with keyObj');
 
// Get size
myMap.size;
 
// Get value
myMap.get(keyObj);
 
// Check if key is in the map
myMap.has(keyObj);
 
// Delete
myMap.delete(keyObj);
</syntaxhighlight>
 
;Notes
* You can mix and match types of keys
* The hash for objects are randomly generated under the hood
* Do not use <code>[]</code> to get or set from the map
* Iterating over a Map will be in order of insertion
 
;Saving as json
See [https://2ality.com/2015/08/es6-map-json.html es6 map json]<br>
<syntaxhighlight lang="javascript">
const data = JSON.stringify([...myMap]);
myMap = new Map(JSON.parse(data));
</syntaxhighlight>
 
===Set===
[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set MDN Set]
 
<syntaxhighlight lang="js">
let my_set = new Set();
 
// Returns the set itself
my_set.add(key);
 
my_set.has(key);
 
my_set.clear();
 
// Returns if key has in the set
my_set.delete(key);
</syntaxhighlight>
 
===WeakMap===
Unlike map, weakmap holds weak references to its keys. This allows keys to be garbage collected when no reference to it remains.
Note that once keys are garbage collected, they are also removed from the weakmap since you can no longer access them.
You can not iterate through a weakmap.
 
===WeakSet===


==WebXR==
<syntaxhighlight lang="javascript">
// Check for VR support
if ("xr" in navigator && "isSessionSupported" in navigator.xr) {
  navigator.xr.isSessionSupported('immersive-vr').then((supported) => {
    console.log("immersive-vr supported:", supported);
  });
}
</syntaxhighlight>
</syntaxhighlight>


==Modules==
==Modules==
These days, we can use modules for everything.
===Getting Started===
===Getting Started===
[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules MDN Guide to Modules]<br>
[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules MDN Guide to Modules]<br>
Example Module
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
// Import three.js as a module. webpack will resolve this.
import * as THREE from 'three';
// Import MyClass as a module. webpack will resolve this.
import MyClass from "./MyClass.js";
// Pretend we're writing another class
export default class MyOtherClass {
  constructor() {}
}
</syntaxhighlight>
==Useful Packages==
Packages which run in the browser and may be useful for developing web applications.
Note that some of these may overlap with the NodeJS page.
===lerp, clamp===
<syntaxhighlight lang="bash">
npm i lerp clamp
</syntaxhighlight>
<syntaxhighlight lang="javascript">
Math.lerp = require("lerp");
Math.clamp = require("clamp");
</syntaxhighlight>
===pako===
[https://github.com/nodeca/pako pako github]<br>
"zlib port to javascript, very fast!"
<syntaxhighlight lang="bash">
npm install pako
</syntaxhighlight>
===url-join===
Basically <code>path.join</code> for the browser.<br>
<syntaxhighlight lang="bash">
npm install url-join
</syntaxhighlight>


===mathjs===
[https://mathjs.org/ https://mathjs.org/]<br>
Some useful math things for JavaScript in the browser and in NodeJS
<syntaxhighlight lang="bash">
npm install mathjs
</syntaxhighlight>
</syntaxhighlight>