Javascript - Array

| Comments

Array Manipulation

Insert an item into an existing array is a daily common task. You can add elements to the end of an array using push, to the beginning using unshift, or the middle using splice.

But those are known methods, doesn’t mean there isn’t a more performant way [or] maybe a faster way.

Add to end of an array
Add a element at the end of the array is easy with push(), but there is a way more performant.

1
2
3
4
var arr = [1,2,3,4,5];

arr.push(6);
arr[arr.length] = 6; // 43% faster in Chrome 47.0.2526.106 on Mac OS X 10.11.1

Both methods modify the original array. Don’t believe me? Check the jsperf

Add to beginning of an array
Now we are trying to add a item to the beginning of the array

1
2
3
4
var arr = [1,2,3,4,5];

arr.unshift(0);
[0].concat(arr); // 98% faster in Chrome 47.0.2526.106 on Mac OS X 10.11.1

Here is a little bit detail, unshift edit the original array, concat return a new array. jsperf

Add to middle of an array
Add items at the middle of an array is easy with splice and is the most performant way to do it.

1
2
var items = ['one', 'two', 'three', 'four'];
items.splice(items.length / 2, 0, 'hello');

Tried to run these tests in various Browsers and OS and the results were similar.

Next time you write you code don’t just check for the best way of writing your code but also write code which runs faster to improve performance.

Convert Nodelist to Array

The querySelectorAll method returns an array-like object called a node list. These data structures are referred to as “Array-like”, because they appear as an array, but can not be used with array methods like map and foreach.

Here’s a quick, safe, and reusable way to convert a node list into an Array of DOM elements:

1
2
3
4
5
6
7
8
const nodeList = document.querySelectorAll('div');
const nodeListToArray = Array.apply(null, nodeList);

//later on ..

nodeListToArray.forEach(...);
nodeListToArray.map(...);
nodeListToArray.slice(...);

The apply method is used to pass an array of arguments to a function with a given this value. MDN states that apply will take an array like object, which is exactly what querySelectorAll returns. Since we don’t need to specify a value for this in the context of the function, we pass in null or 0. The result is an actual array of DOM elements which contains all of the available array methods.

Alternate method if you are using ES2015 you can use the spread operator ...

1
2
3
4
5
6
7
const nodeList = [...document.querySelectorAll('div')]; // returns a real Array

//later on ..

nodeList.forEach(...);
nodeList.map(...);
nodeList.slice(...);

Empty an Array

You define an array and want to empty its contents. Usually, you would do it like this:

1
2
3
4
5
6
7
// define Array
var list = [1, 2, 3, 4];
function empty() {
    //empty your array
    list = [];
}
empty();

But there is another way to empty an array that is more performant.

You should use code like this:

1
2
3
4
5
6
var list = [1, 2, 3, 4];
function empty() {
    //empty your array
    list.length = 0;
}
empty();
  • list = [] assigns a reference to a new array to a variable, while any other references are unaffected. which means that references to the contents of the previous array are still kept in memory, leading to memory leaks.

  • list.length = 0 deletes everything in the array, which does hit other references.

In other words, if you have two references to the same array (a = [1,2,3]; a2 = a;), and you delete the array’s contents using list.length = 0, both references (a and a2) will now point to the same empty array. (So don’t use this technique if you don’t want a2 to hold an empty array!)

Think about what this will output:

1
2
3
4
5
6
7
8
9
var foo = [1,2,3];
var bar = [1,2,3];
var foo2 = foo;
var bar2 = bar;
foo = [];
bar.length = 0;
console.log(foo, bar, foo2, bar2);

// [] [] [1, 2, 3] []

Stackoverflow more detail: difference-between-array-length-0-and-array

Books I Read in 2015

| Comments

I don’t actually have a habit of reading books, but I read a lot of articles from blog. I got into a habit of reading physical books late in 2013 & the feeling was unique.

You watch a movie, you are feeding your mind with the visuals you see. But when you read a book it let your mind imagine the scene happing on that particular sentence and that’s why I hope most of the people love reading books over movies.

I always believe in small and progressive goals than setting something high and end up with an disappointment of not winning(which may sometimes let you not to try that goal every again in your life), So I set a goal of reading 6 books in 2015. It wasn’t a tough challenge but I kinda feel happy when I complete my goal.

I’m planning to set a reading challenge every year and write about my accomplishment, the books I read & my opinion. This is first post in the series. Here is the set of books I read in 2015

1. Javascript: The Good Parts

by Douglas Crockford

I love Javascript like most web developer does, The first book I bought for learning Javascript is ‘Javascript The Definitive Guide’ a big book of course holds many useful information, but I feel that I made a mistake by purchasing a big book rather than starting with a small one. Reason being I got bored when I read the definitive guide as its so massive explain things in a detailed manner than a short understandable manner for beginner.

Good parts is fairly small book which holds nearly the main concepts of Javascript and of course only the good parts. I thought that’s enough for a beginner to learn the great things first and then try to optimise the way they code by skipping the bad parts.

2. You Don’t Know JS: Up & Going

by Kyle Simpson

You Don’t Know JS - That’s kinda pointing at me, I took it not in a negative but treat it as positive that If I read the book I can say “I Know JS”. So I bought first three books in the series of YDKJS

Another small book and very interesting indeed, Kyle had a style of explaining things short and provide with a nice example for the user to get a grasp of what he is trying to communicate.

3. Scope and Closures

by Kyle Simpson

After reading the first book of YDKJS by Kyle I can’t stop to open the next book in the series which turn out to be a good treasure to find out some nitty gritty parts about the scope and closures which is the most important part of Javascript.

4. Eat That Frog!: 21 Great Ways to Stop Procrastinating and Get More Done in Less Time

by Brain Tracy

Man this book is one master piece, it changed my life. One of my client recommended this book I just bought it to check what’s in it, which turned out to be a best book I read after “Rework" by Jason Fred. Everything in the book is organised and it will make you organise in your tasks, Focus on major things and the 21 ways is the way to success.

I strongly recommend this book to people in all fields to grow up to the next level in their career.

5. Learning Javascript Design Patterns

by Addy Osmani

After learning good parts, know how things work from YDKJS first two books, I took the Design patterns book which I purchased but not read for sometime. I feel that it’s correct time to read about design patterns and apply in some of my code. The book is not only for learning design patterns, it gives me ideas to think of the way I should write the code before even coding.

“You follow a design pattern which suits your need and you are already avoiding problems and writing a well organized code”

6. Wings of Fire: An Autobiography

by A.P.J. Abdul Kalam, Arun Tiwari (Contributor)

Pretty inspiring story of boy from small village in Tamilnadu growing to rocket man who put India in the top countries which excels in Missile & Rocket Technology.

PS: This is just quick post which I manage to do it, Will add more details soon.