JavaScript ternary operator – shortcut to the if statement

The conditional (ternary) operator is the only JavaScript operator that takes three operands and it is frequently used as a shortcut for the if statement. // If isMember (first argument) evaluates to true, return “$2:00” (first expression), // else return “$10.00” (second expression) function getFee(isMember) { return (isMember ? “$2.00” : “$10.00”); } // Another […]

Read More…

Respond to a button click with an observable

A recipe for responding to a button click with an RxJS Observable. HTML <script> src=”https://unpkg.com/@reactivex/rxjs@5.3.0/dist/global/Rx.js”></script> <button>Click me</button> JavaScript var button = document.querySelector(‘button’); Rx.Observable.fromEvent(button, ‘click’). subscribe( (value) => console.log(value.clientX) // just for example, log the x position of the cursor ); JavaScript – Line 3 The observable is created by the operator, fromEvent, which takes an […]

Read More…

Meet IIFE – the quintessential JavaScript closure

If you want to call yourself a JavaScript bad-ass, then there is at least one little code pattern you should know by heart: the Immediately Invoked Function Expression (IIFE). This pattern defines a function that is executed immediately and it looks like this: (function () { alert(“Hello world, I’m an IIFE!”); }()); This is an […]

Read More…