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

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;
}

The 10 min ES6 course for the beginner React Developer

The famous 80–20 Pareto principle is also true when it comes to the learning React & ES6 relationship. ES6 came with more that 75 new features, but from what I’ve seen, I found myself needing less than 20% of them in more that 80% of the cases.

note : just to avoid any confusions and without going into very geeky stuff JavaScript is the same thing as ECMAScript (or ES). ES6 = ES5 + some new features, so both ES6 and ES5 are Javascript. The main difference lies in the set of supported features.

For me it was quite confusing two years ago when I first moved from good old Angular 1, and “pure” ES5 Javascript, to React and seeing in some tutorials things like arrow functions or destructor statements. It was not clear, what was from React and what from ES6.

Actually, for the first week or so, I was almost sure that you could write something like {name} only in React.

Not even by far this is intended to be a complete run-through of all of the new features. It is only the “stuff” from ES6 that I’ve seen used in the vast majority on the React code. So … here we go:

Let and const

In the “old” Javascript (meaning ES5), to declare a variable we were using the keyword var. Given some black magic thing called Javascript hoisting we could use a variable before declaring it.

// ES5
console.log(myVar); // prints out undefined
var myVar = 10;

This can lead to some behavior. Not anymore. In ES6, via the let or const keywords you must explicitly declare something before using it.

// ES6
console.log(myVar) // ReferenceError myVar is not defined
let myVar = 10

As you can imagine, the difference the between const and let is that you cannot change a const after it gets its initial value.

// ES6
let x = 10
const y = 20
x = 25 // all is ok
y = 30 // TypeError: Assignment to constant variable.

No more semicolons

From ES6 both ECMAScript 6 and all the related tools perfectly support automatic semicolon insertion. As a consequence, ECMAScript 6 coders nowadays can get rid of nearly all semicolons and remove some clutter from their code.

//ES5
var theNumber = 10;
console.log(theNumber);

//ES6 - look ma’ no semicolons
let theNumber = 10
console.log(theNumber)

Not quite a life changing feature , but for sure a nice one, especially if you had at some point a love affair with things like CoffeeScript.

Arrow functions

To make a function in ES5 you will have to write something like:

// ES5
var sum = function(a, b) {
   return a + b
}

In ES6 you can fast type it by using :

// ES6
const sum = (a, b) => {return a + b}

And , if you have a very simple one line function , you can even drop the return keyword:

// ES6
const sum = (a, b) => a + b // a one line arrow function will auto return the result of last used value

Another thing to keep in mind is that arrow functions are automatically bound to their upper scope:

function DogWorldContext() {
  this.age = 0

  setInterval(function growUp() {
    this.age++
    console.log(this.age)
  }, 1000)
}
var worldWithStandardFunction = new DogWorldContext()
// will print Nan every second, as the growUp is a standard function it has it's own this keyword context.
function DogWorldContext() {
  this.age = 0

  setInterval(()=> {
    this.age++
    console.log(this.age)
  }, 1000)
}
var worldWithArrowFunction = new DogWorldContext()
// will print 1,2,3 ... every second

The arrow functions don’t have their own this. The this context becomes the parent one, in our case the DogWorldContext.

Destructor statements

To quote from developer.mozilla.org the destructor statements makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

It is quite a common case the need to extract a attribute from a object into a separate entity. Let’s say we have the following code:

// ES5; let's say this.props.user = {name: "Daniel", age : 32}
alert(this.props.user.name + " " + this.props.user.age);

So to make it easier to read we could have something like:

// ES5; let's say this.props.user = {name: "Daniel", age : 32}
var name = this.props.user.name;
var age = this.props.user.age;
alert(name + " " + age);

But with ES6 we could use destructor statements and say:

// ES6; let's say this.props.user = {name: "Daniel", age : 32}
const {name} = this.props.user
const {age} = this.props.user
alert(name + " " + age)

Or with just one line:

// ES6; let's say this.props.user = {name: "Daniel", age : 32}
const {name, age} = this.props.user
alert(name + " " + age)

Object Literals

Somehow in the same idea we have the Object Literals. They allow us to define key-value pairs with less code.

// ES5
str = "HELLO"
number = 20
obj = {
   str: str,
   number: number
}

In E6 this can be easy translate into:

// ES6
str = "HELLO"
number = 20
obj = { str, number} // will make obj = {str: "HELLO", number: 20}

Classes, constructors and methods

We did not have class as a keyword in the “old Javascript”. So, in order to create a simple Dog class, you could make a workaround like this one:

// ES5
function Dog(name, weight){
  this.name = name;
  this.weight = weight;
}

Dog.prototype.speak = function(){
    alert("Woof, woof … my name is: " + this.name);
};

// Instantiate new objects with ‘new’
var dog = new Dog("Spike", 25);

// Invoke methods like this
dog.speak(); // alerts “Woof, woof … my name is: Spike”

You could also define a base object, and other approaches, but the bottom line was that you did not have classes “out of the box”. So meet the ES6 classes and objects:

//ES6
class Dog {
   constructor(name, weight) {
      this.name = name
      this.weight = weight
   }
   speak() {
     alert("Woof, woof … my name is: " + this.name)
   }
}
const dog = new Dog("Spike", 25)
dog.speak()

