Javascript - goatandsheep/goatandsheep.github.com GitHub Wiki
function add()
{
var a = arguments[0];
var b = arguments[1];
return a + b
}
add(1,2);
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
add({
a: 1,
b: 2
})
function add({ a = 0, b = 0}) {
return a + b
}
-
map
: help with debugging
promise.resolve(<Promise or value or function>)
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)
}
});
}
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) {
- forgetting to declare variables: global
-
let
: private -
var
: public
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`
}
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)
}
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
const Hello = async () => {
try {
await updateUser()
} catch (err) {
console.error(err)
}
}
let asyncFor = (arr, func) => {
arr.forEach( async(item)=> func(item))
}
// e.g. asyncFor([1,2,3], run)
- Transpiling: ES6,7 --> ES5
- Minification / Uglification
Best thing when importing components is to have relative imports to allow you to move your application around to different directories.
Cross-origin: fetch('url', { mode: 'no-cors'})
Array.from(new Set(xs)).filter(x => xs2.includes(x))
https://api.video/blog/tutorials/uploading-large-files-with-javascript