Backend JS - atabegruslan/Notes GitHub Wiki

Prototype

https://www.youtube.com/watch?v=DqGwxR_0d1M&list=PL0zVEGEvSaeHBZFy6Q8731rcwk0Gtuxub&index=5

  • .__proto__ property points to the object that the current object actually will use when doing lookups on the prototype.
  • .prototype only exists on functions, in case you want to use those objects as constructors passed to the new keyword.

So with prototype-based languages, it's just: object -> object -> object.
There are no classes and instance objects. Just objects.
So Prototype inheritance/chaining can be better described as objects delegating its missing functionalities to other objects.

Inheritance, eg: Date objects inherit from Date.prototype

From ES6, JavaScript introduced the class keyword. But it's essentially a syntactic sugar over the prototype-based system.

Class vs Prototype

In short: prototype is eaasier for the computer under the hood.

Proper comparison: https://softwareengineering.stackexchange.com/questions/110936/what-are-the-advantages-of-prototype-based-oop-over-class-based-oop

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

Call, apply & bind

Map, Reduce & Filter

Check empty

https://levelup.gitconnected.com/different-ways-to-check-if-an-object-is-empty-in-javascript-e1252d1c0b34

Object to Array:

  1. Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}

  2. ES6 spread syntax: { ...['a', 'b', 'c'] }

  3. Array's map function resp.data.data is the object:

let listOfObjects = Object.keys(resp.data.data).map((key) => {
	return resp.data.data[key]
})
  1. Array's reduce function: https://dev.to/afewminutesofcode/how-to-convert-an-array-into-an-object-in-javascript-25a4

Sleep

https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep/39914235#39914235

function sleep(ms) 
{
	return new Promise(resolve => setTimeout(resolve, ms));
}

await sleep(1000);

Polling

var thereYet = false;
var intervalName = setInterval(function() {
    if ( /* "there yet" condition */ ) 
    {
        thereYet = true;
    }
    
    if (thereYet) 
    {
        clearInterval(intervalName);
    }

    // Do action
}, 100);

AJAX with recursion

https://stackoverflow.com/questions/19332049/while-loop-with-jquery-async-ajax-calls/19332078#19332078

function recursive_function()
{
	$.ajax({
	    ...,
	    async: true,
	    success: function(res) {
		if ( NOT DONE ) 
		{
		    recursive_function();
		}
		else
		{
		    // DONE
		}
	    }
	});
}

Debouncing vs Throttling

  • Debouncing: Hold up for a while then act
  • Throttling: Act then hold up for a while

https://redd.one/blog/debounce-vs-throttle

Differentiate browser refresh, visiting new website, forward, back

Download direct with AJAX

Typed Arrays

Destructuring and related techniques

https://stackoverflow.com/questions/22202766/keeping-only-certain-properties-in-a-javascript-object

Eval

https://www.w3schools.com/jsref/jsref_eval.asp

But try not to use it, it may execute malicious code.

Merge two Arrays and Remove Duplicates

https://thispointer.com/5-ways-to-merge-two-arrays-and-remove-duplicates-in-javascript/

Deep-merge 2 objects

https://gist.github.com/ahtcx/0cd94e62691f539160b32ecda18af3d6

with nested arrays

const merge = (target, source) => {
  for (const key of Object.keys(source))
  {
    if (Array.isArray(source[key]))
    {
      Object.assign(source[key], [...new Set(target[key].concat(source[key]))]);
    }

    if (source[key] instanceof Object && !Array.isArray(source[key]))
    {
      Object.assign(source[key], merge(target[key], source[key]));
    }
  }

  Object.assign(target || {}, source)
  
  return target
}

Get caret position in text area

https://gist.github.com/atabegruslan/123cbba73cf97c7ce2025bdd1494f20e

Weird Parts Explained

History

JavaScript mostly implements the ECMAScript specification.
More info about JS vs ECMAScript: https://www.freecodecamp.org/news/whats-the-difference-between-javascript-and-ecmascript-cba48c73a2b5/

