Warren Shea

Warren Shea’s Notes for JavaScript (and TypeScript)

v20230104

Notable JavaScript Experts

Quick Reference

Terms

Conversions

NodeList to Array

Various Notes (no particular order)

Truthy/Falsy

In a conditional statement, these values are not true or false (boolean) but are accepted as conditions:

Better console.log

events

Pointer events

prevent from running

Propagation (bubbling up) + Capture (trickle down)

Functional Programming via Filter Map Sort Reduce

const totalValue = arrayName.reduce((total,arrayItem) => {
  return total + arrayItem.doSomething;
},0);

Imperative Programming

JAMstack - Javascript, APIs, Markup

Adding to the DOM via JavaScript

<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->

Scope

Global Scope

Block Scope

Function Scope

Lexical Scoping

this

Hoisting

function functionName() {} //function declaration
var variableName; //variable declaration

to the top of the containing function (or file if you’re at top level). this lets you call a function declared this way even if it’s defined below.

However, function expressions are not hoisted up, nor are variables defined with let

const functionName = function() {} //function expression
let variableName; //let variable declaration

Closures

Adding Event Listeners to multiple items

buyButtons.forEach(button => {
  button.addEventListeners('click', callbackFunction);
});
function handleClick(button) {
  button.addEventListeners('click', callbackFunction);
}
buyButtons.forEach(handleClick);

Headless

The Main Thread

Web Workers

Arrow functions

IIFE - Immediate-invoked Function Expressions

To execute functions immediately, as soon as they are created Don’t pollute the global object, simple way to isolate variables declarations

(function() {
  /* */
})();

(function doSomething() {
  /* */
})();

(() => {
  /* */
})();

Async Await

async function functionName() {
  const res = await fetch("url");
  console.log(res.json());
}

The console.log doesn’t run until after the await is completed

Promises

What is the extent of your experience with Promises and/or their polyfills? What are the pros and cons of using Promises instead of callbacks?

JavaScript Functions are First Class Citizens

.apply and .call

function theFunction(name, profession) {
    console.log("My name is " + name + " and I am a " + profession +".");
}
theFunction("John", "fireman");
theFunction.apply(undefined, ["Susan", "school teacher"]);
theFunction.call(undefined, "Claude", "mathematician");
theFunction.call(undefined, ...["Matthew", "physicist"]); // used with the spread operator

function.prototype.bind

When would you use document.write()?

What’s the difference between feature detection, feature inference, and using the UA string?

Explain how JSONP works and why it’s not really AJAX

Instead of

//alpha.com code
fetch('https://beta.com/file.json')

which would return a cross domain issue (CORS), you could do

<!--alpha.com code-->
<script src="https://beta.com/file.json"></script>
//https://beta.com/file.json
myFunction({
  //object
})

where myFunction is defined on alpha.com code.

Difference between document load event and document ready event?

Why would you use something like the load event? Does this event have disadvantages? Do you know any alternatives, and why would you use those?

Explain the same-origin policy with regards to Javascript

Why is it called a Ternary expression, what does the word “Ternary” indicate?

//conditional
if(conditional) { // one
  truthy_block // two
} else {
  falsy_block // three
}

//ternary expression
(conditional) ? truthy_block : falsy_block

what is "use strict";? what are the advantages and disadvantages to using it?

Explain what a single page app is and how to make one SEO-friendly.

What are some of the advantages/disadvantages of writing Javascript code in a language that compiles to Javascript?

Advantages:

What is the purpose of a code style linting tool?

What is an event loop?


To Revisit

I’ve posted some questions I’ve seen online that I tried to look into but I still have trouble understanding. Sometimes with experience, things like this clear themselves up over time.

What are generators

What is currying

function curry(f) { // curry(f) does the currying transform
  return function(a) {
    return function(b) {
      return f(a, b);
    };
  };
}

// usage
function sum(a, b) {
  return a + b;
}

let curriedSum = curry(sum);

console.log( curriedSum(1)(2) ); // 3

What are monads?

When to use classes instead of factory functions

Use cases for WeakMap/WeakSet


TypeScript

