DEV Community

loading...
Cover image for Learn these awesome Javascript concepts.

Learn these awesome Javascript concepts.

Abhishek Raj
Learning something worth sharing....
Updated on ・3 min read

Introduction

You must have seeing people abusing and hating JS, because they compare Javascript with other languages like Java, C++, Go but Javascript is entirely different.

In this post I will be showing some cool things in javascript.

Generator Function ⚡

These are a type of function which can pause and resume its execution.

In simple words, suppose you call this function and you want to pause it execution at a certain state/condition and after certain condition you want to again resume its execution, you can do using generator function.

In the above example, you can see generator function are created using Asterisk(*) after writing function and when you want to pause its execution use yield and to stop use return, you can even return values using yield.

If you want to resume the execution, execute .run() method of the generator object.

Usages

  1. Iterator
  2. Generating infinite number efficiently

Read More (Ctrl + Click)
Some More (Ctrl + Click)

Async Await vs Generator Function ⏳

  1. Generator Functions and Async Functions can be used to write asynchronous code which can wait.

  2. Generator function always yields an object like {value: any, done: bool} but Async function returns a promise to resolve or can throw an error if doesn't resolves.

  3. Generator function runs till yield and pauses but Async function runs till await and waits there.

Read More

Closure 🤏

Closure is an environment, created inside a function which stores some variables and can be used by another function inside that scope.

In the above example, you can see how the parentName is bind with child function.

Usages

  1. Hiding data inside function.
  2. Maintaining state.

Read More

Currying 🍛

Suppose of you have a function with N arguments, converting it into N function calls with only 1 arguments, is called Currying in Javascript.

Famous Question: Create a currying function to give sum of N numbers e.g. function(1)(2)(3).....(N) = 1+2+3+...+N

Usage

  1. Used to create Higher Order Function
  2. Memoization
  3. Error handling
  4. Initializing functions

Read More

Higher Order Functions (HOF) 💪

HOF accepts functions as argument and/or returns function with closure.

E.g. Array methods like map, reduce, filter.....etc.

Usage

  1. Binding functions with state

Read More

Call, Apply & Bind 📞

Call, Apply and Bind are JS methods using to bind object with this.

In the above example, I have shown how you can use call, apply and bind.

Usage

  1. DRY: Do Not Repeat Code
  2. Debouncing

Read More

Connect Me @ Linkedin, Github, Twitter, Youtube 😇

Thanks to Akshay Saini for his amazing series on JS.

Discussion (40)

Collapse
lukeshiru profile image
LUKESHIRU • Edited

I know excellent JS devs that might not know, or know but don't use at all some of the features you mention. For example I don't use generators because they are basically functions that hold a mutable state, and return "different values per call" which isn't pure. Generally if I want that, I can replicate something like a generator without having an actual generator:

const counter = (max = 0) => ({
    done: max <= 0,
    next: () => counter(max > 0 ? max - 1 : 0),
    value: max
});

// vs

const counter = function* (max = 0) {
    let count = max;

    while (count >= 0) {
        yield count--;
    }

    return 0;
};
Enter fullscreen mode Exit fullscreen mode

Also, your examples in general could be written with arrow functions which could make them far easier to read, specially the curried one:

const multiplicate = multiplier => multiplicand => multiplicand * multiplier;

// vs

function multiplicate(multiplier) {
    return function (multiplicand) {
        return multiplicand * multiplier;
    };
}
Enter fullscreen mode Exit fullscreen mode

And the idea with currying is the reuse, mainly, so the example after it also could be improved a little:

const double = multiplicate(2);
const triple = multiplicate(3);

double(3); // 6
triple(3); // 9

// vs

multiplicate(2)(3); // 6
multiplicate(3)(3); // 9
Enter fullscreen mode Exit fullscreen mode

Cheers!

PS: Please, next time try to avoid titles like you used, is one step away from being "If don't you use titles like this, you don't know how to click-bait!" :/

Collapse
hasnaindev profile image
Muhammad Hasnain

Posts such as these are targeted at beginners. The concepts and alternatives you suggest are not just your own opinions regarding what is good and bad but also makes things unnecessarily complex.

Yes, you're very smart but not everyone has a decade of experience under their belt. Those who have, aren't going to come and read these posts.

Collapse
stojakovic99 profile image
Nikola Stojaković

I fail to see how anything he mentioned makes things unnecessarily complex.

Thread Thread
hasnaindev profile image
Muhammad Hasnain • Edited

That's the problem with "senior" developers on dev.to. They fail to see things from a beginner's perspective. If you know these concepts then this post isn't for you.

Thread Thread
lukeshiru profile image
LUKESHIRU • Edited

I understand that maybe this:

argument => returnValue;
Enter fullscreen mode Exit fullscreen mode

Might be harder to understand than this:

function (argument) {
  return returnValue;
}
Enter fullscreen mode Exit fullscreen mode

Still, saying "this post is not for seniors" is disingenuous at best. First because originally the post had other title, that was alluring seniors as well (if you are a senior, you know that you'll never know everything, there is always something new to learn, so "skipping posts" is not a great idea either), and second if the target is junior devs, then is even more important to be clear that you don't HAVE to know every thing in this list in order to be a competitive developer (as I mentioned in my initial comment, I don't even use generators, there are devs that don't use promises unless they have async/await, and so on)...

Thread Thread
stojakovic99 profile image
Nikola Stojaković

I'm not a senior developer but medior. Maybe I don't see it well from the beginner perspective - that's what I asked the question and that's why I was expecting a good answer.

Thread Thread
stojakovic99 profile image
Nikola Stojaković

Honestly I don't see why people find arrow methods so confusing. I find them much clearer and easier to read.

Thread Thread
hasnaindev profile image
Muhammad Hasnain • Edited

The first example implements an iterator interface along with recursive. The watered down version is cute but multi-level arrow functions and currying, do you think a beginner would find that easy?

I hope you found this answer good enough. If you still don't see how people find this difficult perhaps you could sit down with a beginner or better yet, spend some time teaching JavaScript to someone as their first programming language, as in actually mentor someone.

You'll be very frustrated.

Thread Thread
lukeshiru profile image
LUKESHIRU

I have a mentoring stream in Spanish, I did other one in English in the past, a discord channel, and a mentoring program in the company I'm working on, besides the project I have with two close friends which also are junior devs. To be honest they generally find arrow functions easier to understand than regular functions, unless they have experience with other language that didn't had that, but they get the concept pretty fast and prefer it to the longer alternative.

Still, you keep on pointing that "arrow function syntax is hard", which I get, but you keep omitting the fact that the article was asking devs to know a bunch of things that aren't as "key" as the article previously depicted.

Thread Thread
hasnaindev profile image
Muhammad Hasnain • Edited

I didn't click on this when its previous title, so, I won't concern myself with that. If we are discussing this, let's not casually ignore the iterator interface and recursion. Currying also causes additional complexity because you're throwing functional programming into the mix.

Regardless of what I say, you'll remain firm in your point of view and speak from your experience as if it is the experience of every new developer. Anyways, I don't want to talk about this further.

I prefer your answers but I have a very grave problem with this attitude where senior developers shove their opinions down other's throat. Even I haven't really studied functional programming, what are the odds that a beginner would've.

Have a good day Luke!

Thread Thread
lukeshiru profile image
LUKESHIRU

Commenting on posts is not "reinforcing opinions down other's throats", opinions can be dismissed. Because I'm a "senior"(*) I'm not allowed to give feedback in posts targeted to junior developers? I don't get it ... still, I get that you don't want to discuss any longer.

You too have a good day, Muhammad!

(*) I didn't mentioned this here, but from my pov seniorities are a joke, so I hate to use those terms.

Thread Thread
hasnaindev profile image
Muhammad Hasnain

Of course, you're allowed to give feedback. I hope I didn't cause any strife, if I did, I'm sorry. Regarding seniorities, well, that's something we can agree on. Thanks. :)

Thread Thread
stojakovic99 profile image
Nikola Stojaković

Currying is a hard concept on it's own for beginners. Arrow functions don't make it much harder in my opinion - it's just a different syntax.

Thread Thread
hasnaindev profile image
Muhammad Hasnain

... yeah, whatever.

Collapse
lukeshiru profile image
LUKESHIRU • Edited

The point in my comment:

  1. The original title said that you had to know this things to be a JS dev (kinda gatekeeping), and the author agreed and changed the title.
  2. There are easier ways of doing some of this things with modern tools. Would you suggest to use something like eval nowadays? No, you'll suggest strict mode and better practices (designed to make DX better, performance and security better, etc.). What's the point in learning old or bad practices, other than context for better alternatives?

In short: You missed the point.

Thread Thread
abhishekraj272 profile image
Abhishek Raj Author

Comparing Generator function with eval is vague.
I would use generator function instead of creating my own generator object then use it.

Thread Thread
lukeshiru profile image
LUKESHIRU

I wasn't comparing generators with eval, the comparison was actually between something old like eval with something new like generators, arrow functions, and so on.

Just to clarify, I did my original comment with the best of intentions. It looks like it was taken as something with bad intentions and it wasn't. If I had thought that this post was actual click-bait, I would have reported it as I did with many others that are actually ads, spam or click-bait.

Thread Thread
abhishekraj272 profile image
Abhishek Raj Author

Its an open world, not always everyone has to agree with everyone. We all have our opinion. You are free to share your opinion neither I am hiding any negative comments.

You are also free to report this post.

Thread Thread
lukeshiru profile image
LUKESHIRU

Please, read carefully, maybe is a language barrier (my original language is spanish and maybe I wasn't clear enough):

  1. My original comment was only feedback about the post, and the title, with no negative intention.
  2. My suggestions were to:
    • Update the title.
    • Don't imply that everything in this list has to be known to be a "JavaScript developer" (which felt like gatekeeping).
    • Improve the examples, particularly the curried one, to use more modern syntax (which makes sense to make it easier to read and use).
  3. I didn't and I will not report this post, because you were great and updated the title to be a better fit for the content. I mentioned that I reported other posts that actually went against the terms of DEV, but this isn't one of those, and I mentioned that because, again, I didn't wrote any of this with bad intentions U_U

I feel like both you and Muhammad Hasnain are being super "defensive" when I'm not attacking the post in any way. I doesn't make any sense to keep going with this "argument", I just wanted to clarify that my comments are usually well intentioned. The only way I can write something negative, is when the post is actually bad (either by not following the terms of DEV, or by being damaging posts).

Cheers

Thread Thread
abhishekraj272 profile image
Abhishek Raj Author

Cool agreed.
Although my native language is Hindi not English ;)

Thread Thread
lukeshiru profile image
LUKESHIRU • Edited

Yup, double language barrier then 😅

Me <-> Spanish <-> English <-> Indi <-> You
Enter fullscreen mode Exit fullscreen mode
Thread Thread
hasnaindev profile image
Muhammad Hasnain

Believe it or not, English is my third language language. I'm fluent in Pashto that's spoken in Pakistan and Afghanistan. I can speak Urdu which is like 90% same as Hindi so I can speak Hindi too.

I can read Arabic and understand Punjabi a little but I'm not counting them as language. Spanish is also an interesting language. I was thinking about properly learning 4th.

Not sure if I should learn Mandarina, Spanish or German. It really depends on which country I'll decide to move to. =)

Collapse
abhishekraj272 profile image
Abhishek Raj Author

Thanks for the feedback, renamed the title.
Yes, I avoided arrow function in currying because its quite easy to understand returning functions for beginners.

Almost every thing in JS can be written on our own, it doesn't need to know the original javascript concept.

Cheers

Collapse
sakethkowtha profile image
sakethk • Edited

I like generators. Redux-Saga library has been developed using generators. I would say generators is not bad way. Its our choice whether to use generators or not

Collapse
lukeshiru profile image
LUKESHIRU

Not the point of my comment, but ok :)

Collapse
mfurkankaya profile image
Furkan KAYA

Really nice clickbait. 👌

Collapse
jcubic profile image
Jakub T. Jankiewicz • Edited
  1. HOC is React pattern called Higher Order Components that have nothing to do with Higher Order Functions.
  2. I would add interator protocol to the list. This is the API behind generators that make them work. This is also what make for..of loops works with arrays. Because Arrays are iterators.
