{{announcement.body}}
{{announcement.title}}

10 JavaScript Things New React Devs Need to Know

DZone 's Guide to

10 JavaScript Things New React Devs Need to Know

In this article, take a look at ten JavaScript things that developers need to know.

· Web Dev Zone ·
Free Resource

I recently worked with a group of volunteer developers to start moving our RICOH THETA Developer community web sites into an integrated React web application. The experience was wonderful. We were able to quickly tap into REST API data sources with React and build an interface to our fun dev community that gets roughly 1 million views a year. Most of us were new to React when the project started. Although I had fun, it would have been more fun had I spent an extra 20 minutes brushing up on modern JavaScript before I started reading React code examples.

I'll explain the 10 JavaScript things we wished we studied just a little bit more before we started coding the site in React by grabbing online code examples.

Our new React site is still in the community feedback phase, but you can see the current concept here. The site consists of three primary React components, each pulling data from a different REST API. The backend data sources are a combination of APIs from our Discourse forum, Django Rest Framework holding our list of apps in PostgreSQL, and our custom document server. 

The bottom line is that the component architecture of React is so awesome that we were able to get something up in a few days and use the site itself to solicit feedback on the design instead of a long-drawn-out process of mockups and discussion. 

You might also be interested in: Functional Programming Using JavaScript

Absorb the 10 tips below and get started on your first React project today. 


1. Fat Arrow

Fat arrows are used as function shortcuts. Instead of writing function() , you can omit the function keyword and write  () => . You can omit the return statement and the curly brackets if you return only line, () => "long string" .  

You can assign the function to a constant: const MyExport = () => { code goes here }.

2. Template Literals

There are three ways to specify strings in JavaScript.

  1. Double quote  "string" 
  2. Single quote  'string' 
  3. Back-tick  `string` 

The back-tick string comes with special powers.

You can insert variables into the string.

JavaScript
 




x


1
const name = "Scoopy Doo";
2
const description = "a cartoon dog"
3
 
          
4
console.log(`${name} is ${description}.` );



Another fun back-tick feature is that the string can span multiple lines.

JavaScript
 




xxxxxxxxxx
1


1
console.log(`The
2
sky
3
is
4
blue`);



Run and edit code snippets.

3. Import and Export

You can import code from one file into another.

 import { MyExport } from "./MyExport.js";  

In this example, I am importing MyExport.js into App.js

This code example is available here.

To import the contents of a file, you must export it. The example below shows use of a fat arrow function, template literal, and the new export feature.

JavaScript
 




xxxxxxxxxx
1


 
1
export const MyExport = () => {
2
  const name = "Mickey";
3
  const type = "cartoon character";
4
  const description = "icon of the Walt Disney entertainment empire";
5
  return `${name} is a ${type} and a ${description}`;
6
};



Back in my  App.js  file, I can now use the function that I exported from  MyExport.js .

JavaScript
 




xxxxxxxxxx
1


 
1
import { MyExport } from "./MyExport.js";
2
 
          
3
export default function App() {
4
  console.log(MyExport());
5
  return "";
6
}



The  console.log  output is shown below. 


4. Destructuring

You can destructure objects or arrays with this syntax.

 const {userId, title} = json 

To illustrate this example, let's first pull a JSON entry from the fake JSON test server, jsonplaceholder.

JavaScript
 




xxxxxxxxxx
1


1
const fetch = require('node-fetch');
2
 
          
3
console.log("get a single JSON entry for testing");
4
fetch('https://jsonplaceholder.typicode.com/todos/1')
5
  .then(response => response.json())
6
  .then(json => {
7
    console.log(json)
8
    })



I can now work with this single JSON entry.

JavaScript
 




xxxxxxxxxx
1


 
1
{ userId: 1,
2
  id: 1,
3
  title: 'delectus aut autem',
4
  completed: false }



The JSON entry is held in the variable called,  json .

I can now pull the  userId  and  title  out by enclosing these keys in curly brackets.  {userId, title}.

JavaScript
 




xxxxxxxxxx
1


 
1
console.log("starting deconstruction of object")
2
fetch('https://jsonplaceholder.typicode.com/todos/1')
3
  .then(response => response.json())
4
  .then(json => {
5
    const {userId, title} = json
6
    console.log(`the userId is ${userId}`);
7
    console.log(`the title is ${title}`);
8
    })



The console will show the following:


Run the example  here.

5. Map

You will use the array map method constantly. Master it. This works like a forEach loop.

Code examples are available here

JavaScript
 




xxxxxxxxxx
1


 
1
myArray = [1,2,3,4];
2
 
          
3
// square each element of array
4
console.log(myArray.map(element => element * element));



