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>
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!");
node script.js
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];
1.the forEach
function:
function callbackFunction(value, <index>) {
sum = sum + value;
}
array.forEach(callbackFunction);
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);
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);
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;
}
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"
}
};
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"
Functions
In JavaScript there are 3 ways to declare functions:
- Named function
function myFunction() {
//code here
}
- Anonymous function
function() {
//code here
}
- Arrow functions
const myFunction = () => {
//code here
}
There are different ways of using functions:
- Normal
myFunction();
- IIFE (Instantly Invoked Function Expression)
function myFunction() {
//code here
}();
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
}
}
}
parentFunction().returnedFunction();
**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();
}
}
}
parentFunction().returnedFunction() //"text to be returned"
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
});
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
})
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!"
}
is equivalent with:
async function myFunction() {
return Promise.resolve("Hello World!")
}
- the
await
keyword Theawait
keyword before a function makes the function wait for a promise.
let result = await promise;
**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
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);
});
- with the
axios
function - axios function needs to be installed
**Note: **You have to import the axios
library like this:
import axios from 'axios';
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));
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));
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.
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.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.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
Top comments (11)
The Event Loop is one of the most important aspects to understand about Node.js.
π· nodejs.dev/learn/the-nodejs-event-...
Yes! Knowing how the event loop behaves was one of those things that just levels up your JavaScript significantly.
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.
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).
And then run both separately
I hope this could help other who seeks for other case example.
Thanks for sharing. Helping each other is the only way to improve. ππ
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
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.
Thanks alot.
You saved me
Great post, man! I got new things to learn. Thanks.
Thanks a lot for sharing your opinionβ₯οΈππ
Great