Skip to content

Instantly share code, notes, and snippets.

@arlg
Last active October 15, 2018 10:37
Show Gist options
  • Save arlg/4233860 to your computer and use it in GitHub Desktop.
Save arlg/4233860 to your computer and use it in GitHub Desktop.
Javascript the good way
/*FOR LOOPS
-------------------------------------------*/
//SLOW -> (no caching of the length)
for (var i = 0; i < myArray.length; i++) {}
//GOOD -> (caching the length) : http://jsperf.com/forloops3
for (var i = 0, l = myArray.length; i < l; i++) {}
//BEST -> backwards for loop + caching the length : http://jsperf.com/forward-and-backward-for-loops/2
for (var length = arr.length, i = length - 1; i >= 0; --i) {}
/*MATHS
-------------------------------------------*
/* Math.round()
---------------*/
//http://jsperf.com/math-round-vs-hack/53
//SLOW
var rounded = Math.round(somenum); // Use Hacks :
//GOOD
var rounded = ~~ (0.5 + somenum);
//BEST -> Hack with bitwise shift
var rounded = (0.5 + somenum) << 0;
//BEST2 -> Hack with bitwise OR
var rounded = (0.5 + somenum) | 0;
/*CANVAS
-------------------------------------------*/
/*Clearing
---------------*/
//BEST : clearRect
ctx.clearRect(0, 0, c.width, c.height);
/*Pre-rendering in Games
---------------*/
// http://jsperf.com/render-vs-prerender
/*jQUERY
-------------------------------------------*/
/*Selectors
---------------*/
//Always use .find() when possible : http://jsperf.com/context-vs-find-jquery/3
//Also, avoid using tags on the first selector : http://jsperf.com/jquery-selectors-testing-for-bobby
//BAD ->
$("element child");
//BEST ->
$("#element").find("child");
/*Tests
---------------*/
//Test if element is on the page
//BEST -> use native length method
if($("element").length){doThings();}
/*Chaining
---------------*/
//No performance differences between jquery chaining or not, so, chain when you can.
$().foo().bar().stuff() ....
/*Get attributes
---------------*/
//Use Native JS
//BAD
$testList.each(function() {
x = $(this).attr('id');
});
//BEST
$testList.each(function() {
x = this.id;
});
/*
---------------*/
//How to get the html string from a jquery object (eg : to copy dom elements)
//Use .prop()
$(this).find("img").prop('outerHTML')
-> '<img alt="" src="images/small/calendar-article-3-1colums.jpg">'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment