-2

I'm currently learning JS and I'm not quite sure what this does. Could I please get some explanation?

  num = num.map(x => {
        return (x == 0) ? 1: 0; 
    }).join("");

Thank you.

  • 6
    Which part presents a problem? – VLAZ Nov 20 '21 at 23:00
  • 5
    it's important to read [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) – ProDec Nov 20 '21 at 23:03
  • 2
    You could invest some more time of checking the official mdn docs. What does Array.map produces as output and what is the purpose of Array.map, rather than asking the same directly on stack overflow. – Nitheesh Nov 20 '21 at 23:03

1 Answers1

2

map calls a provided callbackFn function once for each element in an array, in order, and constructs a new array from the results. callbackFn is invoked only for indexes of the array which have assigned values (including undefined).

// Arrow function
map((element) => { ... })
map((element, index) => { ... })
map((element, index, array) => { ... })

// Callback function
map(callbackFn)
map(callbackFn, thisArg)

// Inline callback function
map(function(element) { ... })
map(function(element, index) { ... })
map(function(element, index, array){ ... })
map(function(element, index, array) { ... }, thisArg)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

So with that in mind, let's take a look at the JS code

  num = num.map(x => {
        return (x == 0) ? 1: 0; 
    }).join("");

For me this code is somewhat incomplete, but I would imagine that you might have something like

let num = [1,2,3,4,5,6,7,8,9,10]

num = num.map(x => {
        return (x == 0) ? 1: 0; 
    }).join("");
// we reassign the value of num to a NEW array, because map will create that for us.
// when we call .map() on our array, it will begin to iterate over the array
// we're giving each element an arbitrary name of 'x'
// In our return statement, we are going to make a comparison with a ternary operator.
// We are going to loosely compare each element of the array (x) to zero.
// If this is true, we reassign x to 1. If this is false, we reassign to 0
// We then join the array with no separators using Array.prototype.join()
// => '0000000000'

So now if we do it with another array, let's see what happens.

let num = [0,0,1,1,4,0,5]
num = num.map(x => {
        return (x == 0) ? 1: 0; 
    }).join("");
// => '1100010'