if (typeof padding === "number") {


The State of JS

I always find the State of JS survey as one of the best ways to learn something new/cutting edge. Here, I’ll list some items and a brief description / info on what it is - mostly for my own learning:

Language

Numeric Separators

String.prototype.replaceAll()

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
//
console.log(p.replaceAll('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
//
// global flag required when calling replaceAll with regex
const regex = /Dog/ig;
console.log(p.replaceAll(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"

String.prototype.matchAll()

const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';
//
const array = [...str.matchAll(regexp)];
//
console.log(array[0]);
// expected output: Array ["test1", "e", "st1", "1"]
//
console.log(array[1]);
// expected output: Array ["test2", "e", "st2", "2"]

Regexp Match Indices / String.prototype.match()

const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex = /[A-Z]/g;
const found = paragraph.match(regex);
//
console.log(found);
// expected output: Array ["T", "I"]

Array.prototype.at()

const array1 = [5, 12, 8, 130, 44];
let index = 2;
//
console.log(`Using an index of ${index} the item returned is ${array1.at(index)}`);
// expected output: "Using an index of 2 the item returned is 8"
//
index = -2;
//
console.log(`Using an index of ${index} item returned is ${array1.at(index)}`);
// expected output: "Using an index of -2 item returned is 130"

Array.findLast()

const array1 = [5, 12, 50, 130, 44];

const found = array1.findLast((element) => element > 45);

console.log(found);
// expected output: 130

Object.hasOwn()

const object1 = {
  prop: 'exists'
};
console.log(Object.hasOwn(object1, 'prop'));                    // expected output: true
console.log(Object.hasOwn(object1, 'toString'));                // expected output: false
console.log(Object.hasOwn(object1, 'undeclaredPropertyValue')); // expected output: false

Promise.allSettled()

Promise.any()

const promise1 = Promise.reject(0);
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'quick'));
const promise3 = new Promise((resolve) => setTimeout(resolve, 500, 'slow'));
//
const promises = [promise1, promise2, promise3];
//
Promise.any(promises).then((value) => console.log(value));
//
// expected output: "quick"

Top Level await()

(async function() {
  await Promise.resolve(console.log('🎉'));
  // → 🎉
}());
await Promise.resolve(console.log('🎉'));
// → 🎉

Dynamic Import

// say.js
export function hi() {
  alert(`Hello`);
}

export function bye() {
  alert(`Bye`);
}

// another file.js
let {hi, bye} = await import('./say.js');

hi();
bye();

Temporal

Logical OR || e.g. expr1 || expr2

Logical AND && e.g. expr1 && expr2

Nullish Coalescing

Operator ??

const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0

Assignment ??=

const a = { duration: 50 };

a.duration ??= 10;
console.log(a.duration);
// expected output: 50

a.speed ??= 25;
console.log(a.speed);
// expected output: 25

Logical Assignment

const a = { duration: 50, title: '' };
//
a.duration ||= 10;
console.log(a.duration);
// expected output: 50
//
a.title ||= 'title is empty.';
console.log(a.title);
// expected output: "title is empty"

Proxies

Private Fields

class ClassWithPrivate {
  #privateField;
  #privateFieldWithInitializer = 42;

  #privateMethod() {
    // …
  }

  static #privateStaticField;
  static #privateStaticFieldWithInitializer = 42;

  static #privateStaticMethod() {
    // …
  }
}

Error.prototype.cause

try {
  connectToDatabase();
} catch (err) {
  throw new Error('Connecting to database failed.', { cause: err });
}

Browser APIs

Service Workers

Intl

WebGL

Web Animations

WebRTC

Web Speech API

WebSocket

Custom Elements

Shadow DOM

Page Visibility API

Broadcast Channel API

Geolocation API

File System Access API

Web Share API

WebXR Device API

Other Features

Progressive Web Apps

WebAssembly (WASM)

Front end Frameworks (2022 version)

Rendering Frameworks

Testing

Mobile & Desktop

Build Tools

Monorepo Tools

Other Tools

Date Management

Data Visualization

Graphics & Animations

Data Fetching

Back-end Frameworks

Utilities

JavaScript Runtimes

JavaScript Edge/Serverless Runtimes

JavaScript Flavors

Non-JavaScript Languages

Which sites/courses/etc. do you consult?

Video Creators

Podcasts


OLD STUFF: Vanilla JS IE11 Friendly AJAX Request

Vanilla JS IE11 Friendly AJAX Requestfunction jsonp(uri) {
  return new Promise(function(resolve, reject) {
    var id = '_' + Math.round(10000 * Math.random());
    var callbackName = 'jsonp_callback_' + id;
    window[callbackName] = function(data) {
      delete window[callbackName];
      var ele = document.getElementById(id);
      ele.parentNode.removeChild(ele);
      resolve(data);
    }

    var src = uri + '&callback=' + callbackName;
    var script = document.createElement('script');
    script.src = src;
    script.id = id;
    script.addEventListener('error', reject);
    (document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(script)
  });
}

if (navigator.userAgent.toLowerCase().indexOf('msie') > -1 && window.XDomainRequest) {
  // Use Microsoft XDR
  var xdr = new XDomainRequest();
  xdr.open("get", url);
  xdr.onload = function() {
    // XDomainRequest doesn't provide responseXml, so if you need it:
    var dom = new ActiveXObject("Microsoft.XMLDOM");
    dom.async = false;
    dom.loadXML(xdr.responseText["data"][0]);
  };
  xdr.send();
} else {
  jsonp(url).then(function(data){
    temp_get_symbol_payload = data["data"][0];

    /*if there are more than 1 result(s)*/
    if (temp_get_symbol_payload) {
      if (temp_get_symbol_payload.length > 0) {
        get_holding_payload.classList.remove("display:none");
        get_holding_payload.innerHTML = "";
        /*iterate through*/
        for(let i=0;i<temp_get_symbol_payload.length;i++) {
          get_holding_payload.insertAdjacentHTML('beforeend', self.render_autocomplete_result(query,i,input_id,autocomplete_id,temp_get_symbol_payload[i]));
          if (i === results_max_results) {
            break;
          }
        }
      }
    }
  });
}