I’m trying to understand how to use functions in JS.
This code converting decimal numbers to binary numbers:
JavaScript
x
21
21
1
for (j = 13; j <= 16; j++) {
2
res = ""
3
number = j
4
5
while (number > 0) {
6
res = res + number % 2
7
number = Math.floor(number / 2)
8
}
9
10
len = res.length
11
12
rev=""
13
14
for (i = 1; i <= len; i++) {
15
rev = rev + res[res.length - i]
16
}
17
18
console.log(rev)
19
}
20
21
but when I’m trying to put this code into a function, the function returns only the first or the last value. What am I doing wrong?
JavaScript
1
23
23
1
function f(min, max) {
2
for (j = min; j <= max; j++) {
3
res = ""
4
number = j
5
6
while (number > 0) {
7
res = res + number % 2
8
number = Math.floor(number / 2)
9
}
10
11
len = res.length
12
13
rev=""
14
15
for (i = 1; i <= len; i++) {
16
rev = rev + res[res.length-i]
17
}
18
}
19
return rev
20
}
21
22
console.log(f(13,15))
23
Advertisement
Answer
You have to store the result of each iteration in array.
JavaScript
1
26
26
1
function f(min, max) {
2
const results = []
3
for (j = min; j <= max; j++) {
4
res = ""
5
number = j
6
7
while (number > 0) {
8
res = res + number % 2
9
number = Math.floor(number / 2)
10
}
11
12
len = res.length
13
14
rev=""
15
16
for (i = 1; i <= len; i++) {
17
rev = rev + res[res.length-i]
18
}
19
20
results.push(rev)
21
}
22
return results
23
}
24
25
console.log(f(13,15))
26
Also you should declare your variables in JavaScript, because not doing that can lead to bugs https://www.geeksforgeeks.org/what-happen-when-we-directly-assign-the-variable-without-declaring-it-in-javascript/