The result is: 

  [ 1, 4, 9, 16 ] 

This example uses the fat arrow function. This allows us to eliminate the curly brackets and return statement. The code loops through each element of the array and holds each value in the variable  element 

You can add a string to the variable. 

 console.log(myArray.map(element => "My number is " + element)); 

You can get the index of the array by adding a second parameter.

 console.log(myArray.map((element, index) => `At index ${index} the number is ${element} `));

 

6. Filter

Using the same array, you can filter the output for conditions.

 console.log (myArray.filter(element => element > 3)); 

Filter returns an array. In this example, the array is only a single element, [4].

7. Find

Find is similar to filter but does not return an array. It will only return the first element that meets the condition and then exits.

 console.log(myArray.find(element => element === 3)); 

This code returns a single number, 3 .

8. Reduce

This is the most difficult to understand of the array methods.

It works like a loop that has an outside global variable that keeps the contents of a mathematical operation applied to each element of the array.

The classic example is to add all the elements of an array together and return a single number.

JavaScript
 




xxxxxxxxxx
1


1
console.log("use reduce to sum array and produce single result");
2
console.log(myArray.reduce((total, current) => total + current));



This returns 10.  The variable total starts at 0. 

  1. total = 0, current = 1 (first element of array)
  2. add 0 + 1.  Now total is 1.
  3. loop through array
  4. total = 1, current = 2 (second element of array)
  5. add 1 + 2. Now total is 3
  6. loop 
  7. total = 3, current = 3 (third element of array)
  8. add 3 + 3.  Now total is 6
  9. loop
  10. total = 6, current = 4 (fourth element of array)
  11. add 6 + 4. Now total is 10 - This is the answer!

You can start the total or accumulator at any value. The code below starts the accumulator at 100.

 console.log(myArray.reduce((total, current) => total + current, 100)); 

The result is 110.

The code for all the array exercises is available here.

9. Ternary Operator

The ternary operator looks weird.

 console.log(activeUser ? "Welcome" : "Please sign in");   

It functions like an if-then-else statement.

The variable to the left of the question mark  ?  is a boolean true/false variable. The string "Welcome" is shown if activeUser is true.  If activeUser is false, then the string after the colon   is shown - "Please sign in" is shown.  This code will log "Welcome"

JavaScript
 




xxxxxxxxxx
1


1
const activeUser = true
2
console.log(activeUser ? "Welcome" : "Please sign in"); 



This code will log "Please sign in".

JavaScript
 




xxxxxxxxxx
1


 
1
const activeUser = false
2
console.log(activeUser ? "Welcome" : "Please sign in"); 



Despite the weird looks, the concept of the ternary operator is easy to understand if you think of it as a shortcut for an if-then-else statement.

10. Async and Await

I find the syntax of async and await easier to understand compared to promises.

In my earlier point on deconstruction, I used a promise.

JavaScript
 




xxxxxxxxxx
1


 
1
const fetch = require('node-fetch');
2
 
          
3
console.log("get a single JSON entry for testing");
4
fetch('https://jsonplaceholder.typicode.com/todos/1')
5
  .then(response => response.json())
6
  .then(json => {
7
    console.log(json)
8
    })



Although the functionality of promise and the async function with await are the same, the promise can be written with async and await to clearly show what your code is waiting for.  In this example, the code must first wait for the response data to arrive from the Internet.  It then needs to wait for the response to be converted into JSON.  The code example below is available here

JavaScript
 




xxxxxxxxxx
1
11


1
const fetch = require('node-fetch');
2
 
          
3
async function getUsers() {
4
    const response = await fetch('https://jsonplaceholder.typicode.com/users');
5
    const data = await response.json();
6
    return data;
7
}
8
 
          
9
getUsers()
10
    .then(data => {
11
        console.log(data.find(entry => entry.website === 'conrad.com')) });



Summary

React is a wonderful framework to use for development. It can help make JavaScript fun again.  The development system integrates Babel behind the scenes, allowing us to use new JavaScript features that makes JavaScript easier to use once we learn the new syntax. Beginners to React might feel intimidated reading the many code examples or tutorials available for React if they aren't familiar with the new features of JavaScript.  Learning JavaScript language fundamentals before diving into React will allow you to focus on the cool and exciting component architecture of React that enables you to build beautifully designed applications quickly.  

Further Reading

How JavaScript Actually Works: Part 1

Guide to New JavaScript Features Introduced at Google I/O 2019

Topics:
javascript ,react ,web dev ,react developer ,react tips

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}