Javascript

JAVASCRIPT

various MVC frameworks in javascript for comparison

BABEL REPL compiles everything into the final state (before serving), use it to check for everything

TODO: learn a lot of javascript

the bits that make javascript work

3(++) ways to run javascript (together with html+css)

  1. internal (synchronous loading) - script is between <script></script> tags
  2. external (synchronous loading) - script is separate file but browserify-ed to magically appear in between <script></script> tags
  3. external (asynchronous loading) - script is separate file, uses module loading

examples in ./code/js-runtime-methods/

1. internal synchronous

1x html file

html file runs with javascript inside within the <script></script> tags

2. external synchronous

1x html file, 1x js file

html file runs, calling the (browserified) app.js file

how?

Browserify parses the AST for require() calls to traverse the entire dependency graph of your project.

3. external asynchronous

1x html file, 2x js file

javascript (node) starts a server through node server.js, which serves the html file, which calls the (browserified) client.js file

(run the .js (something like node server.js and the html is served at some port))

server side

client side

++

this is hard. what are its uses?? A: this dude says so below

You do not "need" to load javascript files asynchronously or via some custom loader. Here are some reasons when asynchronous loading or custom loading might provide a benefit:

When the javascript file is not normally needed and you might want to load it upon demand rather than all the time When the javascript file is not needed for initial page display and you want to maximize the speed of first display for your page When you want to control the timing of exactly when the javascript file is loaded When you are deciding, based upon some condition, whether to load the javascript file or not (for example, if loading from a CDN failed, you might load from a backup location) When you want script loading to proceed in parallel with other things rather than serialized one after another If you don't need any of these benefits or some other benefit provided by programmatic loading, then you can just use the normal <script> tags and let them load synchronously.

all-in-one

comparisons between internal and external js

understanding asynchronous function calls

when people say, 'don't block the event loop', they mean 'don't put shitty slow code on the stack, because the browser can't do what it needs to do, which is update its frames to be a fluid ui'.

Wha?

read the following topic then.

how does Javascript work? (event loops)

the video the awesome event loop ide 'loupe'

a single-threaded non-blocking asynchronous concurrent language has a call stack, an event loop, a callback queue, some other apis

v8 engine

javascript is a single threaded programming language

the call stack

call stack

blocking

blocking the call stack

blocking 2

solution to blocking : asynchronous callbacks

call me ... maybe?

with concurrency & and event loop

one thing at a time. except not really.

async

it's a bit chaotic, so let's break it down piece by piece

async1

stack is call stack - essentially 'javascript land', webapis, task queue and event loop are hidden from us but lives in the browser / nodejs runtime environment.

async2

the main() process starts (Javascript starts running)

async3

the call stack (also called Javascript Runtime) steps through the code from top to bottom, performing the console.log('Hi'); task. hee you can see it in the call stack.

async4

here we run into out asynchronous function. the setTimeout function gets pushed onto the call stack and executed.

async5

async10

