Skip to content

kerwitz/jstips

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 

Repository files navigation

header

Introducing Javascript Tips

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.

Insert a new item into an array

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.1

Don'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.1

Instead 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!

Can you help us enrich it?

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

Let’s keep in touch

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!

Tips list

Return back the January 1st

License

CC0

About

This is about one JS tip every day!

Resources

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • JavaScript 100.0%