DEV Community

loading...

Concepts you should know to be a master of JavaScript

Mihai Stanciu
I'm trying to learn about all things tech. I'm also a student trying to learn about a career in the tech world.
・5 min read

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.js

console.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 2

console.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' keyword When 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 keyword The 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 keyword

const 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

Discussion (11)

Collapse
epsi profile image
E.R. Nurwijayadi

The Event Loop is one of the most important aspects to understand about Node.js.

πŸ•· nodejs.dev/learn/the-nodejs-event-...

Collapse
javier123454321 profile image
Javier Gonzalez

Yes! Knowing how the event loop behaves was one of those things that just levels up your JavaScript significantly.

Collapse
mstanciu552 profile image
Mihai Stanciu Author

Thanks for sharing. I think I will alocate one entire article to the event loop, as I didn't want to make this one too long.

Collapse
epsi profile image
E.R. Nurwijayadi • Edited

I'm actually just another beginner in NodeJS world. To help more beginner, I have made a working example with souce code in github.

πŸ•· epsi.bitbucket.io/lambda/2020/12/0...

First defined both functions, as a sender (producer), and a receiver (customer).

Sender and Receiver

And then run both separately

Run Both in Program Entry Point

I hope this could help other who seeks for other case example.

Thread Thread
mstanciu552 profile image
Mihai Stanciu Author

Thanks for sharing. Helping each other is the only way to improve. πŸ‘πŸ˜

Collapse
labib profile image
Asif

Dude ,
I am new at Dev.to , Can You please tell me how to increase font size in the middle of the Blog . Or How do I write bigger Words in the middle when writing a Blog .
BTW , Very useful Blog
Thanks

Collapse
mstanciu552 profile image
Mihai Stanciu Author

You can use Markdown. It gives instructions when you make a new post on the right side. You can use # - for h1

- for h2

...

- for h6

Also you can use text for bold text.

Collapse
labib profile image
Asif

Thanks alot.
You saved me

Collapse
stanley profile image
Stanley Gomes • Edited

Great post, man! I got new things to learn. Thanks.

Collapse
mstanciu552 profile image
Mihai Stanciu Author

Thanks a lot for sharing your opinionβ™₯οΈπŸ‘πŸ˜

Collapse
chathunbandara profile image
chathuranga bandara

Great