One of the New Years Resolutions, if I had one, would have been to learn JS this year. And as far as I am a VBA developer I automatically assume that I know the basics of it. But still, there are some nice things in JS that one can only dream about in VBA. Thus, in this article I have decided to summarize some of them.
Let’s start. The nice things for a VBA developer in JS are probably mapping, filtering and reduction. The idea of mapping is to produce something out of an array. E.g. in the example I produce a new array from the squared values of my array. (arr_b) Then I filter the array, getting only each third value in the array (arr_c). In arr_d and arr_e I use reduction. Reduction does not return arrays, thus the naming “arr_d” and “arr_e” is not really a good idea, but I have done it.
To make the article a nicer one, I have decided to add an object with functions – simple_plan. In this object I have two functions, both of which are generating some variables. The “add_one” function also returns “ALE”, so we may see it if we print the function with “document write”. This is what we get from our code:
This is the code itself:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
arr_a = [8,10,12,1,17,29,30]; arr_b = arr_a.map(function (sqrt){ return sqrt * sqrt; }); arr_c = arr_b.filter(function(x,counter){ return counter % 3 == 2; //each third }); arr_d = arr_a.reduce(function(x,y){ return x + y + 50; }); arr_e = arr_a.reduce(function(x,y){ return (x<y?x:y); }); var simple_plan = { week1: 100, week2: 200, average: function() { this.avg = (this.week1 + this.week2) / 2; }, add_one: function(){ this.added_one = (this.avg*2+1); return "ALE"; } } simple_plan.average(); simple_plan.add_one(); simply_print(arr_a); simply_print(arr_b); simply_print(arr_c); simply_print(arr_d); simply_print(arr_e); simply_print(simple_plan.avg); simply_print(simple_plan.add_one()); simply_print(simple_plan.added_one); function simply_print(arr_k){ document.write("<hr>"); if (!Array.isArray(arr_k)) { document.write(arr_k); return; } for (i=0;i< arr_k.length;i++){ document.write(arr_k[i]+"<br>"); } } |
Here comes the code in github. Enjoy it! 😀