Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 12, 2021 06:17 pm GMT

Concepts you should know to be a master of JavaScript

MLH #MajorLeagueHacking #LocalHackDay

How to use JavaScript

JavaScript is an amazing programming language. It is most popular as the browser's programming language, but that does not mean that's all it is good for. It is used for much more...backend development, desktop development, machine learning, and many more.
For anything not in the browser, one way to compile and run JavaScript is Node.js.

With the browser

In the browser, you can just add a file with the .js extension to your HTML using the script tag like this:

<!DOCTYPE html><html>  <head>    <title>Page Title</title>  </head>  <body>    <script defer src="path/to/file.js"></script>  </body></html>
Enter fullscreen mode Exit fullscreen mode

Note: Everything in the JavaScript file will be executed in the browser.

With Node.js

In order to run a JavaScript file on your machine all you need to do is use the console like this:

// script.jsconsole.log("Hello World!");
Enter fullscreen mode Exit fullscreen mode
node script.js
Enter fullscreen mode Exit fullscreen mode

What you need to know to master JavaScript

Data Structures

The concept of Data Structures is not specific to JavaScript. But there are some interesting features in JS for them.

Arrays

In JavaScript, arrays have special functions attached to them, called Array Methods.

The examples will use the following array:

var array = [18, 20, 22, 40, 15, 21, 16, 17, 96];
Enter fullscreen mode Exit fullscreen mode

1.the forEach function:

function callbackFunction(value, <index>) {  sum = sum + value;}array.forEach(callbackFunction);
Enter fullscreen mode Exit fullscreen mode

This will return the sum of all elements in the array, without creating a new array.

  • The value parameter has a specific element of the specified array.
  • The index parameter is optional and returns the current index.

2.the map function

function callbackFunction(value, <index>) {  sum = sum + value;}array.map(callbackFunction);
Enter fullscreen mode Exit fullscreen mode

This does the same thing as the forEach function, but it generates a new array to work on.

3.the filter function

function callbackFunction(value, <index>) {  return value > 20;}array.filter(callbackFunction);
Enter fullscreen mode Exit fullscreen mode

This function creates a new array with element that pass the test from the function passed as parameter.

4.the reduce function

var sum = array.reduce(callbackFunction)function callbackFunction(total, value) {  return total + value;}
Enter fullscreen mode Exit fullscreen mode

This function will reduce the array to a single number. In this case it will reduce it to the sum of all elements within it.

The parameters are:

  • total - initial value / previously returned value
  • value - the current value

Objects

In JavaScript, objects are a collection of other elements of the language. I say other elements, because it can also contain functions and other objects.

Example:

const object = {  elem1: "text", //a string  elem2: 2,      //an integer  elem3: function () {                 // a function    const a = 2, b = 3;    return a + b;  },  elem4: {       // an object    elem: "text2"  }};
Enter fullscreen mode Exit fullscreen mode
How to access elements of an object

You can access an element from an object using the . notation.

console.log(object.elem1);     //return "text"console.log(object.elem2);     //return 2console.log(object.elem3());   //return 5(2+3);console.log(object.elem4.elem);//return "text2"
Enter fullscreen mode Exit fullscreen mode

Functions

In JavaScript there are 3 ways to declare functions:

  • Named function
function myFunction() {  //code here}
Enter fullscreen mode Exit fullscreen mode
  • Anonymous function
function() {  //code here}
Enter fullscreen mode Exit fullscreen mode
  • Arrow functions
const myFunction = () => {  //code here}
Enter fullscreen mode Exit fullscreen mode

There are different ways of using functions:

  • Normal
myFunction();
Enter fullscreen mode Exit fullscreen mode
  • IIFE (Instantly Invoked Function Expression)
function myFunction() {  //code here}();
Enter fullscreen mode Exit fullscreen mode

Note: As you can see the function is called instantly after it is declared. We can tell by the parenthesis () at the end of the function declaration.

Returning a function

A function can return another function, with the returned function being called a Closure. Here is an example:

function parentFunction() {  return {    function returnedFunction() {      //code here    }  }}
Enter fullscreen mode Exit fullscreen mode
parentFunction().returnedFunction();
Enter fullscreen mode Exit fullscreen mode

**Note: **This concept helps with encapsulation(technique for compartmentalizing information).
Example:

function parentFunction() {  function _privateFunction() {    return "text to be returned"  }  return {    function returnedFunction() {      return _privateFunction();    }  }}
Enter fullscreen mode Exit fullscreen mode
parentFunction().returnedFunction()  //"text to be returned"
Enter fullscreen mode Exit fullscreen mode

Promises

Producing code is code that can take some time. Consuming code is code that must wait for the result. A Promise is a JavaScript object that links producing code and consuming code.

let myPromise = new Promise(function(resolve, reject) {  resolve();  //when successful  reject();   //when an error occurs});
Enter fullscreen mode Exit fullscreen mode
myPromise  .then(res => {    //when the call is successful    //we have access to the result via the res parameter  })  .catch(err => {    //when an error occurs    // we have access to the error via the err parameter  })
Enter fullscreen mode Exit fullscreen mode

Async/await

  • the 'async' keywordWhen async is in front of the function declaration, the function will return a Promise. So:
async function myFunction() {  return "Hello World!"}
Enter fullscreen mode Exit fullscreen mode

is equivalent with:

async function myFunction() {  return Promise.resolve("Hello World!")}
Enter fullscreen mode Exit fullscreen mode
  • the await keywordThe await keyword before a function makes the function wait for a promise.
let result = await promise;
Enter fullscreen mode Exit fullscreen mode

**Note: **The await keyword can only be used inside an async. function.

Web API requests

Making requests to APIs is an essential part of JavaScript. Every developer is required to know this. For example:

  • a front-end dev is required to know in order to access APIs to make the project more interactive(sending emails, saving in databases, etc.)
  • a back-end dev needs to know this to be able to access existing services(Spotify API, Discord API, Twilio API, etc.), instead of coding the from 0(not reinventing the wheel)

There are 2 great ways to make API calls:

  • with the fetch function (included in the basic JavaScript installation) - no need to install anything
const options = {  method: "GET/POST/PUT/DELETE",  headers: {}, //optional  data: {},  //optional  body: {},    //optional}const request = fetch('url/of/api', options); // this returns a promise so we could and should use the await keywordconst result = request.json(); // returns a JSON object
Enter fullscreen mode Exit fullscreen mode

or

const options = {  method: "GET/POST/PUT/DELETE",  headers: {}, //optional  data: {},  //optional  body: {},    //optional}fetch('url/of/api', options)  .then(res => {    //returns a JSON object  })  .catch(err => {    //code for error here    console.error(err);  });
Enter fullscreen mode Exit fullscreen mode
  • with the axios function - axios function needs to be installed

**Note: **You have to import the axios library like this:

import axios from 'axios';
Enter fullscreen mode Exit fullscreen mode
const options = {  headers: {}, //optional  params: {},  //optional};axios.<get/put/post/delete>('url/to/api', options)  .then(res => {    // can access a JSON object  })  .catch(err => console.error(err));
Enter fullscreen mode Exit fullscreen mode

or

const options = {  headers: {}, //optional  params: {},  //optional  method: "GET/POST/PUT/DELETE"};axios('url/to/api', options)  .then(res => {    // can access a JSON object  })  .catch(err => console.error(err));
Enter fullscreen mode Exit fullscreen mode

What helps in mastering anything code related

This next section is important, however it does not have any technical explanations. These are some tips on how to grow as a developer and what helps when you are looking to get hired. If you're not interested you can skip this part.

  1. Join a community
    Communities of developers can help you meet new people interested in the same topics. It's not only fun but also leads to learning from other developer's experience.

  2. Contribute to Open Source
    Join GitHub. Find something interesting. Add value to that project. For more information, I recommend Eddie Jaoude's Youtube channel. He has amazing content.

  3. Participate in hackathons
    Currently I am taking part in MLH's Local Hack Day: Build, and the challenges are great. They propose topics such as Combine Two APIs, Use a Music API or Use the Twilio API, and many other interesting problems you can solve alone or with your guildmates. It is an amazing experience and I recommend it to anyone serious about development and coding. #MLH #MajorLeagueHacking #LocalHackDay


Original Link: https://dev.to/mstanciu552/concepts-you-should-know-to-be-a-master-of-javascript-2nn8

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To