Skip to content

Instantly share code, notes, and snippets.

@gragonmau
Last active January 25, 2018 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gragonmau/5aefe0757159c23c949a9a1919f49c9b to your computer and use it in GitHub Desktop.
Save gragonmau/5aefe0757159c23c949a9a1919f49c9b to your computer and use it in GitHub Desktop.
JS Awesomeness

JS Awesomeness

Javascript is awesome, stick with me and I'm gonna tell you why!

Where it comes from?

JS was never meant to be what it is today. At the very begining it was created to execute simple validation tasks on the client side. It was first implemented by Brendan Eich at the old browser Netscape.The first version of it was built in incredible 10 days.

The story of JS is a bit confusing, and there are multiple conflicting resources about it. It was quite messy at the beggining, as it was a resposibilty of the browser development teams to implement it. They seemed to not have an aggreement at that time. I'm quite sure they haven't done it in purpose, since it was a new thing, but everyone was still understanding their roles in the development community.

The game changing moment was when it was taken to ECMA, an european standards organization, obviously in order to get standardized. JS is also known as ECMAScript, due to ECMA of course. There were several released versions, maybe the most popular one is ES6. Since then, the scenario has really changed -- JS now follows a standard and we shouldn't expect to deal with multiple language versions. It's next releases are guided by a techinical committee called TC-39.

A bit more on JS story may be found here.

P.S: It does NOT have anything to do with Java.

Why is it getting so big?

Jack of All Trades

JS is known for being present pretty much everywere. Let me tell you why...

  • Front-end development. There is no escape from JS in this case. Front-end depends deeply on JS, one way or another you will need to use that.
  • Back-end development. Have you ever heard about Node JS? It's one of the most popular and hyped languages at the momment. It's fast, flexible and most importantly it get things done. There is a particularity about how it deals with threads that makes it awesome (which I'm not gonna mention later on), but if you wanna learn more about it look for the "event loop" and the keywords "node js single threaded".
  • Mobile development. JS runs natively on both iOS and Android. It does not perform as good as the standard apps, but in some cases it worth going for JS rather than building two apps one for each plataform.
  • Databases. Some NoSQL databases, or most of them, use JSON (JavaScript Object Notation) as default reponse for queries, some of them store data as JSON and others allows or restricts queries to be done using JS.
  • Microcontrollers. You can create some cool IoT integrations using JS as well. There are some boards that might be programmed using JS, such as Tessel 2.

Have in mind that... JS allows you to play many roles, just by knowing one language. You could either go "full JS" in order to have a slightly shorter learning curve.


Widely Used

JS is the most popular programming language at the world. There is more people working with JS than any other language.

Which means, there is a huge community backing up the language.


The Docs

JS documentation is awesome. Mozilla Developer Network, MDN, has plenty docs about the language. I often use them, just to review or either to find out the answer for a question. It is by far one of the best sources of JS knowledge. Have a look.


The Libs, Frameworks and others

There are lots of libraries written in JS and ready to be used. I wouldn't say all of them are good 'cause I would be lying. But there are awesome ones... I'm gonna list some of them:

  • Express JS
  • Native Script
  • React JS
  • RxJS
  • Angular JS
  • Ionic JS
  • Gulp

Those are the most famous ones that I have at the top of my mind, but there are other minor ones that are hell useful.

You might get things done faster with JS.


Hybrid Language

Have you heard about functional programming? JS allows you to use multiple programming paradigms and kinda mix them, depending on your need. Why not use OOP in conjunction with some Functional concepts and consider the Reactive paradigm? It suits your needs.

Chances are you have used JS today! And you grandma too! ;)


The complaints...

I sometimes hear people telling bad things about JS, but I was never convinced by them. Sometimes they don't know about ES6 features, sometimes they had some bad time with async, sometimes they can't deal with the dynamic typed variables, sometimes they are just bad developers...

I don't mean to put JS in a pedestal -- I'm not that type of guy, but I prefer to know the languages drawbacks and deal with them when possible. Let's defend JS against this developers.

Question: I can't deal with the fact that JS does not have strong typed variables...

Answer: It's meant to be dynamic, an there is a reason for that. Imagine why it was first built... The intent was to validate a form... Text inputs will usually return strings independently if the text is a number, a symbol or an emoji... Why not have them casted to integer when they get assigned to a math operation? Sometimes we just want to compare the content without bothering to cast it...

let definitelyText = "1"// <- ";" is optional
let certainlyNumber = 1
let anotherNumber = 2
let troll = "aaaaa"

// The result depend on the first item at the "sum", if it's a string the final type will be a string
console.log(definitelyText + certainlyNumber) // "11"
console.log(definitelyText + anotherNumber) // "12"

// If it's a number it will try to sum
console.log(certainlyNumber + definitelyText) // 2
console.log(anotherNumber + definitelyText) // 3
console.log(certainlyNumber + troll) // NaN, which stands for not a number

// "==" compares only the content
if(definitelyText == certainlyNumber) { // true
    console.log("It matches!")
}
else{
    console.log("There is something wrong with JS!")
}

// While "===" compares the type as well
if(definitelyText === certainlyNumber) { // false
    console.log("Ops!")
}

If you can't deal with the fact or if you start panicking looking at this code, just go for TypeScript... It ironically add types and some other cool stuff to JS. Depeding on your need it might be a match ;)


Afirmative sentence: Node JS sometimes is hard...

Afirmative response: Yes.

Comment: This is when you get that you teacher lied to you when they said that if you understand programming logic, you would be able to master any programming language... No, unfortunately it depends on the paradigm... I learned Node JS by failing!


Question: JS has no classes, I'm so disapointed...

Counter-argue: It does. Click here....

Comments: No.


We could keep going for a long time... Still if I would pick the most important concept or even the worst misconception about JS, I would say ES6... Most people usually remember ES5 which is not the most brilliant JS relase -- that's ES6! ES6 made it completely different. This is new JS baby. Actually not, we are about to have ES9 released... Still ES6 was the most dramatical change.

Hands on!

Okay, now we got to the most important part: let's do some cool stuff with JS. I don't mean to get you mastering it, I just want to show you some basic stuff. Let's go for Repl.It where we will be able to write and execute some JS just in time!

Variable types

// There are three ways to declare a variable const, let and var
const cant = "Can't touch this!" // You got it right?

// Those two looks similar... 
// The diference is let executes in a blocked scope, if you didn't get it just use let
var variable = ":(" // Sad
let letItBe = ":D" // Happy, let "replaces" var on ES6

Hello World

console.log("Hello World!") // BTW semi-column are optional on ES6

If statement

let yes = true
let sure = "true"

// While "==="" compares content and type "==" looks only for the content
if(true === yes && sure == true) {
    console.log("Yes")
}
else if(sure === true) { // You may user as many as else if's as you wish, just try switch case first
    console.log("Wat")
}
else {
    console.log("No")
}

For statement

// Can you guess the result?
for(let i = 0; i < 10; i++){
    console.log(i)
}

Functions

//Okay there are serveral was to declare a function...

// Simple, get declared once the file is loaded
function greeting(name){
    console.log("Good morning " + name)
}

// echo("JS Awesomeness") would fail here

// Inside a variable get declared "up down", just like a variable, it couldn't be used here
const echo = function(text){
    console.log(text)
}

// Arrow, the short way of doing so
const hello = name => console.log("Hello " + name)

greeting("Grag")
echo("JS Awesomeness")
hello("it's me")

JS Square

// This example was copied from MDN

class Rectangle {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
  
    get area() {
        return this.calcArea();
    }

    calcArea() {
        return this.height * this.width;
    }
}

const square = new Rectangle(10, 10);

console.log(square.area);

Source


JS Points

// This example was copied from MDN

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    static distance(a, b) {
        const dx = a.x - b.x;
        const dy = a.y - b.y;

        return Math.hypot(dx, dy);
    }
}

const p1 = new Point(5, 5);
const p2 = new Point(10, 10);

console.log(Point.distance(p1, p2));

Source


Map Function

// Formant Name
let people = ["mauricio", "rafael", "camila", "kelvin", "renan", "victória"]

const mapFormatName = function(name) {
    let nameSlice =  name.slice(1, name.length)
    return name[0].toUpperCase() + nameSlice 
}

console.log(people.map(mapFormatName));


// Square
let numbers = [1,2,3,4,5,6,7,8,9]

const mapSquare = square => square * square

console.log(numbers.map(mapSquare))

Filter Function

let cars = [
    { brand: "Ford", engine: "1.4", color: "red"},
    { brand: "General Motors", engine: "1.0", color: "gray"},
    { brand: "General Motors", engine: "1.0", color: "white"},
    { brand: "General Motors", engine: "1.6", color: "white"},
    { brand: "General Motors", engine: "1.0", color: "gray"},
    { brand: "Gurgel", engine: "1.6", color: "white"},
    { brand: "General Motors", engine: "1.0", color: "gray"},
    { brand: "Rolls Royce", engine: "1.0", color: "black"},
    { brand: "Rolls Royce", engine: "1.4", color: "red"},
    { brand: "Rolls Royce", engine: "1.0", color: "gray"},
    { brand: "Rolls Royce", engine: "1.0", color: "white"},
    { brand: "Ford", engine: "1.0", color: "gray"},
    { brand: "Ford", engine: "1.6", color: "red"},
    { brand: "Ford", engine: "1.6", color: "gray"},
    { brand: "Ford", engine: "2.0", color: "red"},
    { brand: "Lada", engine: "3.0", color: "gray"},
    { brand: "Lada", engine: "1.0", color: "black"},
    { brand: "Lada", engine: "1.0", color: "black"},
] 


// Red Cars
function filterRedCars(car){
    return car.color === "red"
}

console.log(cars.filter(filterRedCars))
console.log(""); //Break line

// Ford Cars
function filterFordCars(car){
    return car.brand === "Ford"
}

console.log(cars.filter(filterFordCars))
console.log(""); //Break line

// Red Rolls Royce Engine Over 1.0 Cars
const filterRedRollsRoyceEngineOverOneZero = car => (car.brand === "Rolls Royce" && car.engine > 1.0 && car.color === "red")

console.log(cars.filter(filterRedRollsRoyceEngineOverOneZero))

Reduce Function

let people =  [
    { name: "João", age: 20 },
    { name: "Maria", age: 30 },
    { name: "Pedro", age: 12 },
    { name: "Godofredo", age: 45 },
    { name: "Rogério", age: 27 },
    { name: "Capitão Nascimento", age: 38 },
    { name: "Juan", age: 40 },
]

const mapAge = people => people.age;

const reduceSumAge = (x ,y ) =>  x + y

const averageAge = () => {
    let age = people.map(mapAge)
    return (age.reduce(reduceSumAge) / people.length).toFixed(2)
}

console.log(averageAge())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment