1

This was derived from another coders Codewars solution

Aim: The code at this point in time is used to return the sum of rows and columns and diagonals, to see if all the sums stated of this 4x4 magic, are the same number

var arr = [
    [9, 6, 3, 16],
    [4, 15, 10, 5],
    [14, 1, 8, 11],
    [7, 12, 13, 2]
];

var _r = arr.map(v => v.reduce((a, b) => a + b), 0)
var _c = _r(arr.map((v, i) => v.map((_, j) => arr[j][i])));
var _d1 = arr = arr.reduce((s, _, i) => s + arr[i][i], 0);
var _d2 = a => a.reduce((s, _, i) => s + a[a.length - 1 - i][i], 0);

console.log(_r);
console.log(_c);
console.log(_d1);
console.log(_d2)

Problem: However the thing I can't get my head round is what the underscores in this code are used for, any ideas?

A. Tran
  • 333
  • 1
  • 5
  • 13
  • 1
    It's just a variable name. You can use $ and _ for variable names. – dfsq Mar 17 '17 at 12:16
  • 2
    It is commonly used by Underscore.js, but it can be any variable: http://underscorejs.org/ – Sander Aernouts Mar 17 '17 at 12:17
  • check this for more understanding. http://stackoverflow.com/questions/8288756/in-javascript-what-does-this-underscore-mean – UDID Mar 17 '17 at 12:19
  • It is just a variable. Also this is incorrect `var _c = _r(arr.map((v, i) => v.map((_, j) => arr[j][i])));` `_r` is just one variable. not function – UDID Mar 17 '17 at 12:19
  • @UDID Because of the map and reduce reference I think TO is asking about the "placeholder" in the parameters `(..., _, ...)` – Andreas Mar 17 '17 at 12:22
  • 1
    The underscore by itself is used by a lot of people to indicate parameters they don't care about. For instance if you have an event handler and don't care about the `Event` object: `elem.addEventListener('click', _ => document.querySelector('#other-elem').textContent = 'foobar');` – Jared Smith Mar 17 '17 at 12:22

1 Answers1

3

In this particular case, they're used as parameter names for parameters that the person writing the code didn't intend to use.

They didn't want to bother giving those parameters names, so they named them _.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • So what would variable `_` represent in this case, for `var _d2 = a => a.reduce((s, _, i) => s + a[a.length - 1 - i][i], 0);` as in what parameter does '_' represent? – A. Tran Mar 17 '17 at 13:27
  • @A.Tran In `Array#reduce` the second parameter holds the value of each successive value in the input array. That line of code ignores that parameter and produces a result based only on the the accumulator `s` and the successive index numbers `i`. That code produces a function `_d2` that takes a 2-dimensional array and returns the sum of the diagonal from the bottom-left to top-right: `arr[3][0] + arr[2][1] + arr[1][2] + arr[0][3]` – JLRishe Mar 17 '17 at 13:37