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

Replacing console logs with debugger; and using conditional breakpoints

If you are like me and still slipping back to the nasty habit of using too much the console.log(); statements for debugging in Javascript this video was of real help.

Something did not feel natural for me to go in the devtools, find the troublesome block of code and add there a breakpoint.

Being in the code editor all the time, was much more easy just to drop a few console.log() statements in there. More easy yes, but for sure not more productive.

But it turns out that if you drop a debugger; statement (min 1.20 in the video) it triggers the breakpoint with full access to the debugging tools.

javascript debuger statement

Another cool trick in the video is are the usage of the conditional breakpoints (min 3.00) from the dev tools.

But you can use this that also with the debugger; as well:

for (let counter = 1; counter < 10; counter++) {
    // more complex code here
    if (foo === 5) {
        // activate the brekpoint only  when foo is 5
        debugger; 
    }
}

So, welcome debugger and bye-bye console.log().

Tagged template literals in Javascript

In ES6 the templated literals were added in Javascript. They are used to interpolate values in a string.

const name = 'Tom'
const age = 20;
const myString = `The name is ${name} and the age is ${age}.`;
/* 
myString is now "The name is Tom and the age is 20."
before  ES6 the templated literals we had to write:
myString = "The name is " + name + " and the age is " + age "."
*/

So, this made things a bit more elegant when concatenating strings.

But we can do more than this. We can define tagged template literals. Basically, they are a combination of a tag function and a string template literal. What's returned from the tag function will determine the final format of the string.

Let's say we want to show a string like this one in the below picture.

The basic string literal will just alow use to write this:

const text = `${p.name} is ${p.age} years old.`;

However, with the tagged template literals we can say:

const text = setHighlightTags `${p.name} is ${p.age} years old.`;

We can name the tag function however we want. In our example the setHighlightTags is defined as:

function setHighlightTags(strings, ...values) {
   let str = '';
   strings.forEach((string, i) => {
       str += string;
       if(values[i]) 
          str += `<span class='hl'>${values[i]} </span>`;
   });
   return str;
}

And the .hl CSS class has just some simple rules:

.hl {
    background-color: yellow;
    padding: 2px 10px;
}

And that's pretty much all we need. We can get more creative when we need it. There are libraries, like styled-components (React) or chalk (for colorful logs) that take this feature to the next level.

If you want you can read more about it here. Also, check out below the full codepen for this example:

See the Pen
tagged-template-literals
by JS Craft (@js-craft)
on CodePen.

6 things I didn’t know you can do in Javascript

The fact that JavaScript is such a flexible language makes it maybe the easiest language to start with and the hardest to master. I’ve been working with JavaScript for more than 10 years now and I still stumble upon some hidden syntax or tricks that I never knew existed.

So let's see some JS mysteries that I've recently discovered.

1. There is a function constructor. You will give it the parameters and the body of the function and it will return back the actual function :

const diff = new Function('a', 'b', 'return a - b');
diff(20,13) // 7

2. We have a with statement in Javascript. It takes as a parameter an object and binds the properties of that object to the scope of the contained code block.

const book = {
    author: 'Ernest Hemingway',
    title: 'The Sun Also Rises'
}
with(book) {
    console.log(author); // Ernest Hemingway
    console.log(title); // The Sun Also Rises
}

3. we can use the + operator to convert a string to a number. No more the need to use functions like parseInt() or parseFloat(), unless you want to parse to that specific numerical type.

const nr = +'1.5';
nr + 1; // 2.5

4. we can assign properties to functions. We can make configurable functions by assigning specific properties to that function.

function sayHello() {
    if (sayHello.country = 'US') {
        return alert('Hi there!');
    }
    if (sayHello.country = 'FR') {
        return alert('Bonjour !');
    }
    if (sayHello.country = 'GR') {
            return alert('Guten Tag !');
        }
    return alert('Hi');
}
sayHello.country =  'FR';
sayHello(); // alert('Bonjour !');

Also, we can use these function properties as counters or "static variables".

5. we can use the arguments.callee.caller to see what function invoked the current function. The arguments var is a default of any js function. But we have the arguments.callee.caller that will tell us who called that function. Something like a console.trace() but just one level deep.

function sayHello() {
    alert(arguments.callee.caller); //start
}

function start() {
    sayHello();
}()

Also the arguments.callee refers to the currently running function.

6. we have a void operator. You give it anything and it returns back undefined.

void(1); // undefined
void(true); // undefined
void(false); // undefined
void({}); // undefined

You may ask yourself why you would want an operator like this one? Well because before ES5 you could actually assign a new value to the original undefined:

undefined = "abc";
x = undefined;
alert(x); // "abc"
// this will not work anymore
// but it explains why we have the void operator 

So ... Javascript the language where surprises never end!

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: