JavaScript: Difference between revisions

No edit summary
 
(12 intermediate revisions by the same user not shown)
Line 4: Line 4:
For server and desktop application JavaScript usage, please see the [[NodeJS]] page.
For server and desktop application JavaScript usage, please see the [[NodeJS]] page.


==Usage==
==Language Syntax==
For basic dom manipulation, see [https://htmldom.dev/ https://htmldom.dev/].
General Ecmascript syntax. Parts of this section applies to browser-side JS and server-side JS (Node.js, Deno), though details may vary between runtimes.
 
===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===
 
===Picture===
 
===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 MDN Guide]
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
var myRegex = /(\d+),(\d+)/;
const myRegex = /(\d+),(\d+)/;
var myStr = "124,52";
const myStr = "124,52";
var match = myStr.match(myRegex);
const match = myStr.match(myRegex);
// Captures
// Captures
console.log(match[1], match[2]);
console.log(match[1], match[2]);
console.table(match);
console.table(match);
</syntaxhighlight>
</syntaxhighlight>


===Classes===
===Classes===
Line 120: Line 78:


===Async-await===
===Async-await===
Added in ES2017<br>
Added in ES2017
 
See [https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await Async_await]<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.
Async functions return implicit promises. They allow you to use keyword <code>await</code> to get results from other promises or functions.
===Enums===
See [https://stackoverflow.com/questions/287903/what-is-the-preferred-syntax-for-defining-enums-in-javascript Stack overflow]
Ecmascript doesn't have a built-in way to define ENUMS. One way is to use <code>Object.freeze</code>:
<syntaxhighlight lang="js">
const WORKERSTATUS = Object.freeze({
  ACTIVE: "ACTIVE",
  DISABLED: "DISABLED",
});
</syntaxhighlight>
; Notes
* This does not enforce any kind of type. If you need that, use [https://www.typescriptlang.org/docs/handbook/enums.html typescript enums].
===<code>var</code> vs <code>let</code>, <code>const</code>===
* <code>var</code> is the old way of declaring variables. It has function-scope rather than block-scope. Note that <code>var</code> can also be redefined which can hide errors.
* <code>let</code> and <code>const</code> are post-ES6 ways which have block-scope.
These days you should never use <code>var</code>. 
The Google [https://google.github.io/styleguide/jsguide.html JS Style Guide] and [https://google.github.io/styleguide/tsguide.html TS Style Guide] suggest using <code>const</code> by default.
==Browser 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===
===Picture===
===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>


==Compilation==
==Compilation==
Line 233: Line 257:
my_set.clear();
my_set.clear();


// Returns if key has in the set
// Returns true if key was in the set
my_set.delete(key);
my_set.delete(key);
</syntaxhighlight>
</syntaxhighlight>
Line 255: Line 279:


==Modules==
==Modules==
These days, we can use modules for everything.
These days, we can use modules for everything.
Note that in most instances, you should compile these using Webpack, browserify or similar. 
For Node.js, you will need to transpile using Babel. 
 
However some modern browsers now support importing modules directly using script tags. 
 
* [[Caniuse: Modules]]


===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]


Example Module
Example Module
Line 265: Line 295:
import * as THREE from 'three';
import * as THREE from 'three';
// Import MyClass as a module. webpack will resolve this.
// Import MyClass as a module. webpack will resolve this.
import MyClass from "./MyClass.js";
import {MyClass} from "./MyClass.js";


// Pretend we're writing another class
// Pretend we're writing another class
export default class MyOtherClass {
export class MyOtherClass {
   constructor() {}
   constructor() {}
}
}
</syntaxhighlight>
</syntaxhighlight>
;Notes
* The Google style guide suggests always using named exports rather than using <code>export default</code>.


==Web Workers==
==Web Workers==
Line 286: Line 319:
* [https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers MDN: Using web workers]
* [https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers MDN: Using web workers]
* [https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API Web Workers API]
* [https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API Web Workers API]
==Documentation==
Use [https://jsdoc.app/ JSDoc] for documentation. 
Example:
<syntaxhighlight lang="js">
</syntaxhighlight>
==Testing==
Frameworks for testing JS:
* [https://jestjs.io/ https://jestjs.io/]


==Useful Packages==
==Useful Packages==
Line 321: Line 366:
npm install mathjs
npm install mathjs
</syntaxhighlight>
</syntaxhighlight>
[[Category:Programming languages]]
==Misc==
* [[Javascript CDNs]]