Javascript - goatandsheep/goatandsheep.github.com GitHub Wiki

Overloading

No inputs

function add()
{
  var a = arguments[0];
  var b = arguments[1];
  return a + b
}

add(1,2);

Object input

add({
  a: 1,
  b: 2
})

function add(options) {
  var a = options.a || 0  // set default value
  var b = options.b || 0
  return a + b
}

or using es6:

function add(options) {
  let {a, b} = options
  return a + b
}

or using rest parameters

var add = function(...args){
  var sum = 0;
  args.map((i) => {sum += i});
  return sum;
}
add(4, 3, 6); // 13

Destructuring (ES6)

add({
  a: 1,
  b: 2
})

function add({ a = 0, b = 0}) {
  return a + b
}

Files

  • map: help with debugging

Promises

  • promise.resolve(<Promise or value or function>)

Promisify

promisified(inputs: any): Promise<any> {

  return new Promise((resolve, reject) => {
    const cb = (err, result) => {
      if (err) {
        reject(err)
      }
      resolve(result)
    }
    
    cb_funk(inputs, cb)
  });
}
    runSyncAsAsync(func, input) {
      return new Promise((resolve, reject) => {
        try {
          const result = func(input)
          resolve(result || '')
        } catch(err) {
          reject(err)
        }
      });
    }

Closures

Memory Location

When you assign a variable to another, you're generally just making a copy of the value, but when you assign a variable to the same object, it copies the reference to the value, not just the value.

That means you cannot do:

const solid.rock = "foo"
solid.rock = "bar" 

but you can do:

const solid = {
  rock = "foo"
}
solid.rock = "bar"

Take caution when checking hasOwnProperty vs attribute === undefined because the object may define the property and leave it empty if it is not a dynamic object.

if ("undefined" === typeof variable) {

Locality

  • forgetting to declare variables: global
  • let: private
  • var: public

Arrow Functions

Useful for ensuring locality of the this keyword.

(inputVars) => valueReturned // generic
var answer = (a,b) => a * b // example returns a * b
(inputVars) => {
  return this.a * this.b // if you need a multi-line function, which uses `this`
}

for-loop

Use let in your for-loops because var makes the variable accessible outside the loop.

for (let i = 0, len = nums.length; i < len; i++)
{
  console.log(i)
}

Arithmetic

Be careful with string arithmetic.

'4' - '2' // subtraction works great
> 2
'2' - '4' // even negatives
> -2
'4' + '4' // addition is actually concatenation
> "44"
'4' - '2' + '2'
> "22"
'4' - '2' + parseInt('2') // use parseInt as often as possible. Preferably all the time.
> 4

Async-await

Error handling

const Hello = async () => {
    try {
        await updateUser()
    } catch (err) {
        console.error(err)
    }
}

Looping

let asyncFor = (arr, func) => {
  arr.forEach( async(item)=> func(item)) 
}
// e.g. asyncFor([1,2,3], run)

Compiling

  • Transpiling: ES6,7 --> ES5
  • Minification / Uglification

Imports

Best thing when importing components is to have relative imports to allow you to move your application around to different directories.

fetch

Cross-origin: fetch('url', { mode: 'no-cors'})

filter

Array.from(new Set(xs)).filter(x => xs2.includes(x))

Uploading large files

https://api.video/blog/tutorials/uploading-large-files-with-javascript

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