Checkout my Getting Started with React video course on Skillshare. It is 100% free.

Using computed property names with console.log

Let's say we have the following code:

const tom = { name: 'Tom', colour: 'blue and white' }
const pib = { name: 'Puss in Boots', colour: 'orange'}
const syl = { name: 'Sylvester', colour: 'blue and white' }

console.log(tom) // { name: 'Tom', colour: 'blue and white' }
console.log(pib) //  { name: 'Puss in Boots', colour: 'orange'}
console.log(syl) // { name: 'Sylvester', colour: 'blue and white' }

By using the computed property names in Javascript we can have all the console.log statements combined into just one line.

console.log({ tom, pib, syl }) // {tom: {…}, pib: {…}, syl: {…}}

Quite a useful trick for when you want to console.log the full context of a piece of code.

Here and here you can find two more articles with tips when using the js console.

Video – Using XHR breakpoints to intercept HTTP calls in Chrome Devtools

Last week I've found myself in a tricky caching situation where I could not say exactly was happening with an Ajax call.

Mike Sherov was kind enough to show me how we can use the Google Chrome Devtools to pause any Javascript execution when an HTTP call is made and point to where that call was made from.

I made a short video about it. Hope you like it.

By the way, check Mike's courses on egghead about Web Security Essentials and JavaScript ES2019 in Practice. They are super good!

Beyond console.log() – 3 Console methods you can use for better Javascript debugging

We can enhance our Javascript debugging experience using a set of less known features of the Console utility.

1. Using CSS with console.log

You can style your console log messages. You need to add the %c flag alongside a second parameter containing the actual CSS styles. For example:

console.log("%cA green message", "background-color: green; padding: 5px; color: white");

will output the following:

2. Using console.table() and console.dir() to print objects.

The plain console.log() is meant to print single lines. However, if you want to print objects console.table() and console.dir() are a better fit.

For example, if we have the following objects:

const firstChar = {name: "Han Solo", age: 35};
const secondChar = {name: "Chewbacca", age: 190};

The console.table(firstChar) will give the following nice formatted output:

And we can use table also with an array of objects.

console.table([firstChar, secondChar]);

Will output:

3. Adding new flavors: console.warn() and console.error()

And maybe the easiest commands to add to your toolbelt are the different levels of errors in showing up a message:

console.log("a simple log"); // no alter
console.warn("pay attention!"); // yellow alert 
console.error("a serious error !!!"); // red alert

This will output:

Disclaimer: when it comes to finding what is wrong with your Javascript code, please keep in mind that in the vast majority of cases it's faster to use tools like the javascript debugger from Google Chrome DevTools or Firefox instead of the plain old console.log.

Javascript – using default values for function parameters and when destructuring

I still find myself writing code like the one below:

function myFunction(name) {
    if (typeof name !== 'undefined') {
            name = "unknown person";
    }
}

Even if with the ES6 default values for paramters the code can be made just into this:

function myFunction(name = "unknown person") {
    // code here
}

And we can have the default values even when using the destructuring statements.

Let's say that we have:

const myName = {
    first: "Js",
    last: "Craft",
};
const { prefix, first, last } = myName; 
console.log(prefix + " " + first + " " + last);
// will output: undefined Js Craft
// because prefix is not set in the myName obj

But, if we define default values for the destructed properties:

const myName = {
    first: "Js",
    last: "Craft",
};
const { prefix = "Mr", first, last } = myName; 
console.log(prefix + " " + first + " " + last);
// it will output: Mr Js Craft

So, keep calm and use default values!

Vue.js and GraphQl – the documentaries

I've been having these two videos saved in my bookmarks for quite some time now. And being looked in the house for the full day(s) it was time to give them a go.

There are two documentaries: one about Vue.js and it's creator Evan You, and the other about GraphQl.

And boy I was in for a treat. They are SUPER good.

Both the quality of video and the production made me feel like I was watching a documentary done by something like Netflix. But with and for developers :))

So if you are curious to find out more about the story and the people behind some of the tools that we are using daily give them a try:

Throttling VS Debouncing in Javascript

A few days ago I've written a short article about debouncing in Javascript.

Another term very related to debouncing is throttling. Both techniques do the same thing: they make sure expensive operations (like API calls) are limited in a time interval.

But, in different ways:

  • throttling makes sure that one function is not called more than once in X milliseconds
  • meanwhile debouncing makes sure that a function is executed only if it was not called again for the past X milliseconds; basically with debouncing we make sure a function is called only once, even if it was involved multiple times.

A simple implementation for a throttling function may look like this:

function throttle(f, t) {
    return function (args) {
         let previousCall = this.lastCall;
        this.lastCall = Date.now();
            if (previousCall === undefined || (this.lastCall - previousCall) > t) { 
                f(args);
            }
     }
}

You can see in the other tutorial the implementation for the debouncing function.

For example, if we have a user is pressing a button every 500 milliseconds for 6 seconds:

  • with a throttling interval of 2 seconds, the call for the button will take place 3 times.
  • with a debouncing time of 500 milliseconds, then after 6 seconds, the call for the button only takes place just once

Also if you want to read more I have found useful the following links:

What is debouncing in Javascript

On the UI some user actions are expensive.

For example, a search operation can be expensive if we do it for every keypress. If the user types a word with 6 characters, and we search at every keyup event then we will have 6 API calls in a very short interval.

The fix would be to make the actual search only after the user had finished typing the search term. In other words, make the API call one second later after no key was pressed anymore for one second.

And this is were debouncing comes into play.

Debouncing makes sure that a function is not called again until a certain amount of time has passed without it being called.

For example, if the user is typing javascript we should search just for the jull word and not for:

  • j
  • ja
  • jav ...

Here is how one simple implementation of a debouncing function may look like:

function debounce(callback, time) {
    let interval;
    return () => {
        clearTimeout(interval)
        interval = setTimeout(() => {
                interval = null
                callback(arguments)
            }, time)
    }
}

Besides searching debouncing can be used with other expensive operations such as resizing a window, scrolling or autocomplete a text input based on an API call.

You can find here the full working example.

The double negation !! in Javascript

While working on a bug I have stumbled upon the following piece of code.

return !!(this.isFirstOverall() || this.get('videoId'));

I was super sure it is a mistake, and that was the root of the bug. It did not make any sense to negate a negation.

But after a bit of googleing I have found that there is such a thing as dobule negation in Javascript.

Long story short, its purpose is to convert any expression to an actual true/false boolean value.It is like having Boolean( insert_value_here.).

Take for example the follwoing expression:

const isIE8 = navigator.userAgent.match(/MSIE 8.0/);  
console.log(isIE8);

This will log either an Array or null. And yes, we can evaluate null as being false. Actually, null is a falsely value to be more precise.

But, if we double negate this:

const isIE8 = !!navigator.userAgent.match(/MSIE 8.0/);  
console.log(isIE8);

An actual true/false boolean value will be outputed.

The double negation !! is not an actual operator, like && or ||. It is just a sequence of two negation ! signs.

The first negation converts the data (whatever it data type it may be) to a boolean, but with the opposite value. The second negation changes the boolean again to give the actual result.

// example - the long version
const x = {}; // truthy
const y = !x; // false
const z = !y; // true 

// or by using the double negation
const x = {}; // truthy
const z = !!x; // true

Advantages and disadvantages of using the !! double negation in Javascript

Well, it depends on what do you want to make more clear. For sure the actual code will look strange to someone (like me 😅) who does not know about this double negation trick.

On the other side, it will provide more clear value for the actual evaluation. The result will be just true or false. For example, you will not have to wonder anymore if an empty object is considered true or false.


const result = {};
if(result) {
    // make something
}

JS Interview question: removing duplicates from an array

I was making a list of common interview questions for junior front-end developers. One common question that pops up quite often is how to remove duplicates from a JavaScript array.

Let's say we have to the following array:

const withDuplicates = ["dog", "cat", "dog", "cow", "dog", "cat"]

To keep just the unique values we will have:

const uniqueValues = [...new Set(withDuplicates)]
// it will return ["dog", "cat", "cow"]

Bam, that's all! Just one line!

It works as well with numeric values but does not work with objects.

The Set is a Javascript data structure and its main purpose is to be a container for data that can’t be repeated.

By initializing a Set with a destructured array (the ... operator before new Set()), we pass the actual values the Set will automatically remove the duplicates. Finally, we convert it back to an array by wrapping it into square brackets.

The Set was added in 2015 by the ES6 version of Javascript.

The old complex solution without using the ES6 Set

Before having Sets in Javascript we had to do this manually with a code similar to this one:


function remove_duplicates(arr) {
    var obj = {};
    var ret_arr = [];
    for (var i = 0; i < arr.length; i++) {
        obj[arr[i]] = true;
    }
    for (var key in obj) {
        ret_arr.push(key);
    }
    return ret_arr;
}