Friday, 12 April 2019

Introduction to JavaScript

Here are some notes & links I used on my quest of learning JavaScript. You won't find anything spectacular here :)

JS in general

Coding convention

When to use and when not semicolons?

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

Memory Management

Memory management model

Causes of memory leaks

How to free up memory?

JS in Front-End

What is DOM?

Web page lifecycle

How to check which events on the page/window have handlers attached?
When does DOMContentLoaded fire? What does its handler usually do?

What is the vanilla JS equivalent of '$(document).ready()'?

When does window.onload fire? What does its handler usually do?

How to prevent web page from closing?

window.onbeforeunload = function() { return "Would you really like to close your browser?"; }

Threading system

Is JS single or multi-threaded language and why?
How does event system work if it’s single-threaded?


Assigning and passing to functions by value and by reference


How to rethrow the error?

Data types

JavaScript is a weakly typed language, not un-typed language. Primitive types are passed into functions by value, while non-primitives are passed by reference. The typeof operator in JavaScript explicitly informs you of what the type of a variable is (hint is in the name of the operator). There are 5 primitive types (string, number, boolean, undefined, symbol) and two non-primitives (object, function) that are available in user land. [source]
Which 2 types of data types are defined by the latest ECMAScript?

List all primitives.

null vs unsigned

List all 6 falsy values in JS


What is an “object” in computer science?



What is the difference between Object.values() and


template string

How to make template string substitution in runtime?


How to find if array contains some element which matches some criteria?

jQuery - What happens if some operation is executed on the empty array?
e.g. what happens if find returns empty array in:
$footer_ip.find(".user--ip, .virtual--ip").addClass("animated fadeInUp");

How to create an array?

How to redefine Array.toString function?


Expressions and operators

Loose equality operator

What does it do?

Double Equals vs. Triple Equals

Destructuring assignment

Spread syntax



Built-in (global) functions

parseInt - what is the purpose of radix argument?

How to verify that parsing some string as integer was successful?


Arrow functions

Self-Executing Anonymous Functions


Is addEventListener (using listeners) preferred over attaching a handler?

What is the correct attaching a handler (if go down this route)?
How to avoid wrong double handler execution?
Describe event phases
(capturing, bubbling...)

jQuery - Why returning false from (click) event handler?


JavaScript: async/await with forEach()

Should a Promise.reject message be wrapped in Error?

resolve & reject

`resolve` and `reject` functions inside a Promise's executor


(Especially pay attention to point #3 - Returned Promises are not wrapped - which explains when and why await can be omitted)

JavaScript loops - how to handle async/await
JavaScript: async/await with forEach()

Web APIs



How to set text in a <span> element?

querySelector vs querySelectorAll

When to use (set) innerHTML and when innerText?

Misc How Tos

How to declare a constant data member in a class?

Best Practices

Check that there is no unnecessary console.log which goes into production.
Check that there are no unused variables.
Check return values of functions (is it null, undefined, empty array, error code etc...)

Make sure of the time order of events and functions...e.g.

document.addEventListener("DOMContentLoaded", function() {});

If xxx is never executed but you can see that document has event handler for DOMContentLoaded event that means that the document.addEventListener("DOMContentLoaded" code was executed too late, after DOMContentLoaded event has already been fired!

var btn = document.querySelectorAll("a.btn")[0];

Use querySelector.

I prefer:

var btn = document.querySelector("a.btn");
btn.addEventListener('click', function(e) {
   const url = "secure://extensions/?id=dmfdacibleoapmpfdgonigdfinmekhgp";
   chrome.tabs.create({ url: url });


var btn = document.querySelector("a.btn");
if (btn !== null) {
   btn.addEventListener('click', function(e) {
      const url = "secure://extensions/?id=dmfdacibleoapmpfdgonigdfinmekhgp";
      chrome.tabs.create({ url: url });
} else {
   console.log(“WARNING: a.btn element not found.”);

as console.log message would probably be unnoticed in the log while exception thrown in case btn is null would be marked in red in console log.

use _xxx for private member variables

use no special naming for global variables because try to avoid globals outside of application constants

Consts write as MY_CONST.

This function has a lot of side effects on the DOM and global multimap. Not necessarily a problem, although the function name doesn't communicate this. A nicer way may be restructure the app to have a function that returns a state object and then hands this off to a function which generates/mutates the DOM. It's a more "functional" way of doing it anyway! Personal preference.

when you say "state object", do you mean data (e.g. optimalGateway and multimap) in this case?

I mean an object representing all data within the application. Granted, this is quite a Redux/React way of thinking and is harder to implement with a bunch of jquery, so it may not be appropriate. Still, if I'm calling a function called loadDataFromBackgroundPage at the top level with no return value, it is very unclear that is going to have side effects on the DOM. I would expect it to have a return value of that data, and no side effects. Then that data could be handed off to another function to handle the rendering.

$() equivalent to $(document).ready()

$(handler) is now preferred to $(document).ready(handler) (

I have two similar handlers for $(document).click in this code so I'm going to merge them.

Function name capitalisation consistency.

selectedGatewayId = vpnExtensionEngine.getGateways().find(g => + ", " + === selectedLocation).id;

If find returns undefined, we'll get an error here. Might be worth adding a check for this or catching the error.

All parseInt calls should specify the base. e.g. parseInt(unixTimestampString, 10)

( confirms this)

Another DOM ready handler. Can we condense these in to one?

var url = "";

Move to const?

replace var with let wherever applicable.

Instead of looping infinitely and throwing, can we adjust this condition?

That's certainly better approach as exception is used here to control the flow of execution (and not to signal exceptional behaviour).

use setTimeout vs setInterval and clearing it immediately in the callback
Callback has to be executed only once, after timeout so it makes more sense to use setTimeout

const serverApiVersionMajor = lightVpnControllerApiVersion.split(".")[0];
const serverApiVersionMinor = lightVpnControllerApiVersion.split(".")[1];

Array destructuring supported in Chrome 49+, so could rewrite these two lines as:

const [serverApiVersionMajor, serverApiVersionMinor] = lightVpnControllerApiVersion.split(".")

Arrow functions are used elsewhere, so could use one here as well for compactness. Personal preference. Also, you wouldn't need the .bind(this) as the arrow function doesn't create a closure.

Chrome 42+ supports the fetch API. More compact and returns a promise, so don't need to wrap it like this.

General tips:

Stack Overflow:


Cool Tips and Tricks

How to print the name of the JS file currently loaded in html?

console.log('Loading script: ' + document.currentScript.src);

How to add a line break to the string in messages.json?
Where should I put <script> tags in HTML markup?
Remove Render-Blocking JavaScript
JavaScript Where To

String literals:

console.log(‘Hello, world!’)


console.log("Hello, world!")

What is lexical scope?
What is "this"?
What is Lexical Scope Anyway?
How do I write a named arrow function in ES2015?

Why is the content of some js files wrapped inside a function which is wrapped inside anonymous self-executed function?

(function () {...})();

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
Self-Executing Anonymous Functions
Immediately Invoked Function Expression (IIFE)
What does “use strict” do in JavaScript, and what is the reasoning behind it?
Should I 'use strict' for every single javascript function I write?
Not recommended to use “use strict” in ES6?
Strict Mode
What is this Javascript “require”?
What is require?
Requiring modules in Node.js: Everything you need to know
Commonly accepted best practices around code organization in JavaScript
ECMA-262, 9th edition, June 2018

What is the difference between String.slice and String.substring?

Create a JavaScript array containing 1…N
Tasks, microtasks, queues and schedules

No comments: