DEV Community

Harshit Kedia
Harshit Kedia

Posted on

Useful Javascript nuggets

Finished revising basic javascript from freecodecamp, noted some important points:

-> For a multi-dimensional array, we can use the following logic to loop through both the array and any sub-arrays, when the length of the arrays vary or is unknown:

const arr = [ [1, 2], [3, 4], [5, 6] ];

for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}

-> Recursion (function calling upon itself): For multiplying the first n elements of an array:
multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]
Therefore the code can be:
function multiply(arr, n) {
if (n <= 0) {
return 1;
} else {
return multiply(arr, n - 1) * arr[n - 1];
}
}
*Recursive functions must have a base case when they return without calling the function again (in this example, when n <= 0), otherwise they can never finish executing.

-> Formula to generate a random whole number in the range from given min to max:
Math.floor(Math.random() * (max - min + 1)) + min

-> parseInt(string, radix)
Radix specifies the base of the number in the string, which can be an integer between 2 and 36, stores the parsed input as integer. Eg: in the following code, 11 is in the binary system, or base 2:
const a = parseInt("11", 2);

-> Code for an array of 1 to N using recursion:
function countup(n) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1);
countArray.push(n);
return countArray;
}
}
*The array returned here is from 1 to N and not from N to 1 because at the point where n is pushed into the array, countup(n - 1) has already been evaluated and returned.

Top comments (0)