JS Terminology

JavaScript engine: A program or interpreter that understands and executes JavaScript code.
Synonyms: JavaScript interpreter, JavaScript implementation

V8 in Chrome, SpiderMonkey in Firefox, and Chakra in Edge. Each engine is like a language module for its application, allowing it to support a certain subset of the JavaScript language.

A JavaScript engine to a browser is like language comprehension to a person

JavaScript runtime: The environment in which the JavaScript code runs and is interpreted by a JavaScript engine.The runtime provides the host objects that JavaScript can operate on and work with.
Synonyms: Host environment

JIT Compiler vs Transpiler

JIT Compiler (eg in V8 Engine)

A compiler compiles a language to bytecode at compile-time. Then the JIT-compiler compiles bytecode to native code at runtime.

https://stackoverflow.com/questions/59807938/the-confusion-with-jit-compilation-in-v8

Transpiler (eg Babel)

A transpiler converts codes that are at similar levels of abstraction. Eg: ES6 code to ES5 code.

JS Templating

https://gist.github.com/atabegruslan/39db447e098e3809847498d34a6fa8ee

Not to be confused with Modules: https://www.w3schools.com/js/js_modules.asp

Node.js & NPM

Modules

Comparisons:

Other related articles:

Bundlers

WebPack

Take this example:

webpack.config.js

module.exports = { 
  entry: "./index.tsx",
  target: "es5",
  module: {
    rules: [
      {
        test: /\.tsx$/,
        use: ['babel-loader', 'ts-loader']
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  }
}

Loaders are pre-processors in WebPack

babel.config.json

module.exports = {
  "presets": [
    "@babel/preset-env",
    "@babel/react"
  ]
}

Publish modules to npmjs

https://zellwk.com/blog/publish-to-npm/

npm login.
It will ask for your NPM username, email and password and email you an OTP.
Then npm publish.

Create Organization

https://docs.npmjs.com/creating-an-organization

Publishing scoped public packages

https://docs.npmjs.com/creating-and-publishing-scoped-public-packages#publishing-scoped-public-packages

Force "downstream" dependencies' versions

Overrides

Only works for NPM >= v8.3

What you can do:

Constrict dependency version

"overrides": {
  "node-ipc@>9.2.1 <10": "9.2.1"
}

So that node-ipc of any version between 9.2.1 and 10 will be made to be v9.2.1

Override "downstream" module

"overrides": {
  "bar": {
    "foo": "1.0.0"
  }
}

Override foo to be 1.0.0 when it's a child (or grandchild, or great grandchild, etc) of the package bar.

There is another way of accomplishing the above: https://docs.npmjs.com/cli/v8/commands/npm-shrinkwrap

Shrink Wrap

package.json

Local modules

In ./local_modules/@whatever-optional-namespace/local-module-name/package.json

{
  "name": "local-module-name",

npm i -S ./local_modules/@whatever-optional-namespace/local-module-name

The following will be generated in ./package.json

{
  "name": "whatever",
  "dependencies": {
    "@whatever-optional-namespace/local-module-name": "file:local_modules/@whatever-optional-namespace/local-module-name"
  },

Now your local module is in.

Use forked NPM modules

For example, just put in the Github link (or a community-fork of it, or your own fork of it)

"dependencies": {
  "react-js-pagination": "https://github.com/wwwaiser/react-js-pagination.git",

This becomes useful when your dependency-module's develop haven't yet updated their work on npmjs.com.

Pre and Post Scripts

Process manager

PM2:

Formatters

Yarn

Yarn is faster: https://waverleysoftware.com/blog/yarn-vs-npm

Version Managers

Others

Constants

Query Params

Convert hyphen <-> camel case

Rid diacritics

https://github.com/atabegruslan/Notes/wiki/Encoding#rid-diacritics

RegEx

http://www.regular-expressions.info/charclassintersect.html

⚠️ **GitHub.com Fallback** ⚠️