Associative arrays in Javascript

tldr; There are no associative arrays in Javascript. But there is indeed a credible alternative. In PHP, we can do the following - var fruits={}; fruits[3]="apple"; fruits[2]="orange"; fruits[1]="pear"; Javascript does not have associative arrays. All you can do is - const fruits = ["apple", "orange", "pear"]; Yes, you can define props for the array itself, but that is an altogether different thing. fruits["grape"] = "white"; The above statement does not “modify the array elements”. It just adds a prop to the array object. So, you cannot iterate and the length of array stays the same as before. ...

Allow a function call once and only once

Allow a function to be called once and only once. We have previously seen an example where debounce can be used to call a function once and can ignore subsequent calls. There is a shorthand way to allow a single function call that if you are not interested in the debounce part of the problem. function getSum(x, y) { arguments.callee.count = arguments.callee.count || 0; arguments.callee.count++; console.log(arguments.callee.count); // 1 2 3 if (arguments.callee.count <= 1) { console.log("sum", x + y); return x + y; } } getSum(4, 2); // 6 getSum(1, 2); // no sum getSum(0, 1); // no sum This is cool, right? Ok then, here’s what you do for homework - discover a way to allow calling any given function twice and only twice.

Using switch with number ranges

You can easily use switch to check whether a number is in specified range. We have seen the advantages of using switch instead of if/else. const num = 1; switch (num) { case 1: console.log("one"); break; case 2: console.log("two"); break; case 5: console.log("five"); break; default: console.log("none"); } You are sold by now, but there is this problem - how will you use switch if you need to check whether num < 10 and num > 5. You may have missed this from our date validation logic, but switch can do the range checks well. You just have to change the conditions a bit. ...

Negative number index in Arrays

Negative number indexes do not countdown in an array in Javascript. There was this forum post that asked about why negative numbers do not work “as expected” in an array. The logic of the question is - const nums = [1, 3, 5]; console.log(nums[-1]); // should have been 5, but returns undefined I fondly remembered my good ol’ days with Python, and then thought about two things - Why do people not use Google? Why do I exist in this universe? The second question was more philosophical in nature, is persistent, and has nothing to do with the question. ...

Check if type of value is array

Check whether a given value is an array before subjecting it to array methods. Loose typing can be a pain when your methods are being called from other methods / external modules. It is a good idea to check for valid types to avoid throwing runtime errors that are difficult to understand or parse. Using type checks is one such practice. As seen earlier, type checks is easily done for primitives. ...

Get a random value from array

Get a random unique value from a specified array. You can use one of the hundred ways to get values at a specific index, or iterate over an array and get values in sequence. const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log(nums[0]); // 1 nums.forEach(val => console.log(val)); // 1 2 3 4 5 6 7 8 9 But, what if you want to randomly get values from the array? That is easy too. console.log(nums[Math.floor(Math.random() * nums.length)]); console.log(nums[Math.floor(Math.random() * nums.length)]); console.log(nums[Math.floor(Math.random() * nums.length)]); However, you will see more repeating values than expected in the above logic (especially if you have a small array). To avoid repetitions, you can compare your current random index with previous random index, and change it if equal. ...

Shorthand for multiple 'or' condition checks

Use this shortcut to do multiple checks in one go. You have seen an or condition a billion times before, haven’t you? const fruit = "apple"; let shape; if (fruit == "apple" || fruit == "orange" || fruit == "water melon") { shape = "round"; } console.log(shape); // round We use or conditions quite a bit, and there is a way to streamline that code. const fruit = "apple"; let shape; if (["apple", "orange", "water melon"].indexOf(fruit) >= 0) { shape = "round"; } console.log(shape); // round Or, you could use an object. const fruit = "apple"; let shape; if ({ apple: true, orange: true, "water melon": true }[fruit] >= 0) { shape = "round"; } console.log(shape); // round These methods are particularly useful when you have to run your values through a set of validation rules. Instead of using nested if or switch statements, you can use a simple array or object to make your code more readable.

Shortcut to initialize objects

Here’s a quick and more readable way to initialize objects from other variables. But, first - how do you normally define objects? const nums = {}; I mean.. initialize objects - from other variables. let x = 2; let y = 4; const nums = { x: x, y: y }; console.log(nums); // { x: 2, y: 4 } You can do the same without using named variables if you like. let x = 2, y = 4; const nums = { x, y }; console.log(nums); // { x: 2, y: 4 } The same holds true for more complex objects as well. ...

Use Array Fill to Create Magic

How to use Array.fill() to your fill. We have seen examples of how to use Array.fill() to quickly fill data in an array. But, can we do more? Yes..! You can generate array with sequential numbers. Use Array.fill() to line up your number array in sequence. const nums = new Array(10).fill().map((val, index) => index + 1); console.log(nums); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Note technically an array.fill(), but you get it :)

Use Bubble Sort to Manually Sort an Array

How can we use our beloved bubble sort in Javascript? We have seen examples of how to sort an array and sorting with multiple attributes. The easiest way is to sort an array is to just use Array.sort(). But that alone will not show you the complexity that you want to show in your program (for e.g. for your next college thesis work that requires you to write minimum 100 pages of code). ...