JavaScript
JavaScript basics
Basics
JavaScript local info
ECMAScript
ECMAScript is the specification used to implement the JavaScript language.
JavaScript was developed by Brendan Eich at Netscape as the in-page scripting language for Navigator 2.
Nearly every JavaScript environment runs at least ECMAScript 5 (ES5), the version of JavaScript introduced in 2009.
Subsequent versions are ES6, ES2016 (ES7) and ES2017 (ES8). Babel is a transpiler, that transforms newer features into ES5 for cross-platform compatibility.
Transpilation is a source to source compilation in which the newer versions of JavaScript are used in the user's source code
and the transpiler rewrites them so that they are compliant with the current specification.
Typing
JavaScript is loosely typed. It also has a feature called prototypal inherintance, a class-free object system where objects
inherit properties directly from other objects.
Simple types
The simple types of JavaScript are numbers, strings, booleans, null, and undefined.
All other values are objects. Numbers, strings, and booleans are
object-like in that they have methods, but they are immutable.
0bjects
Objects are mutable keyed collections. An object is a container of properties, where a property has a name and a value.
A property name can be any string, including the empty string. A property value can be
any JavaScript value except for undefined.
Standard built-in objects include Array, Boolean, Date, Error, Function, JSON, Math, Number, Object, RegExp, String, Map,
Set, WeakMap, and WeakSet.
Objects are class-free. Objects can contain other objects, so they can represent tree or graph structures.
A prototype linkage feature allows one object to inherit the
properties of another. This can reduce object initialization time and memory consumption.
Functions are objects, which are collections of name/value pairs having
a hidden link to a prototype object. Objects produced from object literals are
linked to Object.prototype. Function objects are linked to Function.prototype
(which is itself linked to Object.prototype).
Compilation units
A compilation unit contains a set of executable statements.
In web browsers, each 'script' tag delivers a compilation unit that is compiled and immediately executed.
Lacking a linker, JavaScript throws them all together in a common global namespace.
Invocation
There are four patterns of invocation in JavaScript: the method, function, constructor and the apply invocation pattern.
IDE, checking
IDE: Microsoft's Code VS.
In analogy to C/C++'s Lint, there's JSlint, a JavaScript syntax checker and verifier.
For TS there's Palantir's TSlint, which comes with basic
rules.
Popular rules include airbnb.
Jump points
JS DOM
Document Object Model (DOM)
The DOM is a cross-platform and language-independent interface that treats an XML or HTML document
as a tree structure wherein each node is an object representing a part of the document.
Each branch of the tree ends in a node, and each node contains objects.
DOM methods allow programmatic access to the tree; with them one can change the structure, style or content of a document.
Nodes can have event handlers attached to them. Once an event is triggered, the event handlers get executed.
DOM standards
The principal standardization of the DOM was handled by the World Wide Web Consortium, which last developed a
recommendation in 2004. WHATWG took over development of the standard, publishing it as a living document.
The W3C now publishes stable snapshots of the WHATWG standard.
- W3C DOM
- WHATWG DOM Living Standard
- DOM standards:
- DOM Level 1 provided a complete model for an entire HTML or XML document,
including the means to change any portion of the document.
- DOM Level 2 (published in 2000) introduced the getElementById function as well as an event model
and support for XML namespaces and CSS.
- DOM Level 3, published in April 2004, added support for XPath and keyboard event handling,
as well as an interface for serializing documents as XML.
- DOM Level 4 (published in 2015) is a snapshot of the WHATWG living standard.
DOM and JS
- MDN JS basics
- MDN JS DOM intro
- MDN JS DOM access and interfaces
- DOM interfaces include Document, DOMTokenList, Element, Event, Node, NamedNodeMap, ParentNode, Selection, TreeWalker, Window, etc
- The Document interface
- represents a web page loaded in the browser and serves as an entry point into the web page's content, which is the DOM tree
- has a constructor: Document()
- has properties (some inherited from the Node and EventTarget interfaces) such as Document.Body,
Document.Frameset, Document.Scripts etc
- also, the Document interface for HTML documents inherits from the HTMLDocument interface or, since HTML5, is extended for such documents
- has event handlers such as Document.onafterscriptexecute, and also global event handlers
- has methods (some inherited from the Node and EventTarget interfaces) such as Document.getElementsByClassName(),
Document.requestStorageAccess() (which returns a Promise that resolves if the access to first-party storage was granted,
and rejects if access was denied), document.getElementById(String id), Document.querySelector(), etc
- also, events can be listened to using addEventListener() or by assigning an event listener to the oneventname property
of this interface
- animation events
- clipboard events
- drag and drop events
- fullscreen events
- keyboard events
- load and unload events
- window.addEventListener('load', (event) => {console.log('page is fully loaded');}); OR
- window.onload = (event) => {console.log('page is fully loaded');};
- pointers events
- selection events
- touch events
- transition events
- there are also browser-specific extensions
- full DOM Document reference - details
- MDN JS DOM JS examples
HTML DOM
A document containing HTML is described using the Document interface, extended by the HTML specification to include
HTML-specific features. In particular, the Element interface is enhanced to become HTMLElement and various subclasses,
each representing one of (or a family of closely related) elements.
To use the DOM in an HTML page, you need to use the HTML module of the DOM, either by
- including JavaScript or VBScript in your page, or,
- by using an external application such as a plug-in, ActiveX control, or Java applet,
that accesses the document through your browser (support depends on the browser)
The HTML DOM API provides access to various browser features such as tabs and windows, CSS styles and stylesheets,
browser history, etc.
Different browsers have different implementations of the DOM, and these implementations exhibit varying degrees of conformance
to the actual DOM standard.
- MDN HTML DOM API
- Among the things added to Document by the HTML standard are:
- Support for accessing various information provided by the HTTP headers when loading the page,
such as the location from which the document was loaded, cookies, modification date, referring site, and so forth.
- Access to lists of elements in the document's block and body, as well as lists of the images, links,
scripts, etc. contained in the document.
- Support for interacting with the user by examining focus and by executing commands on editable content.
- Event handlers for document events defined by the HTML standard to allow access to mouse and keyboard events,
drag and drop, media control, etc.
- Event handlers for events that can be delivered to both elements and documents;
these presently include only copy, cut, and paste actions.
Front-end
React
- Facebook - how to create a React app
- Facebook on Github - all projects
- RxJS - Reactive eXtensions for JavaScript
- Reactjs.org - JavaScript library to build UIs
- JSX (JavaScript eXtensions) is a shortcut for using the React.createElement() API
- At the heart is the ReactDOM.render()
React.Express
Reactive Programming is a paradigm to express static (e.g., arrays) or dynamic (e.g., event emitters) data streams with ease,
and also communicate that an inferred dependency within the associated execution model exists,
which facilitates the automatic propagation of the changed data flow.
Reactive Extensions (also known as ReactiveX) is a set of tools allowing imperative programming languages to operate on sequences of data regardless of whether the data is synchronous or asynchronous.
It provides a set of sequence operators that operate on each item in the sequence.
Ajax
AJAX (short for "Asynchronous JavaScript + XML")combines web technologies on the client side to create asynchronous web applications.
With Ajax, web applications can send and retrieve data from a server asynchronously (in the background)
without interfering with the display and behavior of the existing page.
By decoupling the data interchange layer from the presentation layer, Ajax allows web pages and, by extension,
web applications, to change content dynamically without the need to reload the entire page.
In practice, modern implementations commonly utilize JSON instead of XML.
Ajax is not a single technology, but rather a group of technologies.
HTML and CSS can be used in combination to mark up and style information.
The webpage can then be modified by JavaScript to dynamically display—and allow the user to interact with—the new information. The built-in XMLHttpRequest object, or since 2017 the new "fetch()" function within JavaScript, is commonly used to execute Ajax on webpages allowing websites to load content onto the screen without refreshing the page. Ajax is not a new technology, or different language, just existing technologies used in new ways.
jQuery
jQuery is a Document Object Model (DOM) manipulation library. It is a JS library to simplify HTML DOM tree traversal and manipulation,
as well as event handling, CSS animation, and Ajax.
Angular
AngularJS is a JavaScript-based open-source front-end web framework mainly maintained by Google and by a community.
A framework for client-side model–view–controller (MVC) and model–view–viewmodel (MVVM) architectures,
along with components commonly used in rich Internet applications.
AngularJS is the frontend part of the MEAN stack, consisting of MongoDB database,
Express.js web application server framework, Angular.js itself, and Node.js server runtime environment.
Analytics
Web beacons/pixels
A web beacon (also called web bug, tracking bug, tag, web tag, page tag, tracking pixel, pixel tag, 1×1 GIF, or clear GIF)
is one of various techniques used on web pages and email, to unobtrusively (usually invisibly) allow checking that a user
has accessed some content.
Web beacons are typically used by third parties to monitor the activity of users at a website for the purpose of
web analytics or page tagging. They can also be used for email tracking.
When implemented using JavaScript, they may be called JavaScript tags.
Using such beacons, companies and organizations can track the online behavior of web users.
At first, the companies doing such tracking were mainly advertisers or web analytics companies;
later social media sites also started to use such tracking techniques, for instance through the use of buttons
which act as tracking beacons.
Google
Google Analytics.
Google Tag Manager (GTM) allows to manage tags (such as measurement and marketing optimization JavaScript tags) on a site.
Without editing the site code, the GTM user interface allows to add and update Google Ads, Google Analytics, Floodlight,
and non-Google tags.
Hotjar
Hotjar is a behavior analytics service that helps online businesses understand the behavior of website users,
providing feedback through tools such as heatmaps, session recordings, and surveys.
It can be used alongside traditional web analytics tools such as Google Analytics to offer an insight into how people
are navigating websites, and how their customer experience can be improved.
Facebook Pixel
The Facebook pixel is a snippet of JavaScript code that allows to track visitor activity on a website.
It works by loading a small library of functions which you can use whenever a site visitor takes an action (called an event)
that you want to track (called a conversion). Tracked conversions appear in the Facebook Ads Manager and
in the Facebook Analytics dashboard, where they can be used to measure the effectiveness of ads,
to define custom audiences for ad targeting, for dynamic ads campaigns, and to analyze the effectiveness of the
website's conversion funnels.
Back-end
Node.js, nvm, npm, yarn
Node.js
- Nodejs.org Node.js on Wikipedia
- Nodejs.org Node.js is an open-source, cross-platform JavaScript runtime
- an asynchronous event-driven JavaScript runtime (JSRE), built on Chrome's V8 JavaScript engine
- Uses 'modules', comparable to JavaScript libraries, i.e. a set of functions you can include in your application
- connections can be handled concurrently, upon each connection, the callback is fired, but if there is no work to be done, Node.js will sleep
- primarily used to build network programs such as Web servers
- can serve static and dynamic content (server-side scripting)
- represents a "JavaScript everywhere" paradigm, unifying web application development around a single language, rather than different languages for server- and client-side scripts
- natively only supports JavaScript but many compile-to-JS languages are available
- most significant difference between Node.js and PHP is that most functions in PHP block until completion (commands only execute after previous commands finish), while Node.js functions are non-blocking (commands execute concurrently or even in parallel,
and use callbacks to signal completion or failure)
- thousands of open-source libraries for Node.js, most of them hosted on the npm website, ref below.
IPC can be done in http or https:
- nodejs includes an https module
- key generation with openssl, then put the pub and private key in the server directory
- protocol can be specified in web server start script
- use of an HTTPS environment variable - HTTPS=true
Documentation
IDEs
- IDEs include Microsoft Visual Studio (VS Code - with Node.js tools), Atom, Brackets, JetBrains WebStorm, NetBeans,
Nodeclipse Enide Studio (Eclipse-based), ...
- nodeclipse - Node.js dev on Eclipse
- W3schools - Node.js
npm
Package manager for the Node.js server platform, installs Node.js programs from the npm registry, organizing the installation and management of third-party Node.js programs.
- npm - node package manager
- consists of a command line client, also called npm, and an online database of public and paid-for private packages, called the npm registry which is accessed via the client
- the available packages can be browsed and searched via the npm website
- npmaudit allows to check dependencies and vulnerabilities
- Npm.js - the npm registry
All npm packages (should) contain a package.json, created by executing 'npm init' in its directory. The package.json file holds metadata as well as:
- scripts building and starting, lint checking, ...
- dependencies for different versions
- environment variables
yarn
- yarn - JavaScript package manager
Express.js
- Expressjs- minimalistic web framework for Node.js
- Expressjs- routing
- Expressjs- security
- Expressjs- HelloWorld
- express-generator is an application generator tool to quickly create an application skeleton
- routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path)
and a specific HTTP request method (GET, POST, and so on). Each route can have one or more handler functions, which are executed when the route is matched
- static files can be served using the express.static built-in middleware function
- serve-static - documentation
- Express has no notion of a database. This concept is left up to third-party Node modules, allowing to interface with nearly any database
Meteor
- Meteor server based on Node.js
Nest
Nest (NestJS) is a Node.js server-side application framework.
It uses progressive JavaScript, is built with and fully supports TypeScript
and combines elements of OOP (Object Oriented Programming), FP (Functional Programming),
and FRP (Functional Reactive Programming).
Under the hood, Nest makes use of HTTP Server frameworks like Express (the default) and
optionally can be configured to use Fastify.
Nest provides a level of abstraction above these common Node.js frameworks (Express/Fastify),
but also exposes their APIs directly to the developer.
- Nestjs
- Nestjs - microservices
- offers transporters which natively support both request-response and event-based message styles, using TCP by default
- Redis Pub/Sub, NATS, Kafka, gRPC, RabbitMQ, ...
Other
- Mongoose MongoDB object modeling tool, or ODM (Object Document Mapper), written in JS and designed to work in an asynchronous environment
- Mongoose docs
- Everything in Mongoose starts with a Schema which maps to a MongoDB collection and defines the shape of the documents within that collection
Scriptmanagers
Greasemonkey
Greasemonkey is a userscript manager made available as a Mozilla Firefox extension. It enables users to install scripts
that make on-the-fly changes to web page content after or before the page is loaded in the browser (also known as augmented browsing).
TypeScript
JWT, JOSE etc
Refer also to JWT, JOSE, etc.