Hazards of Using Imperative Code

Hazards of Using Imperative Code

Some times, when you have written a short and clear and simple code but the result is wrong, yeah it's so confusing. 

In my last experience, I had written a simple code and it had the wrong result, it was because of the imperative code. In javascript there is a simple method called splice(), that does two things:

The splice() method adds/removes items to/from an array, and returns the removed item(s).

In this case, you should pay attention, how to use it. if you use it twice, after the first time, your array changed. and the second time you will face with the incorrect result. this is simple but it is the hazard of using Imperative code. 

In this sample, the goal is to remove the index from the array. My mistake was like this:

let a = [1,2,3,4,5];

let b = a.splice(0,2);

let c = a.splice(3);

console.log(a);

console.log(b);

console.log(c);

/****************************/

Array(3) [3, 4, 5]

Array(2) [1, 2]

Array(0) []

so we could see the join of "a" and "b" won't make an array without index. this is a common mistake and we must change the second line 3 to :

let c = a.splice(1);

and so the result is correct:

Array(1) [3]

Array(2) [1, 2]

Array(2) [4, 5]




Mehdi Jovaini

Senior oracle developer

4 年

The wolf of wallstreet

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了