Skip to content

Instantly share code, notes, and snippets.

@grenoult
Last active September 1, 2018 01:00
Show Gist options
  • Save grenoult/7a3c07504a1150a65dc0b3d04cb14797 to your computer and use it in GitHub Desktop.
Save grenoult/7a3c07504a1150a65dc0b3d04cb14797 to your computer and use it in GitHub Desktop.
JavaScript and best practices
// Best practices:
/*
1 - Always name anonymous functions.
Good: var clickHandler = function clickHandler() { ... }
Bad: var clickHandler = function() { ... }
Because:
- useful for self-reference
- debuggable stack trace
- self documentating codeYour billing address doesn’t look like it matches up with your current country. Please contact support for assistance or use a payment method registered to your current address.
*/
// Let vs Var
function foo(x, y) {
if (x > y) {
var tmp = 123; // accessible in whole foo function scopre
let tmp = 123; // accessible only in if block
}
}
// Block scoping
function add(text) {
{ let suffix = text; // suffix is only accessible in this block
suffix = '.' + text.toUpperCase();
text = text + suffix;
}
return text;
}
// JavaScript events viewer with bookmark
// -> https://github.com/DataTables/VisualEvent
// Create object
var obj = {};
// Loop through object properties or array elements
for (var i in variable) {
// i: index
// variable[i]: value
}
// Debounce function
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
// Delete and restart the timeout
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment