Javascript, Journey, React

Before you dive into React learn a few more Javascript items.

Working on react these past few weeks I have to warn you that before you move on to the React make sure you are comfortable working with the following concepts. The reason I am saying this is because I learned this the hard way. I knew Javascript or so I thought. I knew V5 of Javascript but in there have been some changes in Javascript that React has adopted and it helps to understand and be familiar with them. Otherwise you will try to learn ES2015, ES2016, and React all at the same time.

So take it from me take a few extra hours, days or however long it takes you to learn these concepts:

  • Const and Let
  • Promises
  • Arrow Functions
  • Spread Operator
  • Object Spread
  • Super keyword

I wrote down some basics on these concepts to help you out, but it might not be enough to truly understand it. I have suggested other resources that might help. 

Const and Let

They are new keywords and can be used as an alternative to the var keyword to declare variables.

const allows us to declare constants or values that cannot be redeclared.

When we do

 var studentName = “Claudia”;

We can down the line change it by doing

studentName = “Eddie”

and everything is fine and the variable has a new assignment.

However if we do

const student2Name = “Mary”

and we try to reassign it

student2Name = “Sam”

we are going to get an error something along the lines of TypeError:  Assignment to constant variable

The only exception to this is if we use const to declare an array or object. In this case we are allowed to push items to the array and change the value of the object.

You are not able to change the value of a primitive. You can mutate if it is an object but not declare again. 

Let

let is a bit more complicated to understand but let’s try to make sense of how it works and why.

`let`, is a keyword where the variable may be reassigned, such as a counter in a loop. It also signals that the variable will be used only in the block it’s defined in, which is not always the entire containing function.

`var` When you define a variable in JavaScript. The variable may or may not be reassigned, and the variable may or may not be used for an entire function, or just for the purpose of a block or loop.

Let’s see an example to understand in a better way:

Var

function example1() {
     console.log(a);
     var a = 1;
 }

example();

If we run this you might expect it to say error, but instead it will run and it will say it’s undefined. The reason is that javascript does what is called as hoisting. What hoisting does is that it takes the declaration of “a” but will not assign 1 to it until it reaches the 2nd line in the function. But we already logged it.

Let

‘use strict’;
function example2() {
     console.log(a);
     let a = 1;
 }

example2();

You can’t use ‘let’ without ‘use strict’;, it throws error.

Now, the code will throw a `ReferenceError`, because `let` makes sure that the variable `a` is visible only after decalaring a.

Just like var, let also hoists up but we cannot access the variable outside the block in which it was declared.

Promises

A new constructor function that helps us manage asynchronous code.

Asynchronous Code?

Code that happens in parallel and separately to the main application. When the work on the side projects/request is complete it will notify the main application. If it worked on one piece at a time it would be called synchronous.

What is a promise?

A one time guaranteed return of some future value. We create a placeholder for the output of an asynchronous operation that we don’t know what it will be or when it will be done executing.

When the operation is done executing the promise is either resolved (also known as fulfilled) or rejected.

Example of a Promise

You go to the dry cleaners and you give them your clothes and a description of what to do.

The dry cleaners gives you a tag and a promise to complete the work.

You leave with the promise and they take more items from other customers.

A few days later you either get your clothes cleaned or they got destroyed by the machine.

In order to get some more clothes cleaned you have to request a new job, it won’t and can’t be the same job as before.

How do we use it?

  • We use the new keyword
  • It accepts a callback function which contains two parameters – they can be called anything but resolve and reject are the most common.
  • These parameters are functions that are to be run if the promise is resolved or rejected.
// promise syntax look like this
new Promise(function (resolve, reject) { ... } );

This blog post by Jecelyn Yeen titled Javascript Promises for Dummies has a really good example of code to use promises.

Arrow Function

A new syntax for writing function in ES2015. It saves some keystrokes instead of typing out the word “function” we use an arrow =>

The old way of writing a function

var add = function(x, y) {
   return (x + y);
}

The arrow way of writing the function

var add = (x,y) => {
     return (x + y);
}

You might be asking yourself well what is the big deal, it looks exactly the same minus 8 letters and I really don’t want to do things differently to save from typing 8 letters.

Well there is a bit more positive news to arrow functions like:

  • The whole function can be put on one line and we can get rid of the word return and the curly braces like this
    • var add = (x,y) => x + y;
  • Just remember that this is only valid for one line functions.

Arrow functions work great with the new ES2015 array methods like map.

Previous way of writing a map method function

let arr=[1,2,3]

arr.map(function(value) {
      return value + 2;
});

//Should return [2, 4, 5]

Now with arrow functions we write

arr.map(value => value + 2);

this is so much shorter and easier to read.

Look at this function and try to understand it and figure it out.

function guessWhatThisDoes(arr) {
     return arr.map(function(value) {
          return value * 3;
     }).filter(function(value) {
          return value % 4 === 0;
     })
};

guessWhatThisDoes([2, 4, 6, 8]); Should return [12, 24]

now look at it with arrow functions

var guessWhatThisDoes = arr => arr.map(val => val * 3).filter( num => num % 4 === 0);

Notice how if there is only one parameter there is no need to have parenthesis around it.

There are some things to be weary with arrow functions.

Arrow functions are not the same as regular functions. Some exceptions are

  • Arrow functions do not get their own “this” keyword.
  • Inside of an arrow function the word “this” has a different meaning. This is whatever value of the keyword “this” would be immediately outside of the arrow function.

SitePoint has a good article explaining the use of this with arrow function.

I split this article up into two for an easier read.

Here is part 2

1 thought on “Before you dive into React learn a few more Javascript items.”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s