Access an array in reverse in Javascript

Access an array in reverse. Consider the array in the code block below - const nums = [1, 2, 3]; Accessing the array is easy enough. console.log(nums[0]); console.log(nums[1]); console.log(nums[2]); /* 1 2 3 */ But, what if you want to access the array from the last element? Use pop We have seen one of the ways to do that using pop. console.log(nums.pop()); console.log(nums.pop()); console.log(nums.pop()); /* 3 2 1 */ But, this changes the array. console.log(nums); // [] Use slice If you want to just access the array from the last element, but not change the array - ...

Optional arguments using spread while calling functions

How about using the spread operator for handling optional arguments, or for null arguments? Consider this code - function sum(x, y, z) { return x + y + z; } We can choose to pass ‘z’ or not, but ignoring ‘y’ returns an error. console.log(sum(1, 2, 3)); // 6 console.log(sum(1, 2)); // NaN console.log(sum(1, , 3)); // error: Unexpected token , Sure, you can use a null or undefined in the middle and get away with it. But, you could also replace that with the spread operator like so - ...

Console.log function for easier debugging

Encapsulate a console.log() in a function and use it anywhere - even within the most complex expressions. The most typical console.log - console.log("hello world"); // hello world Change it to - function logThis(expr) { console.log(expr); return expr; } logThis("hello world"); // hello Why the circus? Well, consider you are debugging this really serious planet array marked for destruction. const planets = [ { name: "mercury", position: 1 }, { name: "venus", position: 2 }, { name: "earth", position: 3 } ]; console.log(planets.sort().filter(planet => planet.position == 3)); Sure, you can unchain the chain and debug. console.log(planets); console.log(planets.sort()); console.log(planets.sort().filter(planet => planet.position == 3)); But, there is no joy in the above code (and in the destruction task I might add). Is there? ...

True comparison using Object.is()

Object.is() provides a true comparison for any object. Start using it today if you have missed out so far..! Consider the code below - console.log("abc" == "abc"); // true console.log(null == null); // true console.log(1 == 1); // true // break console.log(0 == false); // true console.log("" == false); // true While we are ok with the statements above break, the statements below can cause a problem. Typically this is overcome by using strict comparison - console.log("abc" === "abc"); // true console.log(null === null); // true console.log(1 === 1); // true console.log(0 === false); // false console.log("" === false); // false But, what about the only edge case that is so.. so.. so important - ...

Tagged Templates in Javascript

Tagged templates allow our beloved template literals to be taken to a whole new level. The typical use of a template literal is below - let x = 1; let y = 5; console.log(`x is ${x}, y is ${y}`); // x is 1, y is 5 Template literals allow us to avoid stupid statements like this - console.log("x is " + x + ", y is " + y); // x is 1, y is 5 Template literals are cool. Tagged templates take the above function in a different way - ...

Searching the Void in Javascript

What is void and does it have a role in modern Javascript? The unary void operator is rather strange and has quirky use cases. Or, should I say ‘had quirky use cases’. Primarily, void was used to check the true undefined. Consider the below code - undefined = 0; console.log("undefined: ", undefined); The above code would return 0 instead of undefined a couple of years back. So, we did this instead - let planet; //.. a lot of code .. planet = void 0; console.log("planet: ", planet); // undefined void was a sure way to find the true undefined. ...

Easier Date Picker in Vuetify

Date pickers are straight forward, but can become laborious in Vuetify components. Look at how date pickers are implemented in Vuetify - they can cause minor trauma for a beginner. The efficient solution is to implement a custom component. Wrap menu + input box in that generic component, and use it everywhere. Or, just use v-datetime-picker. Get started Install v-datetime-picker in your Vue project. npm install --save vuetify-datetime-picker Add following in your main.js. ...

Input Field with Date Picker in Vuetify

Date pickers are straight forward to implement, but input fields with date pickers need a bit of decoration. What we need? An input field with a date picker that opens on click shows the selected date How do we create that? We start with the ‘date picker’ component in Vuetify. <template> <v-layout row wrap> <v-date-picker locale="en-in" :min="minDate" :max="maxDate" v-model="fromDateVal" no-title ></v-date-picker> </v-layout> </template> <script> export default { data() { return { fromDateVal: null, minDate: "2019-07-04", maxDate: "2019-08-30", }; }, }; </script> Bind value to fromDateVal. Specify locale, min & max dates. ...

Check whether array is a palindrome in Javascript

Check whether a given array has a palindrome in Javascript. Below logic should be fast, if not the fastest. console.log(checkPalindrome([1, 3, 5, 3, 1])); function checkPalindrome(arr) { const len = arr.length; if (len % 2 == 0) return false; for (let i = 0; i < len / 2; i++) { if (arr[i] !== arr[len - i - 1]) return false; } return true; } The code is simple - If given array length is even, it can’t be a palindrome Go through half the array, and find out whether array element is equal to the corresponding element on the “other side”. In other words, check whether first element is equal to last element, the second element is equal to the last but one element, and so on. ...

Find average and median of arrays in Javascript

Find average and median of a given array in Javascript. Problem We are given an array that is hopefully comprised of numbers. Find average and median. Get average Calculate sum, length and use them to get the average. const arr = [3, 7, 2, 6, 5, 4, 9]; const sum = arr.reduce((sum, val) => (sum += val)); const len = arr.length; console.log("average: ", sum / len); // 5.142857142857143 Get median Sort array. Median formula is different depending on whether length of array is odd or even. Array length = odd => median is the average of the two middle numbers Array length = odd => pick the middle number as median const arrSort = arr.sort(); const mid = Math.ceil(len / 2); const median = len % 2 == 0 ? (arrSort[mid] + arrSort[mid - 1]) / 2 : arrSort[mid - 1]; console.log("median: ", median); // 5 One important pre-requisite Although the above arrangement works, it is always a good idea to filter out our arrays for undesired elements! ...