Codementor Events

What To Know In JavaScript To Get Started In React

Published Jul 31, 2017Last updated Jan 26, 2018
What To Know In JavaScript To Get Started In React

ReactJS is a popular JavaScript library for building web applications. There is this notion that you need to know JavaScript well to use ReactJS. In fact, that is not far from the truth. To get started with building user interfaces using ReactJS, there is a minimum list of things you need to know about JavaScript.

You do need to know HTML and CSS to do any form of UI on the web.

For web designers who are already familiar with HTML and CSS and have basic knowledge of Javascript/JQuery you can start building UIs in ReactJS once you get acquainted with the list below:

  1. Using the Browser Console.
  2. Different ways of initializing a variable in JavaScript these days.
  3. Different ways of creating a function in JavaScipt today.
  4. Knowing how to make use of map and filter methods in a JavaScript array.
  5. Tenary operations in JavaScript.
  6. Debugging JavaScript applications in the browser.

I will explain each item on the list, and in a follow up post, I will proceed to apply the knowledge in building a simple ReactJS application.

1. Using the Browser Console

For someone who's just getting started with front-end web development, you can think of the browser console as an interactive shell for testing our knowledge of JavaScript.

Assuming we are using the Chrome web browser, the browser Console looks like this:

browser_console.PNG

It is a tab in the Chrome browser Developer tools (Press F12 to toggle or right click on the viewport and select inspect then select the console tab)

We will be using the browser console to experiment with some of the other points in the list.

2. Different ways of initializing a variable in Javascript Today

For some of you who are already slightly familiar with JavaScript, you'd probably know that to create a variable, you'd make use of the keyword var. it looks like this

var name = "James";

Recently, other keywords have been added, which can also be used to create a variable in JavaScript. They are const and let. To a large extent, they do the same thing with what var does, but there are some minor differences. The reason I am talking about these keywords is because they are heavily used in most ReactJS codebases and ReactJS documentation. An example from the React docs where this keyword is used in can be found here.

The most important differences we need to know are as follows

  1. We can completely replace var with let without any issues.
  2. Once we create a variable using const, we can't reassign it.

Examples of usage of these keywords
variable.PNG

3. Different ways to create a function in JavaScript

In JavaScript, to create a function, we make use of the function keyword. An example of a JavaScript function is shown below:

function addNumbers(a, v){
    return a + v;
}

This is the most common way of creating a function. We could also assign a function to a variable in JavaScript. The above function could also be implemented like this.

var addNumbers = function(a,v){
    return a + v;
}
// To use this function like the above
addNumbers(23, 44);

It works exactly the same way as the initial implementation with one caveat. When implementing a function this way, it is only accessible to implementations below the initialization. Here's an example to clarify this:

function addFourNumbers(a,b,c,d){
    return addNumbers(a,b) + addNumbers(c,d);
}
//Note we are calling the addFourNumbers function before creating the addNumbers funciton
addFourNumbers(23,24,25,26) 

function addNumbers(w,x){
    return x + w;
}

If we were to copy and paste the above snippet into our browser console, we would get the result 98
first_snippet.PNG

But if we implement it this way:

function addFourNumbers(a,b,c,d){
    return addNumbers(a,b) + addNumbers(c,d);
}

addFourNumbers(23, 24, 25, 26);
let addNumbers = function( x, y){
    return x + y;
}

We would run into an error if we copied and pasted the snippet above into the browser console. Because the addNumbers variable hasn't been defined at the point when the addFourNumbers function was called.

second_snippet.PNG

Now that we are familiar with assigning a function to a variable (the second way), there is a new syntax in JavaScript that makes this even shorter.

let addNumbers = (x,y) =>{
    return x + y;
}
addNumbers(3,5) // evaluates to 8
// If the function doesn't contain any logic and we are just returning a result. it could be simplified further

let addNumbers = (x,y) => x + y; 

addNumbers(3, 5) // 8

The above syntax is known as arrow functions and is a really convenient way of assigning a function to a variable in JavaScript.

4. Understanding the map and filter function when using JavaScript arrays.

Given a JavaScript array [1,2,3,4,5], if we wanted to create another array in which each of the elements is a square (i.e the result becomes [2,4,9,16,25]), an easy way to do this is to make use of the map method that is available to all arrays in JavaScript.

