Top 9+ JavaScript Concepts to Know Before Learning React

In this tutorial, we're going to take a look at some of those JavaScript concepts that you must know before learning React: JavaScript basics including the Ternary Operator, Destructuring, Spread Operator, Array methods, Arrow functions, Promises, Fetch API, Async/Await, and ES6 Modules and Import/Export.

React is one of the most popular JavaScript frameworks for building single page applications. Needless to say, as a JavaScript framework, it requires you to have a good knowledge of JavaScript concepts.

In this article, we are going to take a look at some of those JavaScript concepts that you must know before learning React. A good understanding of these topics is fundamental in building large scale React applications. So without further ado, let's get started.

  1. JavaScript Basics
  2. The Ternary Operator
  3. Destructuring
  4. The Spread operator
  5. Array methods
  6. Arrow Functions
  7. Promises
  8. The Fetch API
  9. Async/Await
  10. ES modules and Import/Export

1. JavaScript Basics

React is a JS framework and you'll be using JavaScript extensively in your React code. So, it's a no-brainer that you must be aware of the basic JavaScript concepts.

By basics, I mean things like variables, data types, operators, conditionals, arrays, functions, objects, events, and so on.

Having a proper understanding of these concepts is important for you to navigate properly in React, as you'll be using them in every step while building React applications.

So if you are unsure about these things or want to quickly revise everything again, check out some of these free courses or the freeCodeCamp JavaScript curriculum. The MDN docs and JavaScript.info are also helpful quick-search references.

2. The Ternary Operator

Ternary Operator is a short, one-line conditional operator to replace if/else. It's really useful when it comes to quickly checking a condition to render a component, updating state, or displaying some text.

Let's compare how the Ternary Operator works with the If/Else statement:

// Example of Ternary Operator
condition ? 'True' : 'False'
// Example of If/Else statement
if(condition) {
    'True'
}
else {
    'False'
}:

You can see for yourself how much cleaner and shorter using the Ternary Operator is than using If/Else.

The way it works is that you write a condition, and if the condition is true, your program will execute the statement after ?. If the condition is false, the program will execute the statement after :

Simple, isn't it?

3. Destructuring

Destructuring helps us unpack values from arrays and objects and assign them to separate variables in a simple and smooth way. Let's understand it with some code:

// With Destructuring
const objects = ['table', 'iPhone', 'apple']
const [furniture, mobile, fruit] = objects

// Without Destructuring
const furniture = objects[0]
const mobile = objects[1]
const fruit = objects[2]

In the above example, Destructuring saved us 3 lines of code and made the code cleaner. Now let's see another example of passing props in React with destructuring:

// With Destructuring Ex-1
function Fruit({apple}) {
    return (
        <div>
            This is an {apple}
        </div>
    )
}

// With Destructuring Ex-2

function Fruit(props) {
    const {apple, iphone, car} = props
    return (
        <div>
            This is an {apple}
        </div>
    )
}

// Without Destructuring
function Fruit(props) {
    return (
        <div>
            This is an {props.apple}
        </div>
    )
}

Notice how you have to use props again and again when you don't use destructuring in your props.

Destructuring makes our code cleaner and saves us from using the keyword props every time you use a prop variable. There's more to destructuring and you will learn those things when you start building apps in JavaScript and React.

4. The Spread operator

The Spread Operator was introduced to JavaScript in ES6. It takes an iterable and expands it into individual elements.

A common use case of the spread operator in React is copying the values of an object into another object during a state update to merge the properties of both objects. Look at the below syntax:

const [person, setPerson] = useState({
    id: '',
    name: '',
    age: ''
});

 setPerson([
            ...person,
            {
                id:"1",
                name: "Steve",
                age:"25"
            }
        ]);

In the above example, ...person copies all the values of the person object in the new state object which is then further replaced by other custom values with the same properties, which updates the state object.

This was one of the many use cases of the spread operator in React. As your application becomes larger, tools like the spread operator come in handy to handle data in a better and more efficient way.

5. Array methods

Array methods are very common when building a medium to large scale application in React. You will always be using some sort of array method in almost every React app you build.

So, take some time to learn these methods. Some of the methods are extremely common like map(). You use map() every time you fetch data from an external resource to display it on the UI.

There are other methods like filter, reduce, sort, includes, find, forEach, splice, concat, push and pop, shift and unshift and so on.

Some of them are common in usage, and some will come rarely in use. The key is to understand the common array methods very well, and just be aware of the existence of the other methods so that whenever you need them, you can quickly learn them.

Here's a helpful handbook on array methods and working with arrays in general in JavaScript so you can learn more.

6. Arrow Functions

Arrow functions allow us to create functions in a simple manner with shorter syntax.

// Regular Functions
function hello() {
    return 'hello'
}

// Arrow Functions
let hello = () => 'hello'

Both functions in the above code snippet work the same, but you can see that the arrow function is much cleaner and shorter. The empty () in the above syntax are for arguments. Even if there are no arguments, these brackets should be present.

However, you can skip these brackets if there is only one argument present in the function, like this:

let square = num => num * num

In one-liner arrow functions, you can skip the return statement. You can also declare a multiline arrow function by using curly braces {} similar to regular functions.

let square = num => {
    return num * num
}

7. Promises

You use promises to handle asynchronous operations in modern JavaScript. Once you create a promise in JavaScript, it can either succeed or fail – known as being resolved or rejected in JavaScript terminology.

Promises in JavaScript, in some way, can also be compared to the promises we humans make. Just like human promises are driven by the future implementation of a certain action, promises in JavaScript are about the future implementation of the code, resulting in either it being resolved or rejected.

There are 3 states of a promise:

  1. Pending – When the final result of the promise is yet to be determined.
  2. Resolved – When the promise is successfully resolved
  3. Rejected – When the promise is rejected.

Once a promise is successfully resolved or rejected, you can use a .then() or .catch() method on it.

  • The .then() method is called when a promise is either resolved or rejected. It takes 2 callback functions as arguments. The first one is executed when the promise is resolved and the result is received, and the second one is an optional argument in case the promise is rejected.
  • The .catch() method is used as an error handler and is called when the promise is rejected or has an error in execution.

Enough theory, let's end this section with an example of a promise, including the usage of the .then() and .catch() methods:

let promise = new Promise((resolve, reject) => {
  const i = "Promise";
  i === "Promise" ? resolve() : reject(); // Checkout the above Ternary Operator section to better understand the syntax
  }
);

promise.
    then(() => {
        console.log('Your promise is resolved');
    }).
    catch(() => {
        console.log('Your promise is rejected');
    });

8. The Fetch API

The Fetch API allows us to make async requests to web servers from the browser. It returns a promise every time a request is made which is then further used to retrieve the response of the request.

A basic fetch() takes one argument, the URL of the resource you want to fetch. It then returns another promise that resolves with a Response object. This Response object is the representation of the HTTP response.

So, to get the JSON content from this promise, you have to use the .json() method on the Response object. This at last will return a promise that resolves with the result of the parsed JSON data from the response body.

It might be a little confusing, so pay close attention to the example below:

fetch('http://example.com/books.json') // fetching the resource URL
  .then(response => response.json()); // calling .json() method on the promise
  .then(data => setState(data)); // updating the state with the JSON data

9. Async/Await

Async/Await functionality provides a better and cleaner way to deal with Promises. JavaScript is synchronous in nature and async/await helps us write promise-based functions in such a way as if they were synchronous by stopping the execution of further code until the promise is resolved or rejected.

To make it work, you have to first use the async keyword before declaring a function. For example, async function promise() {}. Putting async before a function means that the function will always return a promise.

Inside an async function, you can use the keyword await to suspend further execution of code until that promise is resolved or rejected. You can use await only inside of an async function.

Now, let's quickly finish off this section with an example:

async function asyncFunction() {
    let promise = new Promise(resolve => {
        resolve();
    });
    let response = await promise; // further execution will be stopped until the promise is resolved or rejected
    return console.log(response);
}

You can learn more about async and await in this in-depth guide.

10. ES modules and Import/Export

Modules were introduced in JavaScript in ES6. Each file is a module of its own. You can carry out objects, variables, arrays, functions, and so on from one file and use them in another. This is referred to as importing and exporting modules.

In React, we use the ES6 modules to create separate files for components. Each component is exported out of its module and imported to the file where it is to be rendered. Let's learn this with an example:

function Component() {
    return(
        <div>This is a component</div>
    )
}

export default Component
import Component from './Component'

function App() {
    return (
        <Component />
    )
}

In React, you have to render every component you declare in the App.js component.

In the above example, we created a component called Component and exported it with our code export default Component. Next, we go to App.js and import the Component with the following code: import Component from './Component'.

Conclusion

You've reached the end of the article! So far we have covered JavaScript basics including the Ternary Operator, Destructuring, Spread Operator, Array methods, Arrow functions, Promises, Fetch API, Async/Await, and ES6 Modules and Import/Export.

I hope you have learned a lot from this article and and understand some of the important JavaScript concepts and why you need to learn them thoroughly before jumping into React.

This article is not an alternative to learning these concepts thoroughly on your own. I have only given a general introduction to them and why are they important. Now it's up to you how you learn these things and build your knowledge from here. Best of luck with the journey!

Original article source at https://www.freecodecamp.org

#javascript #react 

What is GEEK

Buddha Community

Top 9+ JavaScript Concepts to Know Before Learning React
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Sival Alethea

Sival Alethea

1624298400

Learn JavaScript - Full Course for Beginners. DO NOT MISS!!!

This complete 134-part JavaScript tutorial for beginners will teach you everything you need to know to get started with the JavaScript programming language.
⭐️Course Contents⭐️
0:00:00 Introduction
0:01:24 Running JavaScript
0:04:23 Comment Your Code
0:05:56 Declare Variables
0:06:15 Storing Values with the Assignment Operator
0:11:31 Initializing Variables with the Assignment Operator
0:11:58 Uninitialized Variables
0:12:40 Case Sensitivity in Variables
0:14:05 Add Two Numbers
0:14:34 Subtract One Number from Another
0:14:52 Multiply Two Numbers
0:15:12 Dividing Numbers
0:15:30 Increment
0:15:58 Decrement
0:16:22 Decimal Numbers
0:16:48 Multiply Two Decimals
0:17:18 Divide Decimals
0:17:33 Finding a Remainder
0:18:22 Augmented Addition
0:19:22 Augmented Subtraction
0:20:18 Augmented Multiplication
0:20:51 Augmented Division
0:21:19 Declare String Variables
0:22:01 Escaping Literal Quotes
0:23:44 Quoting Strings with Single Quotes
0:25:18 Escape Sequences
0:26:46 Plus Operator
0:27:49 Plus Equals Operator
0:29:01 Constructing Strings with Variables
0:30:14 Appending Variables to Strings
0:31:11 Length of a String
0:32:01 Bracket Notation
0:33:27 Understand String Immutability
0:34:23 Find the Nth Character
0:34:51 Find the Last Character
0:35:48 Find the Nth-to-Last Character
0:36:28 Word Blanks
0:40:44 Arrays
0:41:43 Nest Arrays
0:42:33 Access Array Data
0:43:34 Modify Array Data
0:44:48 Access Multi-Dimensional Arrays
0:46:30 push()
0:47:29 pop()
0:48:33 shift()
0:49:23 unshift()
0:50:36 Shopping List
0:51:41 Write Reusable with Functions
0:53:41 Arguments
0:55:43 Global Scope
0:59:31 Local Scope
1:00:46 Global vs Local Scope in Functions
1:02:40 Return a Value from a Function
1:03:55 Undefined Value returned
1:04:52 Assignment with a Returned Value
1:05:52 Stand in Line
1:08:41 Boolean Values
1:09:24 If Statements
1:11:51 Equality Operator
1:13:18 Strict Equality Operator
1:14:43 Comparing different values
1:15:38 Inequality Operator
1:16:20 Strict Inequality Operator
1:17:05 Greater Than Operator
1:17:39 Greater Than Or Equal To Operator
1:18:09 Less Than Operator
1:18:44 Less Than Or Equal To Operator
1:19:17 And Operator
1:20:41 Or Operator
1:21:37 Else Statements
1:22:27 Else If Statements
1:23:30 Logical Order in If Else Statements
1:24:45 Chaining If Else Statements
1:27:45 Golf Code
1:32:15 Switch Statements
1:35:46 Default Option in Switch Statements
1:37:23 Identical Options in Switch Statements
1:39:20 Replacing If Else Chains with Switch
1:41:11 Returning Boolean Values from Functions
1:42:20 Return Early Pattern for Functions
1:43:38 Counting Cards
1:49:11 Build Objects
1:50:46 Dot Notation
1:51:33 Bracket Notation
1:52:47 Variables
1:53:34 Updating Object Properties
1:54:30 Add New Properties to Object
1:55:19 Delete Properties from Object
1:55:54 Objects for Lookups
1:57:43 Testing Objects for Properties
1:59:15 Manipulating Complex Objects
2:01:00 Nested Objects
2:01:53 Nested Arrays
2:03:06 Record Collection
2:10:15 While Loops
2:11:35 For Loops
2:13:56 Odd Numbers With a For Loop
2:15:28 Count Backwards With a For Loop
2:17:08 Iterate Through an Array with a For Loop
2:19:43 Nesting For Loops
2:22:45 Do…While Loops
2:24:12 Profile Lookup
2:28:18 Random Fractions
2:28:54 Random Whole Numbers
2:30:21 Random Whole Numbers within a Range
2:31:46 parseInt Function
2:32:36 parseInt Function with a Radix
2:33:29 Ternary Operator
2:34:57 Multiple Ternary Operators
2:36:57 var vs let
2:39:02 var vs let scopes
2:41:32 const Keyword
2:43:40 Mutate an Array Declared with const
2:44:52 Prevent Object Mutation
2:47:17 Arrow Functions
2:28:24 Arrow Functions with Parameters
2:49:27 Higher Order Arrow Functions
2:53:04 Default Parameters
2:54:00 Rest Operator
2:55:31 Spread Operator
2:57:18 Destructuring Assignment: Objects
3:00:18 Destructuring Assignment: Nested Objects
3:01:55 Destructuring Assignment: Arrays
3:03:40 Destructuring Assignment with Rest Operator to Reassign Array
3:05:05 Destructuring Assignment to Pass an Object
3:06:39 Template Literals
3:10:43 Simple Fields
3:12:24 Declarative Functions
3:12:56 class Syntax
3:15:11 getters and setters
3:20:25 import vs require
3:22:33 export
3:23:40 * to Import
3:24:50 export default
3:25:26 Import a Default Export
📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=PkZNo7MFNFg&list=PLWKjhJtqVAblfum5WiQblKPwIbqYXkDoC&index=4

🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#javascript #learn javascript #learn javascript for beginners #learn javascript - full course for beginners #javascript programming language

Top 10 React Native App Development Companies in USA

React Native is the most popular dynamic framework that provides the opportunity for Android & iOS users to download and use your product. Finding a good React Native development company is incredibly challenging. Use our list as your go-to resource for React Native app development Companies in USA.

List of Top-Rated React Native Mobile App Development Companies in USA:

  1. AppClues Infotech
  2. WebClues Infotech
  3. AppClues Studio
  4. WebClues Global
  5. Data EximIT
  6. Apptunix
  7. BHW Group
  8. Willow Tree:
  9. MindGrub
  10. Prismetric

A Brief about the company details mentioned below:

1. AppClues Infotech
As a React Native Mobile App Development Company in USA, AppClues Infotech offers user-centered mobile app development for iOS & Android. Since their founding in 2014, their React Native developers create beautiful mobile apps.

They have a robust react native app development team that has high knowledge and excellent strength of developing any type of mobile app. They have successfully delivered 450+ mobile apps as per client requirements and functionalities.
Website: https://www.appcluesinfotech.com/

2. WebClues Infotech
WebClues Infotech is the Top-Notch React Native mobile app development company in USA & offering exceptional service worldwide. Since their founding in 2014, they have completed 950+ web & mobile apps projects on time.

They have the best team of developers who has an excellent knowledge of developing the most secure, robust & Powerful React Native Mobile Apps. From start-ups to enterprise organizations, WebClues Infotech provides top-notch React Native App solutions that meet the needs of their clients.
Website: https://www.webcluesinfotech.com/

3. AppClues Studio
AppClues Studio is one of the top React Native mobile app development company in USA and offers the best service worldwide at an affordable price. They have a robust & comprehensive team of React Native App developers who has high strength & extensive knowledge of developing any type of mobile apps.
Website: https://www.appcluesstudio.com/

4. WebClues Global
WebClues Global is one of the best React Native Mobile App Development Company in USA. They provide low-cost & fast React Native Development Services and their React Native App Developers have a high capability of serving projects on more than one platform.

Since their founding in 2014, they have successfully delivered 721+ mobile app projects accurately. They offer versatile React Native App development technology solutions to their clients at an affordable price.
Website: https://www.webcluesglobal.com/

5. Data EximIT
Hire expert React Native app developer from top React Native app development company in USA. Data EximIT is providing high-quality and innovative React Native application development services and support for your next projects. The company has been in the market for more than 8 years and has already gained the trust of 553+ clients and completed 1250+ projects around the globe.

They have a large pool of React Native App developers who can create scalable, full-fledged, and appealing mobile apps to meet the highest industry standards.
Website: https://www.dataeximit.com/

6. Apptunix
Apptunix is the best React Native App Development Company in the USA. It was established in 2013 and vast experience in developing React Native apps. After developing various successful React Native Mobile Apps, the company believes that this technology helps them incorporate advanced features in mobile apps without influencing the user experience.
Website: https://www.apptunix.com/

7. BHW Group
BHW Group is a Top-Notch React Native Mobile App Development Company in the USA. The company has 13+ years of experience in providing qualitative app development services to clients worldwide. They have a compressive pool of React Native App developers who can create scalable, full-fledged, and creative mobile apps to meet the highest industry standards.
Website: https://thebhwgroup.com/

8. Willow Tree:
Willow Tree is the Top-Notch React Native Mobile App Development Company in the USA & offering exceptional React Native service. They have the best team of developers who has an excellent knowledge of developing the most secure, robust & Powerful React Native Mobile Apps. From start-ups to enterprise organizations, Willow Tree has top-notch React Native App solutions that meet the needs of their clients.
Website: https://willowtreeapps.com/

9. MindGrub
MindGrub is a leading React Native Mobile App Development Company in the USA. Along with React Native, the company also works on other emerging technologies like robotics, augmented & virtual reality. The Company has excellent strength and the best developers team for any type of React Native mobile apps. They offer versatile React Native App development technology solutions to their clients.
Website: https://www.mindgrub.com/

10. Prismetric
Prismetric is the premium React Native Mobile App Development Company in the USA. They provide fast React Native Development Services and their React Native App Developers have a high capability of serving projects on various platforms. They focus on developing customized solutions for specific business requirements. Being a popular name in the React Native development market, Prismetric has accumulated a specialty in offering these services.
Website: https://www.prismetric.com/

#top rated react native app development companies in usa #top 10 react native app development companies in usa #top react native app development companies in usa #react native app development technologies #react native app development #hire top react native app developers in usa

12 Fun Challenges to Learn React Native

So you want to learn React Native? Here’s 12 exercises to that will help you do that.

The post is inspired by a free self-paced workshop I’ve created. If you’re interested in guided instructions, solutions, and extra exercises check it out!

Exercise 1: Hello, World!

The classic starter project. Render a square with a background color. Inside of the square render the text “Hello, world”.

Helpful Links

Exercise 2: Capturing Taps

An app isn’t much if a user can’t interact with it. The most basic form of interaction is capturing a user’s tap (or press) on a screen. Using the

Buttoncomponent, capture a tap event andalert"hello".

#react-native #mobile-app-development #beginners #react #javascript #learn-react-native #programming #learn-to-code

Top 9+ JavaScript Concepts to Know Before Learning React

In this tutorial, we're going to take a look at some of those JavaScript concepts that you must know before learning React: JavaScript basics including the Ternary Operator, Destructuring, Spread Operator, Array methods, Arrow functions, Promises, Fetch API, Async/Await, and ES6 Modules and Import/Export.

React is one of the most popular JavaScript frameworks for building single page applications. Needless to say, as a JavaScript framework, it requires you to have a good knowledge of JavaScript concepts.

In this article, we are going to take a look at some of those JavaScript concepts that you must know before learning React. A good understanding of these topics is fundamental in building large scale React applications. So without further ado, let's get started.

  1. JavaScript Basics
  2. The Ternary Operator
  3. Destructuring
  4. The Spread operator
  5. Array methods
  6. Arrow Functions
  7. Promises
  8. The Fetch API
  9. Async/Await
  10. ES modules and Import/Export

1. JavaScript Basics

React is a JS framework and you'll be using JavaScript extensively in your React code. So, it's a no-brainer that you must be aware of the basic JavaScript concepts.

By basics, I mean things like variables, data types, operators, conditionals, arrays, functions, objects, events, and so on.

Having a proper understanding of these concepts is important for you to navigate properly in React, as you'll be using them in every step while building React applications.

So if you are unsure about these things or want to quickly revise everything again, check out some of these free courses or the freeCodeCamp JavaScript curriculum. The MDN docs and JavaScript.info are also helpful quick-search references.

2. The Ternary Operator

Ternary Operator is a short, one-line conditional operator to replace if/else. It's really useful when it comes to quickly checking a condition to render a component, updating state, or displaying some text.

Let's compare how the Ternary Operator works with the If/Else statement:

// Example of Ternary Operator
condition ? 'True' : 'False'
// Example of If/Else statement
if(condition) {
    'True'
}
else {
    'False'
}:

You can see for yourself how much cleaner and shorter using the Ternary Operator is than using If/Else.

The way it works is that you write a condition, and if the condition is true, your program will execute the statement after ?. If the condition is false, the program will execute the statement after :

Simple, isn't it?

3. Destructuring

Destructuring helps us unpack values from arrays and objects and assign them to separate variables in a simple and smooth way. Let's understand it with some code:

// With Destructuring
const objects = ['table', 'iPhone', 'apple']
const [furniture, mobile, fruit] = objects

// Without Destructuring
const furniture = objects[0]
const mobile = objects[1]
const fruit = objects[2]

In the above example, Destructuring saved us 3 lines of code and made the code cleaner. Now let's see another example of passing props in React with destructuring:

// With Destructuring Ex-1
function Fruit({apple}) {
    return (
        <div>
            This is an {apple}
        </div>
    )
}

// With Destructuring Ex-2

function Fruit(props) {
    const {apple, iphone, car} = props
    return (
        <div>
            This is an {apple}
        </div>
    )
}

// Without Destructuring
function Fruit(props) {
    return (
        <div>
            This is an {props.apple}
        </div>
    )
}

Notice how you have to use props again and again when you don't use destructuring in your props.

Destructuring makes our code cleaner and saves us from using the keyword props every time you use a prop variable. There's more to destructuring and you will learn those things when you start building apps in JavaScript and React.

4. The Spread operator

The Spread Operator was introduced to JavaScript in ES6. It takes an iterable and expands it into individual elements.

A common use case of the spread operator in React is copying the values of an object into another object during a state update to merge the properties of both objects. Look at the below syntax:

const [person, setPerson] = useState({
    id: '',
    name: '',
    age: ''
});

 setPerson([
            ...person,
            {
                id:"1",
                name: "Steve",
                age:"25"
            }
        ]);

In the above example, ...person copies all the values of the person object in the new state object which is then further replaced by other custom values with the same properties, which updates the state object.

This was one of the many use cases of the spread operator in React. As your application becomes larger, tools like the spread operator come in handy to handle data in a better and more efficient way.

5. Array methods

Array methods are very common when building a medium to large scale application in React. You will always be using some sort of array method in almost every React app you build.

So, take some time to learn these methods. Some of the methods are extremely common like map(). You use map() every time you fetch data from an external resource to display it on the UI.

There are other methods like filter, reduce, sort, includes, find, forEach, splice, concat, push and pop, shift and unshift and so on.

Some of them are common in usage, and some will come rarely in use. The key is to understand the common array methods very well, and just be aware of the existence of the other methods so that whenever you need them, you can quickly learn them.

Here's a helpful handbook on array methods and working with arrays in general in JavaScript so you can learn more.

6. Arrow Functions

Arrow functions allow us to create functions in a simple manner with shorter syntax.

// Regular Functions
function hello() {
    return 'hello'
}

// Arrow Functions
let hello = () => 'hello'

Both functions in the above code snippet work the same, but you can see that the arrow function is much cleaner and shorter. The empty () in the above syntax are for arguments. Even if there are no arguments, these brackets should be present.

However, you can skip these brackets if there is only one argument present in the function, like this:

let square = num => num * num

In one-liner arrow functions, you can skip the return statement. You can also declare a multiline arrow function by using curly braces {} similar to regular functions.

let square = num => {
    return num * num
}

7. Promises

You use promises to handle asynchronous operations in modern JavaScript. Once you create a promise in JavaScript, it can either succeed or fail – known as being resolved or rejected in JavaScript terminology.

Promises in JavaScript, in some way, can also be compared to the promises we humans make. Just like human promises are driven by the future implementation of a certain action, promises in JavaScript are about the future implementation of the code, resulting in either it being resolved or rejected.

There are 3 states of a promise:

  1. Pending – When the final result of the promise is yet to be determined.
  2. Resolved – When the promise is successfully resolved
  3. Rejected – When the promise is rejected.

Once a promise is successfully resolved or rejected, you can use a .then() or .catch() method on it.

  • The .then() method is called when a promise is either resolved or rejected. It takes 2 callback functions as arguments. The first one is executed when the promise is resolved and the result is received, and the second one is an optional argument in case the promise is rejected.
  • The .catch() method is used as an error handler and is called when the promise is rejected or has an error in execution.

Enough theory, let's end this section with an example of a promise, including the usage of the .then() and .catch() methods:

let promise = new Promise((resolve, reject) => {
  const i = "Promise";
  i === "Promise" ? resolve() : reject(); // Checkout the above Ternary Operator section to better understand the syntax
  }
);

promise.
    then(() => {
        console.log('Your promise is resolved');
    }).
    catch(() => {
        console.log('Your promise is rejected');
    });

8. The Fetch API

The Fetch API allows us to make async requests to web servers from the browser. It returns a promise every time a request is made which is then further used to retrieve the response of the request.

A basic fetch() takes one argument, the URL of the resource you want to fetch. It then returns another promise that resolves with a Response object. This Response object is the representation of the HTTP response.

So, to get the JSON content from this promise, you have to use the .json() method on the Response object. This at last will return a promise that resolves with the result of the parsed JSON data from the response body.

It might be a little confusing, so pay close attention to the example below:

fetch('http://example.com/books.json') // fetching the resource URL
  .then(response => response.json()); // calling .json() method on the promise
  .then(data => setState(data)); // updating the state with the JSON data

9. Async/Await

Async/Await functionality provides a better and cleaner way to deal with Promises. JavaScript is synchronous in nature and async/await helps us write promise-based functions in such a way as if they were synchronous by stopping the execution of further code until the promise is resolved or rejected.

To make it work, you have to first use the async keyword before declaring a function. For example, async function promise() {}. Putting async before a function means that the function will always return a promise.

Inside an async function, you can use the keyword await to suspend further execution of code until that promise is resolved or rejected. You can use await only inside of an async function.

Now, let's quickly finish off this section with an example:

async function asyncFunction() {
    let promise = new Promise(resolve => {
        resolve();
    });
    let response = await promise; // further execution will be stopped until the promise is resolved or rejected
    return console.log(response);
}

You can learn more about async and await in this in-depth guide.

10. ES modules and Import/Export

Modules were introduced in JavaScript in ES6. Each file is a module of its own. You can carry out objects, variables, arrays, functions, and so on from one file and use them in another. This is referred to as importing and exporting modules.

In React, we use the ES6 modules to create separate files for components. Each component is exported out of its module and imported to the file where it is to be rendered. Let's learn this with an example:

function Component() {
    return(
        <div>This is a component</div>
    )
}

export default Component
import Component from './Component'

function App() {
    return (
        <Component />
    )
}

In React, you have to render every component you declare in the App.js component.

In the above example, we created a component called Component and exported it with our code export default Component. Next, we go to App.js and import the Component with the following code: import Component from './Component'.

Conclusion

You've reached the end of the article! So far we have covered JavaScript basics including the Ternary Operator, Destructuring, Spread Operator, Array methods, Arrow functions, Promises, Fetch API, Async/Await, and ES6 Modules and Import/Export.

I hope you have learned a lot from this article and and understand some of the important JavaScript concepts and why you need to learn them thoroughly before jumping into React.

This article is not an alternative to learning these concepts thoroughly on your own. I have only given a general introduction to them and why are they important. Now it's up to you how you learn these things and build your knowledge from here. Best of luck with the journey!

Original article source at https://www.freecodecamp.org

#javascript #react