but since it is defined as an async function (you have to tell js that it's async when defining your own function too), it gets passed onto the webapis part of the environment and off the call stack.

async11

the call stack (remember, it is the JS Runtime which we see) continues stepping through to the next line, executing console.log('JSConfEU'); while webapis is executing setTimeout.

async15

the stack is cleared. setTimeout continues running for however long it is needed.

async17

setTimeout is done! the result is passed form webapis to the task queue.

async20

now the event loop as one job: to look at the call stack and look at the task queue. if the call stack is empty, it take the first thing in the task queue and pushes it onto the call stack, letting it return the result of the execution from the async function setTimeout, thereby running it.

async23

setTimeout performs its function console.log('there'); and it ends.

common examples of people using event loops

deferring execution to defer execution till the rest of the code is done, using setTimeout(myfunction(){}, 0); (setTimeout with a delay of 0)

other examples

the browser is constrained by what you're doing in javascript

render queue before task queue

important part: the Render's Queue is higher priority than your Task Queue source

render queue blocking

if your task is doing something, the Render Queue is blocked. You can't click anything.

async queueing

async queueing 2

with async functions, you first queue up the async functions wrapped in setTimeout, and then they are run in the webapi and placed back in the callback queue / task queue. this time, Render Queue is allowed to update the frame (render the image) between callback queues so your screen doesn't freeze up.

the heart of Javascript - DOM

Virtual DOM

Things to Know

  1. var, let, const
  2. async/await
  3. .bind() - binding a method to an object
  4. prototypes
  5. inheritance
  6. promises and callbacks - i placed them below cause we should be using async/await instead
  7. event listeners

Var, Let, Const

VAR

var i = 0;
if (true) {
  var i = 1;
}
console.log(i); // 1   even if false. whadda hell.

LET

let i = 0;
if (true) {
  let i = 1;
}
console.log(i); //0   Phew.

CONST

const i = 0;
i = 1; //NOPE

const objThing = {
  i: 0,
};
obj.i = 1; //OK

promises

// PROMISES
// --------
// promises (+ async/await)
// https://codeburst.io/javascript-es-2017-learn-async-await-by-example-48acc58bad65
// resolving and rejecting
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
// promise.all
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
// https://stackoverflow.com/questions/33073509/promise-all-then-resolve

// structure of a promises based async function
function functionName(input1, input2) {
  // always returns a promise where inside you do stuff
  // resolve is where you tell Promise when is the time to mark the code as DONE
  return new Promise((resolve) => {
    const a = "hey";
    // do all your code here

    // when you're done, resolve (special return for Promises)
    resolve(a);

    if ("something bad happens") {
      reject("argh i'm dying!!!");
    }
  });
}

async/await

const puppeteer = require("puppeteer");

// async function that can run on as many threads as possible
async function screenshotter(link_in) {
  const screenshot_name = link_in.split("/").slice(-1)[0];
  console.log(screenshot_name);
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto(link_in);
  await page.screenshot({ path: `${screenshot_name}.png` });

  await browser.close();
}

screenshotter("https://developers.google.com/web/tools/puppeteer");
screenshotter(
  "https://stackoverflow.com/questions/3304014/how-to-interpolate-variables-in-strings-in-javascript-without-concatenation"
);
screenshotter("https://stackoverflow.com/questions/3216013/get-the-last-item-in-an-array");
screenshotter("https://alligator.io/tooling/puppeteer");
screenshotter("https://medium.com/jsguru/javascript-async-await-742ddf66c348");

.bind() - binding a method to an object

  1. you have an object myobject (kinda like a dictionary where keys are 'properties' fancy)
  2. you have two functions that need to use that object fullnamer detailer
  3. you .bind() the object myobject to both fullnamer and detailer with var newFunctionName = originalFunctionName.bind(objectName);
  4. now when you call newFunctionName you run the function using properties from the object
  5. e.g. below:
var person = {
  firstName: "John",
  lastName: "Smith",
  age: 23,
};

function printFullName() {
  console.log(this.firstName + " " + this.lastName);
}

function printDetails() {
  console.log(this.firstName + " is " + this.age + " years old");
}

// TODO: create bound copies of printFullName and printDetails.
var boundPrintFullName = printFullName.bind(person);
var boundPrintDetails = printDetails.bind(person);

boundPrintFullName(); //prints : John Smith
boundPrintDetails(); //prints : John is 23 years old

prototype property

thing.prototype.weight = function(water_amount, flowers_amount) {
    this.water = water_amount;
    this.flowers = flowers_amount;

    return (this.water * 0.1) + (this.flowers * 5)
}

inheritance (read prototype first)

var Person = function () {};

Person.prototype.initialize = function (name, age) {
  this.name = name;
  this.age = age;
};

Person.prototype.describe = function () {
  return this.name + ", " + this.age + " years old.";
};

var Student = function () {};
Student.prototype = new Person();
// THIS HERE ABOVE is the fancy part called INHERITANCE

Student.prototype.learn = function (subject) {
  console.log(this.name + " just learned " + subject);
};

var me = new Student();

me.initialize("John", 25);
me.learn("Inheritance");

Promises, callbacks

dude who implemented promises explains well / reader promises sequence viewer (viz tool)

You know when you have to make a function in a function in a function in function to make sure all the callbacks collapse back in the right order? edit: it's called 'callback hell'.

NOW YOU DON'T HAVE TO.

before

getTweetsFor("domenic", function (err, results) {
  // the rest of your code goes here.
});

after

var promiseForTweets = getTweetsFor("domenic");
// holy shit this is async but it looks exactly the same as sync

or

runFunction().then(successFunc, failureFunc);
// the above runFunction() returns a promise

Promises

Think about a website that loads data from an API then processes and formats the data to display to the user. If we try to process and format our data before the API has even fetched the information, we’re either going to get an error or a blank website. By using a Promise, we can ensure that the API data isn’t processed/formatted until after our API call has succeeded.

Promises can have 3 states

A promise is <strong>settled</strong> if it is not pending. Once a Promise has settled, it is settled for good. It cannot transition to any other state.

from here:

as of present day Javascript, async code looks almost like sync code

In other words, the following asynchronous code:

getTweetsFor("domenic") // promise-returning function
  .then(function (tweets) {
    var shortUrls = parseTweetsForUrls(tweets);
    var mostRecentShortUrl = shortUrls[0];
    return expandUrlUsingTwitterApi(mostRecentShortUrl); // promise-returning function
  })
  .then(httpGet) // promise-returning function
  .then(
    function (responseBody) {
      console.log("Most recent link text:", responseBody);
    },
    function (error) {
      console.error("Error with the twitterverse:", error);
    }
  );

parallels the synchronous code:

try {
  var tweets = getTweetsFor("domenic"); // blocking
  var shortUrls = parseTweetsForUrls(tweets);
  var mostRecentShortUrl = shortUrls[0];
  var responseBody = httpGet(expandUrlUsingTwitterApi(mostRecentShortUrl)); // blocking x 2
  console.log("Most recent link text:", responseBody);
} catch (error) {
  console.error("Error with the twitterverse: ", error);
}

Note in particular how errors flowed from any step in the process to our catch handler, without explicit by-hand bubbling code. And with the upcoming ECMAScript 6 revision of JavaScript, plus some party tricks, the code becomes not only parallel but almost identical.

Event Listeners

<script>
    const input = document.querySelector("input")
    const example = document.querySelector("#example")

    /*
    event listener is added to the thing in html
    which is the input tag, and it listens for 'change'
    as defined in the link above
    when the listener detects 'change', it takes what
    comes out of the input and sets the
    example.style.background to e.target.value
    */

    input.addEventListener("change", (e) => {
        // points to the css
        example.style.background = e.target.value;
    })
</script>

immutability and why it is important

There are generally two ways for changing data. The first method is to mutate the data by directly changing the values of a variable. The second method is to replace the data with a new copy of the object that also includes desired changes.

benefits


SOME BATSHIT CONVENIENCE FUNCTIONS

Conditional Operators

hsb.s = max != 0 ? 255 * delta / max : 0;

wha?

It is called the Conditional Operator (which is a ternary operator).

It has the form of: condition ? value-if-true : value-if-false Think of the ? as "then" and : as "else".

Your code is equivalent to:

if (max != 0)
  hsb.s = 255 * delta / max;
else
  hsb.s = 0;

Short form If else

(condition) ? expression on true : expression on false const result = (10 < 5) ? "cat" : "dog"

Short Circuit Operations

Short form conditionals && and || when used in one line without =,

becomes a short-circuit operation

thing > 5 && "quesadilla";
// if thing is more than 5, the code in the bracket becomes 'quesadilla'
// otherwise it becomes nothing!

Arrow Functions (ES6)

//before
var a2 = a.map(function (s) {
  return s.length;
});

// after
var a2 = a.map((s) => s.length);

fancy AF

string with variables

OTHERS

DONE

things to know (vs python)

cool new things (vs python)

alert() // make a pop up that you can close confirm() // makes a yes/no popup

javascript (coming from python)

slight differences

things to watch out for

python -> javascript
def myfunc(): code -> function myfunc() { code }
list() -> Array
dict -> Objects (they are everywhere)
input() -> prompt()
print() -> console.log()
== -> ===
// below is for strings
"li qun"[1:3] -> "li qun".substring(1, 3)
// below is for arrays (lists)
['a', 'b', 'c', 'd', 'e'][1:3] -> ['a', 'b', 'c', 'd', 'e'].slice(2, 3)

javascript history

  1. JavaScript was originally named JavaScript in hopes of capitalizing on the success of Java.
  2. Netscape then submitted JavaScript to ECMA International for Standardization. (ECMA is an organization that standardizes information)
  3. This results in a new language standard, known as ECMAScript.
  4. Put simply, ECMAScript is a standard. While JavaScript is the most popular implementation of that standard. JavaScript implements ECMAScript and builds on top of it.

useful things

how to run javascript

NODEJS

just like when you do python myapp.py in terminal, now you can do node myapp.js in terminal.

apparently you couldn't before.

eli5

      The main advantage is the asynchronous nature of the language, which is caused by the single-threaded event-loop, which is a fancy way of saying "I can schedule a bunch of jobs simultaneously, and I'll be able to answer them as soon as they are done processing - no job that is done will have to wait around for me to get around to it because I'll know instantly".

command cheat sheet

console.log() and cousins (like print() in python)

  1. html element - innerHTML
    1. ask javascript to find the element
  2. html output - document.write()
  3. alert box (pop up in browser) - window.alert()
  4. browser console - console.log()

load html (the final output usually) when working in js

callback functions

    It's like calling a business on the phone and leaving your "callback" number, so they can call you when someone is available to get back to you. That's better than hanging on the line for who knows how long and not being able to attend to other affairs.
          A callback function is a function which is:

          passed as an argument to another function, and,
          is invoked after some kind of event.

-https://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o/9652434#9652434

Consider how programmers normally write to a file: (LQ: like python)

    fileObject = open(file)
    # now that we have WAITED for the file to open, we can write to it
    fileObject.write("We are writing to the file.")
    # now we can continue doing the other, totally unrelated things our program does

Here, we WAIT for the file to open, before we write to it. This "blocks" the flow of execution, and our program cannot do any of the other things it might need to do! What if we could do this instead:

    # we pass writeToFile (A CALLBACK FUNCTION!) to the open function
    fileObject = open(file, writeToFile)
    # execution continues flowing -- we don't wait for the file to be opened
    # ONCE the file is opened we write to it, but while we wait WE CAN DO OTHER THINGS!

It turns out we do this with some languages and frameworks. It's pretty cool! Check out Node.js to get some real practice with this kind of thinking.