var iter = [1,2,3][Symbol.iterator]();
console.log(iter.next()); // {value: 1, done: false}
console.log(iter.next()); // {value: 2, done: false}
console.log(iter.next()); // {value: 3, done: false}
console.log(iter.next()); // {value: undefined, done: true}
Enter fullscreen mode Exit fullscreen mode
Collapse
abhishekraj272 profile image
Abhishek Raj Author
  1. There was a typo, fixed it.
  2. Will add the iterator to this list.

Cheers

Collapse
gitpaulo profile image
Paulo Santos

Insightful post for beginners! Well done! Some advice: do make sure you use the tag #beginners or at least set the post's expert level down to a lower level since it is showing up in timelines of people that are not so which has caused this mess in the comment section.

Collapse
abhishekraj272 profile image
Abhishek Raj Author

Thanks for the feedback, will update it.

Collapse
vikrambhatt profile image
Vikram Bhatt

FYI except for call, apply and bind methods (which are JS features) the rest are realted to functional programming paradigm rather than JS.

Collapse
oskarcodes profile image
Oskar Codes

Just a quick note, asynchronous functions don’t return a function to resolve, but instead a promise.
Otherwise, this is a great article!

Collapse
abhishekraj272 profile image
Abhishek Raj Author

Oh, I missed that here, will update.

Thanks for pointing out :)

Collapse
dandev95 profile image
DanDev95

Async await returns a promise, not a prototype...

Collapse
abhishekraj272 profile image
Abhishek Raj Author

Thanks for the fix.
Cheers!

Collapse
dandev95 profile image
DanDev95 • Edited

The English and grammar in this article are horrendous.

Collapse
abhishekraj272 profile image
Abhishek Raj Author

Be my english tutor :)

Collapse
sadanandpai profile image
Akshay Pai

Generator in action with example
github.com/sadanandpai/generators-...

Collapse
mooha1999 profile image
mooha1999 • Edited

In the Closure example
The parameter "childName", where will it get its value from?
I'm new to js and this issue is confusing me

Collapse
peerreynders profile image
peerreynders • Edited

This is one of the weird cases where it is actually easier to show with TypeScript:

// A type of function that takes a 
// `string` argument and returns `undefined`
type ChildFn = (name: string) => void;

// A type of function that takes a
// `string` argument and returns a `ChildFn`
type ParentFn = (name: string) => ChildFn;

// `create` is a function of type `ParentFn`
// i.e. it takes a string argument and returns
// a `ChildFn` function. 
const create: ParentFn = (parentName) => 
  (childName) => print(`${parentName} ${childName}`);

// i.e. `create` returns the function 
// `(childName) => print(`${parentName} ${childName}`)`
// note that `parentName` comes from the closure that 
// created the function.

// The function returned from `create` 
// is bound to `child` and has access 
// to `parentName = 'Bitcoin' 
// through its closure which created it
const child: ChildFn = create('Bitcoin');

// Here we finally supply `childName` 
// so that the full string is logged.
child('Dogecoin');

// ---
function print(...args: any[]): void {
  console.log(...args);
}
Enter fullscreen mode Exit fullscreen mode

So it's at child('Dogecoin'); that we supply childName.

A version that uses function declarations only:

// A type of function that takes a
// `string` argument and returns `undefined`
type ChildFn = (name: string) => void;

// The function value returned from `create`
// is bound to `child` and has access
// to `parentName = 'Bitcoin'
// via the closure that created it
const child: ChildFn = create('Bitcoin');

// Here we finally supply `childName`
// so that the full string is logged.
child('Dogecoin');

// [LOG]: "Bitcoin Dogecoin"

// ---

// `create` is a function that takes
// a `string` argument and returns
// a function of the `ChildFn` type.

function create(parentName: string): ChildFn {
  return childFn;

  // ---
  function childFn(childName: string): void {
    print(`${parentName} ${childName}`);
  }
}

// i.e. `create` returns the `childFn` function
// value which has access to `parentName`
// value via the closure that created it.

function print(...args: any[]): void {
  console.log(...args);
}
Enter fullscreen mode Exit fullscreen mode

I believe it's a bit more difficult to understand.