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

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:

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
}