map takes a function as an argument and this function takes two parameters, the first representing the current item and the next representing the index of that item in the array. Documentation on Map

let regularArray = [1,2,3,4,5];
let squareArray = regularArray.map((item, index)=>{
    return item * item;
}) 
regularArray.length === squareArray.length // this is true;

You can think of map as a way of transforming one array into another array. At the end, both arrays have the same number of elements;

filter is also a method available to arrays in JavaScript. It is similar to map in that it also requires a function as a parameter, but the difference is that filter returns a subset of the initial array based on a condition.

So, for example, using the array [1,2,3,4,5]. If we were interested in returning just the odd numbers in the array, using filter would be a good candidate.

let regularArray = [1,2,3,4,5];
let oddArray = regularArray.filter((item,index)=>{
    return item % 2 === 1;
}
console.log(oddArray) // would return [1,3,5]

filter returns a subset of the original array based on a condition. In our example above the condition was that the modulus of each item in the array must be equal to 1.

Bear in mind that the return value of the passed function in filter must be a boolean. If it returns true, the particular item would be added to the new list. If it returns false, the item would be removed in the new list.

5. Tenary operations in Javascript

In JavaScript, conditions are implemented using both if and else statements.

var name = 50;
var amount = 0;
if(name > 25){
    amount = 50;
}else{
    amount = 10;
}

In this above example, we are setting the value of the variable amount based on the condition that if name is greater than 25, then amount would be 50, else amount would be 10 if the condition isn't met.

A simpler way to implement the above is to make use of the tenary operator in JavaScript. The pseudocode is as follows condition ? result when true : result when false
So in the above example, using the tenary operator is as follows

var name = 50;
var amount = name > 25 ? 50 : 10;

Tenary operations are heavily used in React applications especially with expressions so I thought now would be a good time to understand them.

NB: There is a difference between JavaScript statements and JavaScript expressions. A good article on JavaScript expression is located at the MDN docs

6. Debugging Javascript Applications in the browser

Assuming we created a simple html page called sample.html

<!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
  </head>
  <body>
      <script>
          var persons = [{
              name: "James",
              lastName: "AO1",
              age: 32
          },
          {
              name: "John",
              lastName: "AO2",
              age: 25
          },{
              name: "Shola",
              age: 20
          }]

          var fullNames = persons.map((person,index)=>{
              var fullname = person.name + person.country;
              return fullname
          })
          console.log(fullNames);
      </script>
  </body>
  </html>

If we open this sample.html page in the browser and we open the console tab, we would see the below.
third_snippet.PNG

Now, if what we wanted the result to be was ["James AO1", "John AO2", "Shola"], from our result, we can see that we are clearly doing something wrong in the map implementation. To be able to debug our application, we have two options,

  1. Go to the Sources tab on our browser dev tool and add a breakpoint on the part of our code that we want to pause. To add a breakpoint, click the rightbar until a blue icon displays. This blue icon is toggleable.

forth_snippet.PNG

  1. In our text editor when editing the sample.html, add a debugger; statement to point where we want to pause execution.

fifth_snippet.PNG

If we were to refresh our browser, we would observe the following in either case with our developer tools open.

sixth_snippet.PNG

We can see that the browser pauses execution of our HTML file ā€“ at the point of the breakpoint, we can actually evaluate the values of the variables.

While the breakpoint is active, we can move back to the console tab and confirm that we have access to all the variables/functions before the breakpoint.

seventh.PNG

Going back to the Sources tab, we can step to the next line by clicking on the step button on the right side of the developer tools.

eight.PNG

If you observed the highlighted section in the image above, you can see the controls. We can also see that the result of fullname was evaluated and we can pinpoint the root cause of our problem.

To find out more about debugging JavaScript applications on Chrome, visit the Chrome Devtools Documentation for more info.

In the next post, we will apply all these knowledge in building actual user interfaces using ReactJS.

Till then, thanks for reading.

Discover and read more posts from Oyeniyi Abiola
get started
post comments2Replies
Omebe Johnbosco
7 years ago

A nice article .

Abraham Kalili
7 years ago

Check, Check, and Check, looks like Iā€™m ready. Thanks for this piece