Class inheritance and React

Like in the case of Classes, in ES5 you could achieve the inheritance mechanism by doing some workarounds. But we have the extends keyword in ES6.

// ES6 
class Chihuahua extends Dog {
    shaking() {
        alert("look at me ! I’m shaking !")
    }
}

const miniDog = new Chihuahua("Mini Spike", 1)
miniDog.shaking() // I have my own methods
miniDog.speak() // but I’ve also inherited the ones from my upper classes

Also like in the case of the class keyword, extends is only a sugar syntax, but is quite useful in the React code, as it let us move from a code like this :

var Greeting = createReactClass({
  render: function() {
    return <h1>Hello, {this.props.name}</h1>;
  }
});

to a more clear version like:

class Greeting extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

Also keep in mind that if you use extends to define your React components the getInitialState() method is replaced with just a simple this.sate = … statement in the constructor of the class. You can see more about this here.

Filter

Let’s say we have the following array.

const numbers = [5,1, 20, 90, 8, 22, 33, 9]

If you would want to create a new array only with the values that are greater than 10, in ES5 circumstances you would need a for loop, or something similar (eg: see the each() from jQuery).

Well, in ES6, we can use the filter function to go through all the values from the array and keep only the ones that meet the requirements of a function.

//ES6

const notDigits = numbers.filter( function(value) {return value > 9})
console.log(notDigits) // prints out [20,90,22,33]

// or using arrow functions
const notDigits1 = numbers.filter( (value) =>  {return value > 9}
// and we can alos use the default return or the  arrow functions
const notDigits2 = numbers.filter( (value) =>   value > 9 )

.. and Map

Even if it’s from the “old” ES5, map is one of the most underused functions of Javascript. All the time you need to loop through a array , you can use map.

Let say we have the same array as in the previous example.

const numbers = [5,1, 20, 90, 8, 22, 33, 9]

If we just want to display the array just use map:

numbers.map( (n) => console.log(n))
// and you also have a second parameter, the index
numbers.map( (n, index) => console.log(n + ' is the ' + index + ' value from the array ') )
// or if we want to generate a second array by maping 
const double= numbers.map( (n) => n*2 )

You will see map(), over and over in React, all the time we will need to show a list of items:

render() {
    return(
  this.props.items.map( (item, key) =>  <p key={key}>{item}</p>
  )
} 

So, these are the most common ES6 features that I use when writing React code. Disclaimer: the list is highly biased and subjective :). In no way it was intended to diminish the usefulness of other ES6 features. As said earlier, there are many others ES6 that are not covered here, but these concepts should allow you to easily upgrade from ES5 React to the new ES6 syntax and understand what comes from React and what comes from the new ES6 features. Cheers and happy coding!

Why should you have a side project as a javascript developer

Dan Abramov completely changed his life with just 99 lines of code when he created Redux. And yes, it started out of fun as just a simple sideproject. So was the first version of Node.Js, created by Ryan Dahl. When you work on a side project, your returns are directly proportional to the value you add. The more time and effort you put in it, the more you get out.

But what can you get out of a side project? Well, quite a lot of things:

  • a great learning experience
  • a resume and a interview asset
  • last but not least: quite some fun

Sideprojects as a learning tool

Learning by doing is probably the best approach for learning React and Javascript. Opposed to the theoretical learning it allows you to get a real feel of whatever it is you’re playing around with.

One of the best strategies to learn a new framework or language is first to read and follow the tutorials or guides that usually accompanies the tool or framework. Things will work great as you have that tutorial to hold your hand at every step you make. But the real challenge starts when you start a small project by your own. In there you will meet situations that were not in the official documentation, you will start to google and dig deeper, discover new blog posts and tutorials and a new world will open before your eyes.

So the next time you learn a new framework, don't just settle for the default todo list example from the official documentation. Go deeper! For example try to build a IMDB search app, that will fetch data about your favorite movies. Having that done go for a autocomplete box, and a login mechanism. And so on. Being a self-learner is the most important skill a React developer can have.

Passing the job interview with a sideproject

Ok, we will have to admit that there are tiny changes for your side project to become a major success and you get an awesome job working full time on it. But even so it can be a great asset in your professional life.

As a junior developer there is this deadlock circle of "you will not be hired if you don't have experience" and "you can get experience only if you have a job". Sideprojects are the perfect way to break this circle. Build a side project on your own, and you will have something that will be a good substitute for the workplace experience .

Even if you are an experienced developer you still have to pass the technical interviews. But with a few sideprojects up your sleeve, you can easily slip in during a interview something like “That reminds of this thing I’ve been coding on the side”. Your interviewer will ask “what is it about?” and now the game is under your control. You know your side project probably better than any other thing you’ve worked on. And as long as the project comes off as decent and you can effectively defend your design, you’ll leave a great impression.

Also interviewers love sideprojects. They are the living proof of the two biggest assets a developer can have: passion and initiative.

So what should I do as a side project ? Since you will be spending your evenings and weekends working on this, it helps if it’s related to a topic that you are passionate about. It can be a small software application, a card game like Solitare or Blackjack or even a blog. Anything that is not a part of your day job and is out there for the world to see and use.

So go ahead, build something!