# something I cannot understand in javascript code

## Recommended Posts

`function sum(input){ if (toString.call(input) !== "[object Array]") return false; var total = 0; for(var i=0;i<input.length;i++) { if(isNaN(input[i])){ continue; } total += Number(input[i]); } return total; } console.log(sum([1,2,3])); console.log(sum([100,-200,3])); console.log(sum([1,2,'a',3]));`

In this code I do not understand what is

` total += Number(input[i]);`

Number ????

##### Share on other sites
Ingolme    794

It converts the string into a number so that math operations can be done with it. You should read about data types: https://www.w3schools.com/js/js_datatypes.asp

##### Share on other sites

you said Number convert the string into numbers so why here in this code I got NAN

``` function sum()
{
var total = 0;
var letters = ["A" , "B"];
for(x = 0 ; x < letters.length ; x++)
{
total += Number(letters[x]);
}
document.write(total);
}

var x = sum();```

if you run it in the browser you will get NOT A NUMBER OR NAN

##### Share on other sites
davej    244

Because the string "A" cannot be converted to a number.

• 1

##### Share on other sites

ok I understand

Quote

It converts the string into a number so that math operations can be done with it

the items inside the array are numbers so why we need to convert them into numbers ???

and therefore why do not we simply write :

` total += input[i];`

?

##### Share on other sites
dsonesuk    701

IF the values in the array are taken from text type input, the numbers in array will be a string/text, it is precautionary to make sure when used in math operations that 16 + "4" don't equal "164", but 20.

• 1

##### Share on other sites
davej    244
```var a = ["123", 123, "1a2b3c", 122.222, "A"];

for(var i=0 ; i<a.length ; i++){
if(isNaN(a[i])){
alert('a['+i+'] is not a number (nan)');
}
}```

• 1

##### Share on other sites

There are things I cannot understand in this code :

`function subset(arra, arra_size) { var result_set = [], result; for(var x = 0; x < Math.pow(2, arra.length); x++) { result = []; i = arra.length - 1; do { if( (x & (1 << i)) !== 0) { result.push(arra[i]); } } while(i--); if( result.length >= arra_size) { result_set.push(result); } } return result_set; } console.log(subset([1, 2, 3], 2));`

The `Math.pow()` function returns the `base` to the `exponent` power, that is, `baseexponent`.

But I do not understand why it is used in the code above ? what is the purpose of it ? and why it is used in combination with

`arr.length`

what does this mean :

`i = arra.length - 1; `

why bitwise and shift operators are used here in this code ? for what purpose ?

`(x & (1 << i)) !== 0)`

what is the purpose of making an empty array ?

`result = [];`

##### Share on other sites
justsomeguy    939

Format that code so it's readable, and add some console.log statements to have it print out what it's doing.

```function subset(arra, arra_size)
{
var result_set = [], result;
for(var x = 0; x < Math.pow(2, arra.length); x++) {
console.log('x is ' + x);
result = [];
i = arra.length - 1;
console.log('i is ' + i);
do {
console.log('(1 << i) is ' + (1 << i));
console.log('x & (1 << i) is ' + (x & (1 << i)));
if( (x & (1 << i)) !== 0) {
result.push(arra[i]);
}
} while(i--);
console.log('result:');
console.log(result);
if( result.length >= arra_size) {
result_set.push(result);
}
}
return result_set;
} ```

Do you understand the purpose of that code, do you understand why it returns what it does for the input?

##### Share on other sites

Syntactic , this what I could understand so far
f

```unction subset(arra, arra_size) {
var result_set = [],
result;

for (var x = 0; x < Math.pow(2, arra.length); x++) {
result = [];
i = arra.length - 1;
do {
if ((x & (1 << i)) !== 0) {
result.push(arra[i]);
}
} while (i--);

if (result.length >= arra_size) {
result_set.push(result);
}
}

return result_set;
}

console.log(subset([1, 2, 3], 2));```

the for loop , loops

` Math.pow(2, arra.length)`

time . For example here it loops 2 exponent 3 time that is 8 times

`` i = arra.length - 1; ``

is , of course ,  array length -1

`if( (x & (1 << i)) !== 0)`

each time it loops it looks if

``x & (1 << i)) !== 0``

put the result in the empty array result []

`result.push(arra[i])`
`while(i--);`

is a reverse loop . It reverse the numbers .

` if( result.length >= arra_size)`

put a condition so that while does not loop infinitely

` result_set.push(result);`

push the sub arrays in the array

`` result_set``

I cannot understand  the code semantically :

1) math.pow is an exponent mathematical function . What has it to do with array length and for loop in the code above . What is the logical beyond using it ?

2) what is the logic beyond  using bitwise operators in the if condition ?

``if( (x & (1 << i)) !== 0)``
````3)`
```
`` i = arra.length - 1; ``

what is the logic beyond substracting the  array length from 1 ?

4) in the function parameters I understand why the arra is used but why  arra-size is used ?

Quote

Do you understand the purpose of that code, do you understand why it returns what it does for the input?

``````here is the purpose of it :

```http://www.w3resource.com/javascript-exercises/javascript-function-exercise-21.php
```

no I do not understand why it returns what it does for the input because i as I mentioned above i do not get what the code line by line , semantically , does ?

##### Share on other sites
justsomeguy    939

Like that page says, it returns all subsets longer or equal to a certain length.  Do you understand what a subset is?

##### Share on other sites

yes i know what is a subset but i do not know the answer for my 4 questions . That is why I asked them

##### Share on other sites
justsomeguy    939

Well, if you know what a subset is, and you know that this function finds subsets, then you should be able to figure out the answers to some of those questions.

math.pow is an exponent mathematical function . What has it to do with array length and for loop in the code above . What is the logical beyond using it ?

It's the number of possible subsets.

what is the logic beyond  using bitwise operators in the if condition ?

That's how it determines which elements to pull from the source array for each subset.  If you run the version I posted with all of the output it makes it more obvious.

what is the logic beyond substracting the  array length from 1 ?

That's backwards, it subtracts 1 from the array length, and that is the index of the last element in the array.

in the function parameters I understand why the arra is used but why  arra-size is used ?

It's the minimum size for the returned subsets.  Passing 2 means they aren't interested in the subsets with a length of 0 or 1.

##### Share on other sites
Quote

If you run the version I posted with all of the output it makes it more obvious.

with all due respect , after running the version you posted to me , things become more obscure :

Here is the whole code :

```function subset(arra, arra_size) {
var result_set = [],
result;
for (var x = 0; x < Math.pow(2, arra.length); x++) {
console.log('x is ' + x);
result = [];
i = arra.length - 1;
console.log('i is ' + i);
do {
console.log('(1 << i) is ' + (1 << i));
console.log('x & (1 << i) is ' + (x & (1 << i)));
if ((x & (1 << i)) !== 0) {
result.push(arra[i]);
}
} while (i--);
console.log('result:');
console.log(result);
if (result.length >= arra_size) {
result_set.push(result);
}
}
return result_set;
}

var matrix = subset([2, 5, 6], 2);```

I run it line by line :

`console.log('x is ' + x);`

gives

x is 0x is 1x is 2x is 3x is 4x is 5x is 6x is 7

`console.log('i is ' + i);`

gives

i is 2i is 2i is 2i is 2i is 2i is 2i is 2i is 2

```console.log('(1 << i) is ' + (1 << i));
console.log('x & (1 << i) is ' + (x & (1 << i)));```

give

(1 << i) is 4(1 << i) is 2(1 << i) is 1(1 << i) is 4(1 << i) is 2(1 << i) is 1(1 << i) is 4(1 << i) is 2(1 << i) is 1(1 << i) is 4(1 << i) is 2(1 << i) is 1(1 << i) is 4(1 << i) is 2(1 << i) is 1(1 << i) is 4(1 << i) is 2(1 << i) is 1(1 << i) is 4(1 << i) is 2(1 << i) is 1(1 << i) is 4(1 << i) is 2(1 << i) is 1

x & (1 << i) is 0x & (1 << i) is 0x & (1 << i) is 0x & (1 << i) is 0x & (1 << i) is 0x & (1 << i) is 1x & (1 << i) is 0x & (1 << i) is 2x & (1 << i) is 0x & (1 << i) is 0x & (1 << i) is 2x & (1 << i) is 1x & (1 << i) is 4x & (1 << i) is 0x & (1 << i) is 0x & (1 << i) is 4x & (1 << i) is 0x & (1 << i) is 1x & (1 << i) is 4x & (1 << i) is 2x & (1 << i) is 0x & (1 << i) is 4x & (1 << i) is 2x & (1 << i) is 1

``` console.log('result:');
console.log(result);
```

give

result:result:result:result:result:result:result:result:

255,266,26,56,5,2

except the last result all the results of console log  the version you gave me  are obscure and made me more confused

Moreover I still do not understand how math.pow gives the number of all possible subset ?!!!

I read the tutorials about javascript in w3school site which were very useful and helped me a lot but even so I could not get a clear understanding about the code above . Justsomeguy could you please tell me what should I do in order to be able to understand very well the code above ?

##### Share on other sites
justsomeguy    939

Hold on, are you running different versions of that code with only 1 of the console.log statements?  If so, I think you're missing the point of having all of those console.log statements.  Also, the console.log statement where it prints i should probably go inside that do loop, the point is so that you can use that to see what the calculations are doing.

Moreover I still do not understand how math.pow gives the number of all possible subset ?!!!

If you have a set with 3 items in it, how many possible subsets can you create?  The answer is 8 - 23.  If the set has 4 items in it, then there are 16 possible subets - 24. You use Math.pow to get that value from the length of the set.  If you don't understand that then work it out on paper.

• 1

##### Share on other sites
Quote

Hold on, are you running different versions of that code with only 1 of the console.log statements?

that what I , unfortunately , did . However , I run it again with all the console.log statements inside it and , now the logic of the code becomes far more clear to me than before . Moreover , now I understand very well the logic beyond using the Math.pow function . However even with this :

I still cannot grasp very well  the use of bitwise operators in the code

Quote

That's how it determines which elements to pull from the source array for each subset

and this :

(1 << i) is 1
x & (1 << i) is 0
result:
Array [ 2 ]
x is 3
i is 2
(1 << i) is 4
x & (1 << i) is 0
(1 << i) is 2
x & (1 << i) is 2
(1 << i) is 1
x & (1 << i) is 1
result:
Array [ 2, 1 ]
x is 4
i is 2
(1 << i) is 4
x & (1 << i) is 4
(1 << i) is 2
x & (1 << i) is 0
(1 << i) is 1
x & (1 << i) is 0
result:
Array [ 3 ]
x is 5
i is 2
(1 << i) is 4
x & (1 << i) is 4
(1 << i) is 2
x & (1 << i) is 0
(1 << i) is 1
x & (1 << i) is 1
result:
Array [ 3, 1 ]
x is 6
i is 2
(1 << i) is 4
x & (1 << i) is 4
(1 << i) is 2
x & (1 << i) is 2
(1 << i) is 1
x & (1 << i) is 0
result:
Array [ 3, 2 ]
x is 7
i is 2
(1 << i) is 4
x & (1 << i) is 4
(1 << i) is 2
x & (1 << i) is 2
(1 << i) is 1
x & (1 << i) is 1
result:
Array [ 3, 2, 1 ]

I am still unable to understand how and why  the bitwise operators are used to determine which element is pulled from the set and pushed in the subset ??

Could you please make it more clear to me

##### Share on other sites
justsomeguy    939

That's how it figures out which elements to pull for each subset, so that it creates every subset.  For an array with 3 elements, you can think of each subset as containing the numbers in the positions that are set to 1 if you map out 0 to 8 in binary:

```0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1```

Those are the 8 possible subsets.  Bit-shifting the 1 to the left will have it start with 0 0 1, 0 1 0, or 1 0 0, and then ANDing that value with the other counter will provide that list of sets.  When you're looking at the debug output for those operations it helps to convert the numbers to binary values, because that's what it's doing.

##### Share on other sites
Posted (edited)

now the things become more clear : the shift operator is used to change the position of the numbers in the set and the and operator is used to concatenate them together so that they form all possible subset . What I understood ,  too , is that the number of subsets in a set of x elements is 2 exponent x . The code above is taken from this page :

In the end of the code , there is this instruction :

`console.log(subset([1, 2, 3], 2));`

and the expected output from it is  , as mentioned ,

Expected output : [[2, 1], [3, 1], [3, 2], [3, 2, 1]]

which are 4 subsets

however if we take a look at the array in the instruction above , we will see that it contains 3 elements . So 2 exponent 3 is 8 . So normally we need to have 8 subsets and not 4 subsets . So why we got 4 subsets ?

Edited by hisoka

##### Share on other sites
justsomeguy    939

Look at the second parameter passed to the function.

##### Share on other sites

Normally , the second parameter passed to the function is 3 not 2 because the size of [1,2,3] is 3 not 2  . I know it is 3 through this :

`var array = [1, 2, 3] ; var x = array.length ; console.log(x) ;`

the output is 3 not 2 and 2 exponent 3 is 8 not 4

##### Share on other sites
dsonesuk    701

You do realise that the indexing of array starts from 0 not 1, so if you use array length (3) for last item in array (which will be index 2), it will come up as undefined, unless you use array.length -1 for the last record.

##### Share on other sites
Ingolme    794

The second parameter indicates the size of the subsets to search for, not the size of the initial set.

The expected output is wrong. The people who provided the exercise mentioned it here: http://www.w3resource.com/javascript-exercises/javascript-function-exercise-21.php#comment-3039932910

The output should only have subsets with two elements.

• 1

##### Share on other sites
Quote

The second parameter indicates the size of the subsets to search for, not the size of the initial set.

That is it thank you . Sorry , I did not read the comments . Next time I will read the comments too and look al all possible corners of the page

Quote

You do realise that the indexing of array starts from 0 not 1, so if you use array length (3) for last item in array (which will be index 2), it will come up as undefined, unless you use array.length -1 for the last record.

Yes I realise . However if the computer begins to calculate from 0 not from 1 like humans so why the output  here :

`var array = [1, 2, 3] ; var x = array.length ; console.log(x) ;`

is 3 and not 2 ?

##### Share on other sites
justsomeguy    939

The length is 3.  The indexes go from 0 to 2.  That is 3 elements, which is why the length is 3.  0, 1, 2 -> that's 3 elements.

• 1

## Create an account

Register a new account

×