Assigning default values while object destructuring

Easily assign default values while destructuring objects. Consider below code- const obj = { x: 9, y: 1 }; const { x, y } = obj; console.log(x, y); // 9 1 A typical destructuring of objects, this code assigns x and y variables to the x/y props of object obj. This is a-ok, but what if you want to specify defaults in case any of the props are not present? Such defaults help avoid unexpected errors during further processing. Consider below code - const obj = { x: 9 }; const { x, y, z = 1 } = obj; console.log(x, y, (z = 1)); // 9 undefined 1 What’s happening here - ...

Use functional components in Vue

Use light-weight functional components if you want stateless components. Components consist of many different parts in Vue - Data computed properties methods etc. Data property in particular stores states of the component, and enables the component to react to prop changes by keeping track of all that the component has to go through. What if you want no states? For e.g. you have a ‘Contact Service’ component that is statically displayed as an icon on the main page, or a footer component that takes in a prop and displays its value. ...

Evaluate and test Vue scripts using single HTML file

How do you test your Vue code blocks and theories? Of course, you can simply have a test Vue project and throw in a single file component each time. Or, you could follow a simple structure to create a HTML/JS files. Or, you could just create everything in a single HTML page and clone it for quick tests. Not a new concept by any means - but I still wonder why I stick to SFCs each and every time. ...

Signify end of function with a return

return terminates function whenever and wherever it is called. Consider this code block - function getSum(x, y) { return x + y; let product = x * y; console.log(`sum is: ${x + y}, while product is ${product}`); } console.log(getSum(1, 5)); // 6 // no other console statements return will return the control to caller - no matter what state the function is in. You can also use conditional return, or have multiple returns in different blocks. function doSomething(x, y) { if (y > 100) return false; if (x < 0 || x > y) return false; for (let i = x; i < y; i++) { // complex logic const superComplexVar = 0; if (superComplexVar == 0) return false; } } There was a time in history when I used to write code for a single exit point. The flow of control would be smooth and seamless from entry to exit. ...

Three Invaluable shortcuts for type conversion in Javascript

As Javascript developers we dream in type. Here are three quick and easy ways to convert from one type to the other in your Javascript code. Well, just kidding about the whole dream part. Most of us don’t quite care about types as much as we should. Anyhow, here are three quick ways to convert types - Convert to number Use +. console.log(+1); // 1 console.log(+"1"); // 1 console.log(+"a"); // NaN console.log(+true); // 1 console.log(+null); // 0 console.log(+undefined); // NaN console.log(+0); // 0 Convert to string Use ''+ or ''.concat(). ...

Memoized Factorial Function in Javascript

Get factorial of a given number using memoization techniques. Previously we have seen how memoization can be used in a reusable function to get all the advantages of memoization, without the complexity. Today, let us see one more practical example - get factorial of a given number. First, create a function to calculate factorial. let factorial = function(n) { return n <= 1 ? 1 : n * factorial(n - 1); }; console.log(factorial(5)); // 120. works! Then, wrap the factorial function in memoThis. let memoThis = function(func) { const cache = {}; return (...args) => { const key = JSON.stringify(args); return key in cache ? cache[key] : (cache[key] = func(...args)); }; }; let factorial = memoThis(function(n) { return n <= 1 ? 1 : n * factorial(n - 1); }); console.log(factorial(5)); // 120

With statement in Javascript

Avoid having to type your object notation multiple times using with statement. Consider the below code - const earth = { name: "earth", satellite: "moon", position: 3 }; console.log("name:", earth["name"]); console.log("satellite:", earth["satellite"]); console.log("position:", earth["position"]); /* output name: earth satellite: moon position: 3 */ Typing “earth” everywhere can be quite laborious. This is more prominent when you are retrieving a big JSON from somewhere and trying to insert specific values in different parts of the page. Ergo, this shortcut - const earth = { name: "earth", satellite: "moon", position: 3 }; with (earth) { console.log("name:", name); console.log("satellite:", satellite); console.log("position:", position); } /* output name: earth satellite: moon position: 3 */ with can also be nested. ...

Prototype and property naming conflicts - shadowing issues in Javascript

Be wary of prototype naming that can cause potential conflicts with one of the named objects. I have talked about using a non-emumerable property when defining a prototype, but what will happen if your prototype name conflicts with a prop name? You will loose quite a bit of hair - that’s what happens. Object.prototype.color = () => { return "blue"; }; let apple = { name: "apple", color: "red" }; console.log("invoke color function ", apple.color()); // TypeError: apple.color is not a function console.log("invoke color function ", apple.color); // red I don’t know of any way of preventing this other than “being careful”. What we end up doing is to use a name space prefix if we define prototypes. By convention, name spaces are not used in the object props. ...

Git in VSCode

I have been a great admirer and user of command line tools. They reduce so much time and energy while getting things done. But, on the other hand I have not been a reasonably good user of Git by itself. I could never come to terms with typing in one too many statements to get to where I was going. For example - Compare changes with previous version Check who did changes in a specific version Revert to previous version Check changes to stage / commit, and periodically commit These and many more require far too many commands. These commands were sometimes coded in batch files and copied/pasted whenever I needed them. I just could not remember everything - probably not as good a user of Git as I would like to believe. ...

Watch a specific prop of an object

How do you watch a specific prop of an object? Is it useful at all? Watch is invaluable. It allows us to react to changes in the state and keep it that way through the life cycle of the component. Creating a watch is pretty simple. Consider the below example where we are monitoring the search text to respond to changes. You may observe that we simply do not respond to changes, but debounce it - i.e., wait for 1000ms and trigger off a request only if there was no user input within the 1000ms. ...