New year, new project. A JS tip per day!
With great excitement, I introduce short and useful Javascript tips per day that will allow you to improve your code writing. With less than 2 minutes each day, you will be able to read about performances, frameworks, conventions, hacks, interview questions and all the items that the future of this awesome language holds for us.
At midday, no matter if it is a weekend or a holiday, a tip will be posted and tweeted.
Just to give you a glance, this is an example of how the tips would be like.
12/29/2015
Inserting a new item into an existing array is a common daily task. You may append elements to the array using Array.prototype.push(), prepend them using Array.prototype.unshift(), or insert them inbetween using Array.prototype.splice().
But although these are the best known methods for those tasks, better performing ways do exist.
Adding an element at the end of the array is easy with Array.prototype.push() but there's a faster alternative:
var items = [1,2,3,4,5];
items.push(6);
items[items.length] = 6; // 43% faster in Chrome 47.0.2526.106 on Mac OS X 10.11.1Don't believe me? Check the jsperf! Both methods will modify the original array.
Lets prepend an item to the the array:
var items = [1,2,3,4,5];
items.unshift(0);
[0].concat(items); // 98% faster in Chrome 47.0.2526.106 on Mac OS X 10.11.1Instead of using unshift we can also create a fresh array and join it with arr. Array.prototype.concat() will combine both into a new array and return the result.
Check the jsperf!
For inserting elements inbetween the existing ones Array.prototype.splice() turns out to be the best option.
var items = ['one', 'two', 'three', 'four'];
items.splice(items.length, 0, 'hello');You may actually go faster but at the cost of code readability.
I tried run these test in various navigators and os and the results were similar. Please do perform your own tests. I hope these tips turn out to be useful!
Please feel free to send us a PR with your own Javascript tip to be published here. Any improvements or suggestions are more than welcome! Click to see the instructions
To get updates, watch the repo and follow @tips_js, only one tweet will be sent per day. That's a deal!
Don't forget to star the repo, this will help to spread the project!
Return back the January 1st