r/javascript • • May 23 '21

20 JavaScript Concepts you should know as a JavaScript Programmer!

https://blog.devgenius.io/20-javascript-concepts-you-should-know-as-a-javascript-programmer-c04d7b1a8d6e?sk=cc9a655f3a07686a9a1cdd4825c73e18
2 Upvotes

6 comments sorted by

5

u/4391021382 May 23 '21 edited May 23 '21

The closure example doesn't show the most powerful thing about closures. You still have access to variables declared in an outer function even after the outer function has returned.

function counterConstructor() {
let counter = 0;

function up() {
    counter += 1;
    return counter;
}

function down() {
    counter -= 1;
    return counter;
}

return Object.freeze({ up, down });
}

const counter1 = counterConstructor();
const counter2 = counterConstructor();

counter1.up(); // 1
counter1.up(); // 2
counter1.up(); // 3

counter2.up(); // 1

Because of closures there no need for classes

const makeMyConstructor = dependencies => spec => {
    const { dep1, dep2 } = dependencies; // dependency inject
    const { memeber1, member2 } = spec; // constructor arguments
    const reuse = otherConstructor(spec); // composition

    const method = () => {
        // has access to dependencies, spec, reuse, method
    };

    return Object.freeze({ 
        method, 
        goodness: reuse.goodness,
    });
};

const myConstructor = makeMyConstructor(dependencies);
const myObject = myConstrcutor(arguments);

4

u/backtickbot May 23 '21

Fixed formatting.

Hello, 4391021382: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

2

u/Ok-okay-imhere May 23 '21

This article is so helpful! Thank you so much. I’m new to JavaScript and this amazing thing to learn

2

u/oneandmillionvoices May 24 '21

no, it is misleading and in many points completely wrong.

1

u/Ok-okay-imhere May 24 '21

Oh really? Like what point. Sorry I’m new to JS and still learning.