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.

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay