In order to create React.js applications we should know JavaScript (ES6)

In order to create React.js applications we should know JavaScript (ES6)

Modern JavaScript essentials

In order to build applications in React.js, we should know Modern JavaScript (ES6)

Modern JavaScript essentials.

· Var, let, const

· Objects

· This

· Arrow function

· Destructing

· Spread

· Classes

· Modules

Let, var and const A variable is a “named storage” for data. We can use variables to store goodies, visitors, and other data.

To create a variable in JavaScript, use the let keyword.

Let message

Let message = ‘Hello’;

Var instated of let

In the older script, you may also find. Another keyword, var instead of let

Var message ‘hello’;

The var keyword is almost the same as let. It also declares a variable, but in a lightly different “old school way “. it’s generally not used in modern scripts.

now the var variable is accessible inside of the Function in which it’s defined.

now we declare the variable with let keyword that variable only accessible inside that block. The second console.log(i) will give an error. Because let is block scope.

Notes: Var -> variable declares with var keyword are scoped to the function.(var -> function)

Let -> variable declares with let keyword are scoped to the block in which that defined (let-> block) .

Var doesn’t have block scope but function scope

Let is a new feature introduced I ES205 and it’s essentially a block-scoped version of var. Modern JavaScript developers might choose to only use let and completely discard the use of var.

Using constants (const)

To declare a constant (unchanging) variable, use const instead of let. const myBirthday = ’12.06.1998’;

Variable declared with var or let can be changed later. But Variables declared using const are called “constants”. They cannot be changed.

const myBirthday = ’12.06.1998’;

myBirthday=’3.5.2021’;

when a programmer is sure that a variable will never change, they can declare it with const to guarantee and clearly communicate that fact to everyone.

object objects are used to store keyed collection of various data and more complex entities. An object literal is a collection of name-value pairs.

In JavaScript, most things are objects, from core JavaScript features like arrays to the browser APIs. Built on top of JavaScript. we can create our own object to encapsulate related functions and variables into an efficient package.

An object which usually consists of several variables and function which are called Properties and Method, when they are inside objects

Variables -> properties Function -> Methods

Creating an objects

Creating an objectsCreating an objects

Literals and properties

We can immediately put some properties into {. . .} as “key: value” pairs.

property has a key (also known as “name” or “identifier”) before the colon “:” and a value to the right of it.

In the person object, there are two properties:

  1. The first property has the name “name” and the value “said”

  2. The second one has the name “age” and the value 22.

Property values are accessible using the dot notation.

To remove a property, we can use the delete operator.

remove a propertyremove a property

using a function in an object.

The this keyword

in other words, this. name means the name property of these objects.

bind method

In JavaScript function are object, we use bind () method to bind a function to an object.

Functions provide a built-in method bind that allows to fix this.

The basic syntax is:

Function in JavaScript Often we need to perform a similar action in many places of the script. for example. We need to show a nice-looking message when a visitor logs in, logs out, and maybe somewhere else.

Functions are the main “building blocks” of the program. They allow the code to be called many times without repetition.

We’ve already seen examples of built-in functions. Like alert(message), prompt (message, default) and confirm(question).

But we can create a function of our own as well.

It looks like this:

One of my favorite features of modern (ES6) JavaScript is arrow functions.

The above function is an old JavaScript function in ES6 we have a cleaner way to add this code to the function.

Arrow Function There’s one more very simple and concise syntax for creating functions. That’s often better than functions. It’s called “arrow function”, because it looks like this.

**Arrow Function**Arrow Function

if we have only one argument, then parentheses can be omitted (remove) making that even shorter.

if there are no arguments, parentheses should be empty (but they should be present).

an arrow function can be used in the same way as Function Expressions.

function expressionsfunction expressions

arrow functions may appear unfamiliar and not very readable at first, but that quickly changes as the easy get used to the structure.

They are very convenient for simple one-line actions when we’re just too lazy to write many words.

Let me show you where these arrow functions are really useful, let’s imagine, we have an array of jobs. Each job object has an ID, and a property called ACTIVE which we set true or false.

Now let’s imagine we want to get only the active jobs

this is old styles function syntax.

note:- Arrow function does not have its own bindings to this keyword

Differences & Limitations:

· Function is actions. So their name is usually a verb.

· It should be brief, as accurate as possible, and describe what so that some reading the code gets an indication of what the function does

It is a widespread practice to start a function with a verbal prefix that vaguely describes the action. there must be an agreement within the team on the meaning of the prefixes.

Function starting with ….

· get…. — return a value,

· calc… — calculate something,

· create… — create something,

· check… — check something and return a Boolean, etc.

examples of such names

· showMessage(…) // shows a message

· getAge(..) // returns the age (gets it somehow)

· calsSum(..) // calculates a sum and returns the result

· createForm(..) // creates a form (and usually returns it)

· checkPermission(..) // checks a permission, returns true/false

with prefixes in place, a glance at a function name gives an understanding of what kind of work it does and what kind of value it returns.

One function — one action A function should do exactly what is suggested by its name, no more.

Array.map()

The map () method creates a new array with the result of calling a function for every array element.

The map() method calls the provided function once for each element in an array, in order.

It’s useful when calling a function that returns an array in the map() callback.

Mosh. Es5 introduces a new method in arrays called map() this very useful method and in react we use it to render list. When we render a list of items, that’s we use the map() method of the array.

Example.

So Let’s say we have an array of colors with three 3 items. [red, green, blue]

we call the map () method on this array colors. map() and here we need to pass a callback function. The job of this function is to transform each element in this array. It takes one item at a time and returns a new item.

object Destructing the destructing assignment also works with objects.

Syntax.

Example.

Old way

Changing the Name of the property

If we want to assign a property to a variable with another name, for instance, address. street to go into the variable named st, then we can set it using a colon:

The colon shows “what: goes where”.

Spread operator Es6 provides a new operator called spread operator that consists of three dots (…). the spread operator allows you to spread out elements of an iterable objects such as an array, a map, or a set.

The spread syntax can be used when all elements from an object or array need to be included in the list of some kind.

Example

we can even combine the spread operator with normal values.

we can also apply the spread operator to an object.

or

Classes in JavaScript A JavaScript class is a blueprint for creating objects. A class encapsulates data and functions that manipulate the data.

In JavaScript classes are functions. ES6 classes are just a special function.

To verify the fact that classes are special functions, you can use the typeof operator to check the type of the Person class.

if we often need to create many objects of the same kind, like users, or goods or whatever.

The “class” syntax

Then new MyClass () creates a new object with all the listed methods. The constructor() method is called automatically by new, so we can initialize the object.

Example.

When a new Person(“Said”) is called:

  1. A new object is created.

  2. The constructor runs with the given argument and assigns this.name to it.

… Then we can call methods, such as person.walk() and person.name.

Why we use Class Mosh Hamedani. look at this code we use this object Person with two members name and walk ().

if we want to create another Person object, that can walk, so we should duplicate the code and called this object Person2. There is a problem the problem is we have to duplicate the implementation of the walk() method, so we can use Class to solve this problem.

Inheritance Es6 supports the concept of Inheritance. inheritance is the ability of a program to create new entities from an existing entity.

The class that is extended to create newer classes is called the Parent class / super class. The newly created classes are called the child/sub classes.

A class inherits from another class using the “extends” keyword.

The child classes inherit all properties and methods except constructors from the parent class.

A class can extend another class, and objects initialized using that class inherit all the methods of both classes.

Syntax

Example

Let’s said we want to define Teacher class

However, all teachers should be able to walk, because they all Persons. We don’t want to duplicate this walk() method in the Person, and Teacher classes, so how can solve these problems. Use the inheritance.

The Teacher class inherits from the Person class. It means it will inherit all methods defined in this Person class. We add keyword extends, so Teacher extends Person

Now if we create a Teacher object,

we have walk method which we have inherit from the Person Class. And the teach() method that added in Teacher Class.

This is inheritance

Now let’s take to the next level

***inheritance***inheritance

this part in the code.

Whenever we add a constructor in the child class, we need to call the constructor of its parent class, here in the constructor we special keyword super(), which references the parent class. We call it just like method.

· Super() method to call a parent method.

· Super() to call a parent constructor (inside our constructor only)

Modules Modules, introduction As our application grows bigger, we want to split it into multiple files, so-called ‘modules’ A module usually contains a class or a library of useful functions.

What is a module?

A module is just a file, a single script, as simple as that.

There are directives export and import to interchange functionality between modules, call functions of one module form another one.

· Export — keyword labels variables and functions that should be accessible from outside the current module.

· Import — allows importing functionality from other modules.

More about Modules in JavaScript

For a long time, JavaScript existed without a language-level module syntax. That wasn’t a problem, because initially, scripts were small and simple, so there was no need.

But eventually, scripts become more and more complex, so the community invented a variety of ways to organize code into modules, special libraries to load modules on demand.

For instance:

· AMD — one of the most ancient module systems, initially implemented by the library require.js.

· CommonJS — the module system created for Node.js server

· UMD — one more module system, suggested as a universal one, compatible with AMD and CommonJS.

Now all these slowly become a part of history, but we still can find them in old scripts. The language-level module system appeared in the standard in 2015, gradually evolved since then, and is now supported by all major browsers and in Node.js.

We have multiple classes that define in some files. It will be much nicer if split this code accrues multiple files, this what we call Modularity. Instead of writing all code in one file, we write our code in multiple files, we call each file a module.

Our code without modularity

let’s go modularizes our application

I am going to move each file into a spirited file.

Step 1. Create a file person.js file

Step 2. Create a file teacher.js file

Step 3 . to execute both files in the index.js file.

Step 3. To Execute the modules using an HTML file

To execute both the modules we need to make a HTML file. Note we should use the attribute type =” module” in the script tag.

We spirited our code, now we can see each, we have less code in each file, our application is more maintainable.

Importing a Module To be able to consume a module, use the import keyword. A module can have multiple import statements.

1. Importing Named Exports

While importing named exports, the names of the corresponding components must match.

Syntax.

2. Import “as”

However, while importing named exports, they can be renamed using the as a keyword.

3. Import *

If the list is long, we can import everything as an object using import * as <obje>

4. Importing default exports

Unlike named exports, a default export can be imported with any name.

A module can have one and only one default export. The default export is easier to import. The default for a module can be a variable, a function, or a class.

let me quick recipe

with default export

with name export

Best of luck. Enjoy :)

Said Shah Ahmadi