Get Started on Svelte

The typical Javascript frameworks love playing the middleman. They continue playing that role at development and at run time. Svelte is not your typical middleman - instead the framework lays out the path during build, and completely hands over to standard Javascript at runtime. If that does not pick your interest - I don’t know what will 😜. This is the dev cycle cycle for a typical framework - Create your application using a template provided by framework Create application using the excellent toolset provided by framework. The development is almost magical - use components for max reuse, and test/debug your code easily and quickly Package everything without fuss. The build scripts will include a lot of framework code + your own code Deploy build to your web server and reach nirvana While frameworks do an excellent job of running applications, they sit on top of Javascript and web standards to deliver that experience. ...

Null check gotchas

Beware of these null check gotchas. Consider this code - const sum = null; if (sum) { console.log("valid sum"); } // nothing printed The above code shows expected behaviour. Nothing is printed since if(sum) returns false. Now, try the code below. if (sum >= 0) { console.log("valid zero or positive sum"); } // valid zero or positive sum It can throw off your calculations by a wide margin. Strange but true null >= 0. But, null > 0 and null == 0 both return false. ...

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 - ...

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. ...

Finally block has the final say

Finally overrides any return statement from the try/catch. We write try/catch/finally for error handling in Javascript - function tryTryTry() { try { return 4; } catch (e) { console.log(e); } finally { return 42; } } console.log(tryTryTry()); //42 The function returns 42 and not 4. Why? Because finally always gets executed - both for the normal execution flow and errors. In the above code block - try returns 4 control flow jumps to finally block finally returns 42 caller gets 42