r/javascript • • May 28 '19

What are some JavaScript things beginners don't know?

333 Upvotes

383 comments sorted by

152

u/[deleted] May 28 '19

Closure is a concept I see lots of beginners struggle with. You can massively speed up dev time once you grasp how it works in JS.

87

u/Mydrax May 28 '19

Closures are one of the most frequently misunderstood or barely ever undstood concept by beginner Javascript programmers. I personally believe that you will have a lot of "Oh, I see!" moments after you fully understand it. You will be capable of understanding certain things that previously didn't make sense to you because I assure you 100% that you've been using closures without even knowing it!

If you do not understand closures, please read this article, it gives you good understanding of what a normal function is and how it's execution takes place, then explains to you what a closure is. It's big but it will without doubt be an efficient use of time.

23

u/[deleted] May 28 '19

of "Oh, I see!" moments

I understand closure but had very few of these so far

15

u/Mydrax May 28 '19

Well, 2 really awesome use cases of closures I could name off the top of my head are:

  1. When you create function factories, where the outer function can be used to create functions that have similar concerns.

  2. The module pattern, that can be used to create private functions in javascript (where you return a set of functions whose logic is encapsulated).

→ More replies (3)
→ More replies (1)

1

u/thisisafullsentence May 28 '19

Could I roughly boil that article down to: closures a) have access to outside variables, but restrict inside variables and b) provide a new `this` context?

2

u/8lbIceBag May 29 '19

If you're using this in a closure I feel for most cases you're doing it wrong

→ More replies (1)

1

u/[deleted] May 28 '19

Woah.

This article is awesome! I thought I understood what closures were but totally misunderstood the meaning.

Thanks!

23

u/priceLbear May 28 '19

A few weeks ago I spent some time learning about closure and I understand the concept. How exactly does it speed up dev time though? Do you use it often? If yes, could you describe some use cases I obviously fail to see?

8

u/superluminary May 28 '19

JavaScript treats functions as data. A function is a datatype, just like any other object. This means you can pass it around from place to place just as you would pass a string or a number.

What closure gives you is a stable environment to do this. When you create a function, it gains a closure scope that contains all the variables that the function could see when it was defined. These variables are still available no matter when and how you run your function in the future.

Some example use cases are:

Event handlers. Create them now, and have your code execute them later in another context. They still work.

ES6 modules. All those variables you declare in your module live in the function closure. Import them later, they still work.

There are many others. It's core to the language.

18

u/[deleted] May 28 '19

The better you understand it the more efficient your architecture becomes and less time you spend debugging issues that involve global and local variables not being available to functions etc.

16

u/theycallmeepoch May 28 '19

I would really love to see some examples of this as it's not clear to me yet the benefits other than creating a nested function which has "private" variables. I'm not quite at Closures yet in "Secrets of the Javascript Ninja".

12

u/lostPixels May 28 '19

In my experience working on a codebase with 10,000+ LOC, we never use closures. Every method is generally treated as atomic, where every call just accepts arguments are predictably returns results. Closures are cool but in my opinion can be confusing enough that they will cause some less JS focused developers a lot of issues debugging.

9

u/theycallmeepoch May 28 '19

Yes, I feel like a pure functional programming approach helps minimize the need.

It seems like it was good for making your own getter and setter functions but those are built into JS now...

→ More replies (1)
→ More replies (6)

3

u/el_graveto May 28 '19 edited May 28 '19

Lets say you are making a function that stores properties of pen, like function pen, and properties color, shape, lvl of ink, those properties only exist inside of your function. That is good because you avoid conflict with other parts of your code, but if you need to call those properties or change them? You could do it easily by nesting a function inside your function pen that do whatever you want with those properties, those properties are inside that child function scope but out of the rest of the code scope. You can even call that nested function as argument in another function, it create many possibilities and once you get the hang of it you spend less time coding and have a cleaner code, less prone to bugs, also since those properties (or variables, methods,..) are inside of the function scope you avoid memory leaks.

→ More replies (5)
→ More replies (1)

5

u/kamenjan May 28 '19

I think he meant that your dev time is normal if you understand closures :) You know right away when to use arrow function and when not to, so you avoid frequent and pointless code refactoring on account of not understanding closures :)

11

u/[deleted] May 28 '19

I'd argue arrow functions have nothing to do with closures. Scope and closure are not synonymous.

6

u/[deleted] May 28 '19

If you are a React developer, you are leveraging closures on every single component render even if you're not realizing it.

1

u/8lbIceBag May 29 '19

It doesn't really. Maybe because everything is private and you don't have to use this everywhere or program as defensively?

In my experience, if you're someone building off or extending a library, it will slow you down. It sucks to extend a library or framework that uses closures because you don't have access to internals. Also closures are slower and more resource intensive (execution wise) if there's many instances.

Great for singletons or for your own libraries that no one has to extend though

12

u/razorsyntax May 28 '19

I never understood why we don’t call closures “scope”? What’s the difference between closures and scope in, say, C++ or Java?

20

u/senocular May 28 '19

Scope is where values are defined. Closures are functions which reference one or more scopes. They're related but not the same thing

→ More replies (5)

5

u/eatsomeonion May 28 '19

Closure is part of the function scope property

5

u/Candyvanmanstan May 28 '19

Because closure and scope isn't the same in javascript either. A closure can have access to three scopes. It's own scope, an outer functions scope, and global variables.

2

u/ScientificBeastMode strongly typed comments May 28 '19

You can also take a function as an argument (or from a reference in an outer scope), and apply it inside the current function’s scope, which is how classes are “extended.”

→ More replies (1)

1

u/[deleted] May 28 '19

What did you find useful while learning and applying it? As in, what helped you learn it well?

2

u/j_sidharta May 28 '19

I personally read These books (You don't know js series). The one about closures is amazingly well put. The others are also really interesting

1

u/[deleted] May 28 '19

Yeah, I've heard a lot about those books. I'll give them a read soon.

1

u/richieahb May 28 '19

I remember really realising I had “got” closures when I realised the similarity between closures and classes, and that you can basically model the latter with the former (albeit less efficiently)

1

u/fallen_atreus May 28 '19

I completely understand closures now and have done a couple of advanced JS courses on the subject. I haven't worked on big scale projects but have done a couple of smaller ones. Not sure how closures would speed up the development time, I can't seem to pass beyond using closures to keep data private in method, or turn code into some sort of module or use it with setTimeOut to properly use the increment variable.

Care to elaborate? I have been really struggling to put this thing in practice.

→ More replies (1)

135

u/theMightyPanda27 May 28 '19

Promises. They are quite tricky to understand for a beginner, but very convenient as one masters.

29

u/senocular May 28 '19 edited May 28 '19

Normally I would agree with you, but lately that doesn't seem to be the case.

I've been doing a lot of interviews lately and probably the one thing people have consistently showed a keen understanding of is promises. Where people have slipped up the most? this. While I get this is tricky (it's already been brought up a few times in this thread) I've also always considered promises to have a bit of a learning curve, especially compared to the more classic callback approach. But I guess learning material nowadays, and I guess apis in general, use them so much that people need to learn them a lot sooner than before...? Not sure, but I thought that was a little interesting takeaway from these interviews.

Edit: This said with a sample set of "advanced beginners"

→ More replies (5)

12

u/pm_me_cute_rem_pics js/ux May 28 '19

Yeah especially waiting for promises to resolve and parallel stuff with async/await.

For example i see this in a lot of my code reviews with new js programmers:

// does some parallel async stuff
arrayOfItems.forEach(async item => {
    await doSomethingAsync(item)
})

doSomethingWhenDone()

This won't wait for the promise to actually resolve outside of the forEach and call doSomethingWhenDone(). If your program exist it will not wait for your async work to be done.

either do:

const pendingPromises = []

arrayOfItems.forEach(item => {
    pendingPromises.push(doSomethingAsync(item))
})

await Promise.all(pendingPromises)

doSomethingWhenDone()

Or if you like mapping over promises.

await Promise.all(
    arrayOfItems.map(async item => {
        await doSomethingAsync(item)
    })
)

doSomethingWhenDone()

examples https://repl.it/repls/WeeklyColorfulGraduate

4

u/thinkmatt May 28 '19

Also, this is a pet peeve of mine: when I see a function that returns a promise being called w/async+await around it (as inside your map function). You've just wrapped one promise in another, and all it's done is added overhead which does take some performance hit. In your example, it could just be written as `await Promise.all(arrayOfItems.map(doSomethingAsync));` (That's about as many operations as I would put on one line though :)

1

u/[deleted] May 29 '19

How about Promise.each() ?

await Promise.each(arrayOfItems, function(item) {

return doSomethingAsync(item)

})

3

u/pm_me_cute_rem_pics js/ux May 29 '19

Promise.each is not vanilla js, but bluebird it looks like. So if you're not using bluebird you can't use Promise.each

1

u/tjb1019 May 29 '19

i like to use the for...of loop in this type of situation. seems like the cleanest syntax of all the options.

for (const item of arrayOfItems) {
   await doSomethingAsync(item);
}

doSomethingWhenDone();

2

u/justrhysism May 29 '19

I believe this would wait for each promise to resolve before moving onto the next loop.

The Promise.all() solution allows each async call to happen async concurrently; only moving on once all promises resolve (regardless of the order in which they resolve).

→ More replies (3)

2

u/pm_me_cute_rem_pics js/ux May 29 '19

this will execute synchronously instead of parallel. If you want parallel this does not work unless you push the pending promise in an array.

10

u/amdc !CURSED! May 28 '19

knowing Promises is essential if you want to succeed, but once you're familiar with them you should move on to async/await

5

u/SharkLaunch May 29 '19

Async/await are just syntactic sugar around promises, and there are times when the former is more appropriate.

2

u/amdc !CURSED! May 29 '19

Out of interest, what are cases where promises are more appropriate (besides .race and .all which you totally can use in conjunction with await)?

→ More replies (1)
→ More replies (7)

2

u/BehindTheMath May 28 '19

This is one of the most common misunderstandings I see in beginner questions posted here and /r/webdev. Really any async code, including callbacks.

→ More replies (6)

247

u/TrikkyMakk May 28 '19

Months are zero based

47

u/inu-no-policemen May 28 '19

This allows you to use the month as an index:

> ['jan', 'feb', 'mar', 'apr', 'may', 'etc'][new Date().getMonth()]
"may"

It probably sounded like a good idea at the time.

Anyhow, that's why it is that way. This behavior isn't unique to JS either.

28

u/StoneCypher May 28 '19

Much better to use the locale API.

const month = date.toLocaleString('en-us', { month: 'short' });

44

u/NotSamNub May 28 '19

Ah, out of the 6 months in the year, my favourite has to be "etc", such lovely weather during that time of year!

0

u/[deleted] May 28 '19

[deleted]

→ More replies (22)

105

u/ItalyPaleAle May 28 '19

The async programming model and especially how the event loop works.

The latter might be transparent to you 99.9% of the times, but then you’ll run into issues where your code behaves unexpectedly and you just need to execute it in the next tick (iteration of the event loop) instead.

12

u/ThatBriandude May 28 '19 edited May 28 '19

and you just need to execute it in the next tick (iteration of the event loop) instead.

I consider myself pretty well versed in javascript however I can not imagine what you mean with this. How would "execute it in the next tick" look in code?

10

u/envis10n May 28 '19

setImmediate sometimes, you run into a max callstack issue for function calls if you don't ensure that the next call comes on the next tick. This is especially important for recursive functions or looping functions that might call itself again.

6

u/ShellbertShellbach May 28 '19

Note: setImmediate is not a standardized feature of JS and only exists in Node.js, IE10, IE11, and pre-Chromium Edge.

→ More replies (1)

3

u/ThatBriandude May 28 '19

Shouldnt that be handled via logical exit conditions?

Only cases I can think of is where there arent any exit conditions like gameloops or listeners

6

u/envis10n May 28 '19

Depends on how the code is structured. Sometimes a recursive function will call itself too many times and crash, unless you move the next call to the next tick. Logical exit conditions don't matter when you need the function to be called more times than is allowed by the max call limit in a single tick.

→ More replies (1)
→ More replies (1)

9

u/robotslacker May 28 '19

Check out the video below. I didn’t really understand the event loop until this. The presenter does a really good job explaining and visualizing it.

https://youtu.be/8aGhZQkoFbQ

3

u/archivedsofa May 28 '19

setTimeout(doSomething, 0);

4

u/ScientificBeastMode strongly typed comments May 28 '19 edited May 28 '19

setImmediate is less standard, but supposedly faster than setTimeout set to zero. It’s basically a native implementation of setTimeout( ... , 0).

→ More replies (2)

3

u/HattyJetty May 28 '19

Scheduling in general is a pretty advanced topic, if you take different execution environments into account (e. g. Node.js has a process.nextTick(), which is actually "more immediate" than setImmediate()). The presence of microtasks, idle callbacks and animation frames doesn't make life easier for a beginner as well.

1

u/GItPirate May 28 '19

Oh yes this is spot on

1

u/kor0na May 29 '19

Opaque

43

u/jesusthatsgreat May 28 '19

Formatting dates. You don't need a bulky third party library. toLocaleDateString() will do the job in 99% of cases.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

5

u/Bosmonster May 28 '19

For Node you will need to add Localization for it to work properly, so that might be a reason, especially if you don't have control over the environment.

Also the options for dateString are fairly limited compared to some of the libraries out there. For example relative date/time.

8

u/ProgrammingPro-ness May 28 '19

MomentJS has made me so happy over the years.

4

u/DasDoto May 29 '19

I use date-fns these days over moment. You can import only the function you need and the dates are immutable unlike moment. A lot lighter than moment as well.

3

u/ModernCannabist May 29 '19

We just switched to DayJS because it does everything MomentJS does but at about the quarter the size

141

u/inabahare May 28 '19

Using const and let

30

u/rook218 May 28 '19

Learning what linting is has saved me so much time and energy with hammering in simple syntax rules like that.

Another thing I'd say is to learn DOM manipulation first. I got stuck for a month or two on using JS to solve algorithmic problems in online courses like free code camp, but after I had a solid grasp on JS I still had no freaking idea how to actually use it. Starting with the basics of selecting an element and adding a listener would have been a huge boon to my progress.

10

u/yeah666 May 28 '19

I was in the same boat as you. Wes Bos' Javascript 30 helped me get over that hump.

8

u/ScientificBeastMode strongly typed comments May 28 '19

Yeah that’s one of the huge advantages of JavaScript. The visual feedback loop is so much faster with JavaScript than with a lot of other languages, simply because it works in the browser. And building UI with it is a breeze in comparison to other things.

8

u/Murdathon3000 May 28 '19

I don't know, if you're a beginner that just started learning JS in the last couple of years, virtually every resource (at least in my experience) hammers down let and const pretty much right away, or at least very early on.

9

u/inabahare May 28 '19

Yet if you pay attention to the beginner questions asked here and other places, a lot of them use var instead of const or let. That is mostly because a lot of schools/universities/whatever aren't that good at keeping up

3

u/Murdathon3000 May 28 '19

Fair point, that's absolutely true come to think of it.

→ More replies (49)

25

u/[deleted] May 28 '19

How powerful a fucking REPL is and how much you can speed up your learning and coding if you're using one.

1

u/FlandersFlannigan May 29 '19

Can you explain further?

1

u/Funwithloops May 31 '19

I've been using the Node REPL in my backend watch scripts. So in the terminal my server is running in I can run arbitrary code against my backend (run functions, query database models, etc). It's super handy.

0

u/[deleted] May 28 '19

[deleted]

1

u/[deleted] May 29 '19

Exactly and as far as Google Chrome goes I hope you also know about this magic: if you hit a breakpoint in your code the REPL gets the context you're currently in, meaning you can play around with all variables the current scope has access to.

I find myself a lot coding helper functions within the REPL and then just copying it to my editor (that does some needed formatting in the end).

→ More replies (1)

46

u/mjeemjaw May 28 '19

Javascript is very fast in modern environments

13

u/ShortFuse May 28 '19

Javascript is also multi-threaded if you use web-workers (which even works in IE11).

If you ever done desktop software application development, the main thread is basically your UI thread. You can interact between threads with postMessage. It's narrowing down your architecture pattern (MVC, MVVM, MVP, etc) to make that happen where beginners usually get lost.

The popular frameworks don't really push their usage much. I fear many people don't bother learning the core DOM/JS/Browser interactions. It's not bad because most frameworks heavily push async operations (promises), but the less you do on your UI thread, the better.

→ More replies (8)

43

u/chuckySTAR May 28 '19
document.querySelector()

8

u/zayelion May 28 '19

Someone give this man gold!

10

u/BargePol May 28 '19

document.querySelectorAll("body")[0]

11

u/senocular May 28 '19

document.body

7

u/BargePol May 28 '19

thatsthejoke.jpg

61

u/rorrr May 28 '19

How this works. It's actually quite complicated.

28

u/[deleted] May 28 '19

more importantly, understanding the different contexts of this:

this in the global space => window

this in a function => function context

this in a method of an object => the object

this with call/apply/bind => whatever you want it to be

edit for ES6: this is not bound in arrow functions, so the value bound outside the arrow function will be found and used instead.

5

u/rorrr May 28 '19

If you think that covers all the cases, it does not. Try to guess what this prints without running the code:

this.a = 1;
(function() {
	this.a = 2;
	console.log(this.a);
})();
console.log(this.a);

7

u/[deleted] May 28 '19

I would guess 2 for the inner log, and 1 for the outer log. Am I mistaken?

→ More replies (8)

0

u/[deleted] May 28 '19

[deleted]

→ More replies (1)

16

u/tchaffee May 28 '19

It's not complicated. People simply don't take the time to learn. Which is a shame, because it takes about an hour to learn. Here are the rules in the words of Kyle Simpson:

Determining the this binding for an executing function requires finding the direct call-site of that function. Once examined, four rules can be applied to the call-site, in this order of precedence:

  1. Called with new? Use the newly constructed object.

  2. Called with call or apply (or bind)? Use the specified object.

  3. Called with a context object owning the call? Use that context object.

  4. Default: undefined in strict mode, global object otherwise.

Instead of the four standard binding rules, ES6 arrow-functions use lexical scoping for this binding, which means they adopt the this binding (whatever it is) from its enclosing function call. They are essentially a syntactic replacement of self = this in pre-ES6 coding.

That's not complicated. Take the hour or so to read the two chapters on this from the You Don't Know JS series, and you'll be good.

7

u/senocular May 28 '19

Sure, some basic rules make it seem easy, but what rule is this?

button.addEventListener('click', owner.func)

3? No, but most beginners would think so, and not without reason. When it comes to callbacks the waters are murky, and that's where 99% of issues with this come from.

8

u/tchaffee May 28 '19

I guess that could be confusing, but that's not the call site. How long does it take to learn that? I have yet to see someone still be confused about this after taking the time to learn the actual rules and then apply those rules to analyzing code in their daily work. In almost every case of confusion, the person does not know the rules at all. Fair point that beginners could be confused because they don't know all the rules yet. But if something takes an hour to learn, I don't think "beginner" is much of an excuse. Just spend the hour.

→ More replies (2)

4

u/DerGernTod May 28 '19

well, in that case the function call-site is no longer owner, but rather button. the owner object doesn't have anything to do with this function call anymore. for those cases i'd rather do something like that: button.addEventListener('click', (e) => owner.func(e)) which (probably) has the desired behaviour. or, if you don't want to use an additional function, it get's a bit messy: button.addEventListener('click', owner.func.bind(owner))

2

u/[deleted] May 28 '19

Indeed. I have been doing js for 5+ years and still sometimes have head scratching moments with this.

1

u/robolab-io May 28 '19

clone masterrace reporting in

1

u/Dangle76 May 28 '19

Isn’t it the same thing as “self” in python?

1

u/rorrr May 28 '19

Kind of. Similar idea, different behavior.

1

u/mcvoid1 May 28 '19

The short answer: it doesn't.

2

u/rorrr May 28 '19

After doing JS for 20 years, I kinda agree. The whole language isn't nice. I'd love to have something like Go or Java as an alternative. WebAssembly will probably make it happen when it matures.

→ More replies (7)

16

u/magical_h4x May 28 '19

A lot of devs coming from other languages assume const means constant value, whereas it's actually simply constant reference (i.e. can't reassign that variable).

You can't do

const a = 1
a = 2 // error!

but this is fine

const obj = {}
obj.newProp = 1

Check out Object.freeze if you want to prevent the value (objects, specifically) from being changed.

3

u/[deleted] May 29 '19

But even Object.freeze won't freeze deeply - i.e,

const obj1 = {
  obj2: {
    foo: "bar"
  }
}
Object.freeze(obj1);
obj1.obj2 = {foo: 'baz'} // noop 
console.log(JSON.stringify(obj1)) // -> {"obj2":{"foo":"bar"}}
obj1.obj2.foo = 'baz' // legal.
console.log(JSON.stringify(obj1)) // -> {"obj2":{"foo":"baz"}}

This is why the Immutable.js library is a thing.

→ More replies (1)

1

u/MeowTooMovement4Cats May 28 '19

Nice! But why is it called constant by reference? In other languages like C++ you can’t reassign the constant variable nor can you change the property of the object it is assigned to whether it is constant reference or constant value?

struct Ob { int i = 0;};

const Ob foo;

foo.i = 1; //error

foo= Ob(); //error

Ob bar;

const Ob &zoo = bar;

zoo.i = 1; //error

45

u/Mydrax May 28 '19 edited May 28 '19
  1. The importance of using the Chrome DevTools.

  2. Why Linters make your life easier.

  3. Proper error handling (mostly writing code that doesn't fire errors).

  4. Being unable to fully understand or explain the 2 pillars of Javascript: Functional programming & Object Oriented Programming.

  5. How important it is to refer to the bloody documentation before hopping on stackoverflow.

  6. That not all tutorials, all books and all individuals relay accurate and most up-to-date information.

  7. bind(), call() and apply()

  8. High-order array functions like map() and specially reduce(). (It's very rare to see beginners use reduce() at all).

  9. The this keyword and I don't really know why but some beginners tend to find it difficult why you call super() inside the constructor of a child class.

  10. The Shadow DOM, it's not something you'd expect someone to know but it's ideal to learn about it after learning about the DOM and DOM manipulation.

  11. Promises, the for/of loop, async/await , callbacks etc. etc. or writing asynchronous code, and handling/catching errors properly.

  12. Destructuring and Spreading.

  13. Garbage Collection.

  14. Closures.

  15. That stackoverflow is the solution to all your problems.

I think that's a pretty constructive list of the common and more difficult things that beginners don't really know or can't understand. Some of them don't have to do anything with JS but hey!

19

u/snifty May 28 '19

Re 1), personally I think Firefox devtools are better.

1

u/jseego May 29 '19

I think so too, except that they are a hog

→ More replies (3)

3

u/DerGernTod May 28 '19

Being unable to fully understand or explain the 2 pillars of Javascript: Functional programming & Object Oriented Programming. one more thing that probably fits into #4 of your list: the prototype chain

1

u/Mydrax May 28 '19

When you learn OOP in JS, you will indefinitely come across the prototype chain, won't you?

2

u/DerGernTod May 28 '19

true, but i think it's worth mentioning that OOP in JS is vastly different from OOP languages such as e.g. java. understanding the concept of the prototype chain is imo more important than learning the syntactic sugar keyword class and what it does (i agree a lot with kyle simpsons opinion on this, it's very misleading for people coming from different programming languages)

→ More replies (1)

2

u/simkessy May 28 '19

Garbage Collection?

2

u/FlandersFlannigan May 29 '19

Good list, but I don’t use bind, call or apply very often. Am I missing something?

→ More replies (1)

10

u/doublemooncoffee May 28 '19

Great thread. Thank you reddit.

My contribution: You can group console logs by using console.group. You can even style them! Check out other methods here: http://developer.mozilla.org/en/docs/Web/API/console

28

u/DerGernTod May 28 '19

coercion in general

false == 'false' // false
false == '' // true
false === '' // false
var x = false || 'foo' // x is 'foo'
var y = true || 'foo' // y is true
var z = y && x // z is 'foo'

45

u/[deleted] May 28 '19

Most of these have nothing to do with coercion.

I guess you're right about people struggling with it.

16

u/[deleted] May 28 '19

let me end all your struggles:

the only time you use == instead of === in JS is when you do yourVar == null because this checks for null and undefined.

→ More replies (11)

2

u/DerGernTod May 28 '19

i agree only the first two have something to do with coercion, the latter were rather some other things js noobs may be confused about.

→ More replies (1)

19

u/zephyrtr May 28 '19

Reduce. A many to one relationship is way more verbose to manage without it.

4

u/ThatSpookySJW May 28 '19

Also all those nifty higher order functions like map, sort, and filter

0

u/[deleted] May 29 '19

[deleted]

1

u/zephyrtr May 29 '19

Well at least they filtered before they mapped, but yes that grinds my gears. Especially since it's so easy to rewrite: if (filterFunc(item)) accumulator.push(mapFunc(item)); return accumulator;

9

u/bobslaede May 28 '19

Don't try to be clever. Write code that is easy to read and understand.

24

u/[deleted] May 28 '19

Mutability/Immutability of Objects and Arrays. Learn about what changing an existing object means compared to making a copy of an existing one.

16

u/DerGernTod May 28 '19

IIFEs are a concept not really well known in other programming languages, yet they've been quite common in js, especially when working with closures. however, as of const and let they mostly lost their right to exist :D

4

u/dance2die May 28 '19

I've had so much struggle when I first learned JavaScript because it was used everywhere but without mentioning exactly what that pattern is and how it's used.

3

u/[deleted] May 28 '19

They're great for writing one-off scripts with a lot of async stuff using async/await :)

3

u/senocular May 28 '19

I think requiring the use of async was the only time I've ever used an IIFE in the past couple of years. Was never a fan of the pattern, and with top level await I may never use it again :)

7

u/Jackrussell17 May 28 '19

Equality in JavaScript is very convoluted, e.g. an array containing a single element of value "0" is considered == false, but an array containing a single element of value "1" is considered == true.

So it's really best to try to use === and !== where possible, only using == and != where absolutely necessary. Things are more predictable that way.

See this table for a full rundown: https://dorey.github.io/JavaScript-Equality-Table/unified/

7

u/jisscj May 28 '19

Hoisting. This was the thing that puzzled me most coming from C and Java.

24

u/amdc !CURSED! May 28 '19

Writing code without JQuery

11

u/senocular May 28 '19

I'm noticing this isn't the case as much anymore. In fact, if anything, this might have already transitioned over into "Writing code without React" - at least as far as DOM manipulations go. Those who know jQuery mostly seem to be in the boat of "I used it a few years ago, but am rusty now" while those without any of those "years ago" seem instead to know how to do things in React but not with the built-in APIs.

1

u/TheCarnalStatist May 28 '19

I'm far more likely to see folks reengineering problems that can easily be solved with jQuery than i am folks who use it too much

5

u/ingrown_hair May 28 '19

How modules work. It’s straightforward enough, but there’s a lot of stylistic variation you’ll see when reading other people’s code.

5

u/boopbopbeeps May 28 '19

How to use dev tools to inspect their code, see available properties, set breakpoints, etc.

5

u/nullvoxpopuli sand was never meant to think May 28 '19

Where JavaScript ends, and libraries or frameworks begin

4

u/dwighthouse May 28 '19

Named function objects can both be referenced by the contents of the function and have property values attached, allowing for the generation of function instances that have unique data associated with them, like a closure might, but without an actual closure.

1

u/magical_h4x May 28 '19

How do you reference a function object by the contents of that function?

1

u/dwighthouse May 29 '19

I created some code to show how, and explain it:

https://jsfiddle.net/zw2y3o1f/1/

4

u/Razvedka May 28 '19

How 'this' works. And the beginners shouldn't feel bad about it, as that shit is mighty strange when first exposes to it.

3

u/tridiumcontrols May 28 '19

Scoping and the "this" keyword.

3

u/iamlage89 May 28 '19

Everything is an object, even functions

1

u/senocular May 28 '19

Kind of, but not really. Primitives aren't objects but do get autoboxed when you try to use them as one. undefined and null are also explicitly not objects nor get boxed.

3

u/Weshguillaume May 28 '19

How to produce clean and organized code in JavaScript is the hardest part. Beginner's code is usually a mess

5

u/hkd987 May 28 '19

Bracket notation and why/when to use it.

5

u/zayelion May 28 '19
  • You can do most things without a **** framework.

  • Objects do not have Array prototypes on them. People coming from PHP I've noticed have this issue.

  • Cohesion in general. People coming from strictly typed languages having a tendency to want to mutate types of things. Then blame the language. You cant do that in other languages and the code work, I dont understand why they think they can do it now.

  • JS has debuggers.

  • Callbacks, promises, and await/async, and when it is the best use cases to use each.

  • That arrow functions and function keyword are not interchangeable, they have different interactions with `this`

5

u/pm_me_cute_rem_pics js/ux May 28 '19

that:

const catObject = {
    type: 'cat',
    attributes: {
        hasFur: true
    }
}

const copy = Object.assign({}, catObject)
// Or
const copy = { ...catObject }

will not create a copy of the nested object attributtes, it's still a reference to the original object. So changing the attributes object will change it for all copies.

example https://repl.it/repls/FloralwhiteGruesomeSystemcall

3

u/aragonix May 28 '19

Great response! Just wanted to add that one can JSON.parse(JSON.stringify(catObject)) to deep clone simple objects. Note that this method has its downsides: it will ignore all values that dont exist in JSON (functions etc.). Most of the time I would suggest lodash though.

5

u/[deleted] May 28 '19

That Java is not the same as Javascript

6

u/IamAPengling May 28 '19

JavaScript variables are passed by value, but objects are passed by reference.

This means if you do obj1 = obj2, there is a high possibility that if your change the value of any variable inside obj1, it may change inside obj2 as well and vice versa.

The correct way to fix this is Object.assign(obj1,obj2).

4

u/[deleted] May 28 '19

This is poorly written.

If obj2 is an object or an array, changes in obj1 will change obj2 since obj1 will just be a reference to obj2. Any primitive value such as numbers, strings, and booleans are not passed by reference.

Object.assign does not assign the obj2 to obj1, but assigns all properties of obj2 to obj1. This is very different than obj1 = obj2 since obj1 must be an existing object and will have references to any object in obj2 as well as copies of primitives, AND whatever was in the original object that hadn’t been assigned from object 2.

3

u/tomius May 28 '19

You're right. It should be

const obj2 = Object.assign({}, obj1)

→ More replies (3)

2

u/troytirebiter May 28 '19

Object creation and what the “new” keyword actually does.

2

u/Andy101493 May 28 '19

Have a style guide/best practices outlined for the JS code you write. JS will let you get away with a lot of weird things without causing an error, but may not function in the manner you expected.

I personally do a lot of console.log() lines to ensure functions are doing what they should during development. This isnt a profound realization, you should always be testing your code as you go. you know, unless you want to code in challenge mode.

This is not my content, but check out this post for some examples of "weirdness"

https://blog.mgechev.com/2013/02/22/javascript-the-weird-parts/

2

u/PotaToss May 28 '19

How much bang for your buck you get from just knowing your operators, like conditional evaluation of expressions when you use boolean operators, and what those operators actually evaluate to (i.e. their operands, not true/false).

With that, destructuring, spread, and array functions like map and reduce, you can be very expressive with very little code.

It's double edged, though. Another thing beginners don't know is how important it is to comment very expressive code.

2

u/Danieliverant May 28 '19

References. Like when passing a reference to an object to some function and you cannot understand why the original object changed.

2

u/Danieliverant May 28 '19

That 0.1+0.2 !== 0.3.

2

u/Squigglificated May 28 '19

Use MDN as your primary documentation for anything JS, CSS or HTML. And while you’re there spend some time clicking around and you’ll learn a ton of useful stuff you didn’t know was possible with native browser APIs.

2

u/MeowTooMovement4Cats May 28 '19

Prototypal inheritance vs. classical inheritance

2

u/[deleted] May 28 '19

If you declare a var in a for() loop without intializing it to a value, once the value gets set it gets retained for subsequent iterations through the loop:

for (var i = 0; i < 3; i++) {

    var foo;

    if (someCondition()) foo = i;

    if (foo != null) {

        // This will be true if someCondition returned true in this loop

        // OR if it returned true in an earlier loop

    } 

}

2

u/erulabs May 28 '19

Using abstraction libraries should be carefully considered, not thrown around like a favorite set of tools. The number of times I've seen Ramda in a code base that used to be readable...

Bonus: Understanding the cost of simplicity over artifact size. I've had developers spend multiple days pulling out lodash and inlining 1/8th of it into the codebase to "reduce node_modules size". The size of node_modules is fine, please get back to work on things that matter (I promise a single unsanitized input is always worse than making an AWS machine with a 10gbps network card download 10mb - trust me, it will be FINE). No one seems to care about that SQL query that's shipping 50mb over the network, but 50mb of node_modules and suddenly everyone loses their minds!

</grumpy-ops-rant>

1

u/aot2002 May 28 '19

They could always use npm-lazy if they want to cache it for multiple machines.

1

u/erulabs May 28 '19

npm-lazy

Haven't heard of this, but yarn already caches properly - the install time is very short, but for some reason the size of the directory comes up continually. No one seems to bat an eye at my Packer build which apt-get's about 3gb of applications - probably because they aren't aware. Anyways, my point is some Node developers tend to think of dependencies as a bad thing that should only ever be used in extreme need - getting the work done is always more important than bundle size. I can reduce bundle size easily - what I can't do is guess why you wrote your own file-system abstraction or Promise system, 6 months after you've quit and found a new job.

2

u/[deleted] May 28 '19

These threads give me anxiety cause even if it's something I know about, just seeing the highly upvoted comments makes me question whether or not I actually understand it. Then again this is titled begginers.

2

u/[deleted] May 29 '19 edited May 29 '19
  • When to use the Object Oriented model and when to use the Functional Model. (Short summary: If you have a thing that's going to persist, but need to change state, and don't know what actions are going to be done on it until runtime, lean towards object-oriented. If you need to do the same action multiple times to different things, lean towards functional.)

  • Currying. Not that they don't know *how* to curry, but how currying makes things SO much easier once you really get the hang of it -- dependency injection, differentiating between prod and dev databases without having to write a whole bunch of if(isProd){} statements, creating higher order React components, allowing you to use parameters in React's render method...

  • Pointers. Yeah, JS doesn't *use* pointers the way that C, C++, or Rust might use pointers, but under the hood, that's what you're doing when you "pass by reference" vs. "passing by value". Learning a bit of rudimentary C helped me avoid a lot of hard-to-debug "Oh, I'm not copying this, I'm changing it!" bugs.

  • Monads. Eh, don't worry, I'm not going to force you to learn Haskell, but understanding Monads helps you understand what's going on with Promises behind the scenes. One of the big tricky bits of Promises is that Promise.then() always returns a Promise, which is easier to understand if you've fooled around with Identity(val).map(fn).value() and Maybe.of(val)

  • get() and set() - and I'm going to be very controversial here. I think get() and set() should *never, ever be used*, because it can turn a simple assignment of the type

obj.foo = obj2.bar

into a debugging nightmare. If there's a get() on obj2.bar, any arbitrary code could be executed by that assignment. Same if there's a set() on obj.foo.

Now, I know without get() and set() you can't have things like observables, and that it's more difficult to have pub/sub or reactive programming. But is it really that much more difficult to call this.setFoo() or this.getBar() if you need to execute additional code? At least then in the actual code, you give a hint to the programmer that there MAY be something else going on in the assignment - if you know that one of your variable assignments is throwing off a side effect, you have to debugger() until you narrow down the part of the code the side effect is in, and look at each variable assignment (and it still won't be obvious.) By requiring as standard style that anything that executes any code other than a simple get or set be an explicit method call, you can more easily see where errors are introduced. This is one of the reasons I prefer React to Vue (and I love Vue) - Vue's use of observables can make it very easy to get tripped up. (I think Moon.js to actually be a better solution to how Vue works because of it.)

The only time that I can see justifying the use of get() and set() if it's something like

class Distance {
  inMiles = 0
  get inKm(){
    return this.inMiles * 2.2
  }
  set inKm(val){
    this.inMiles = val / 2.2
  }
}
const d1 = new Distance();
d.inMiles = 1;
console.log(d.inKm) // -> 2.2
d.inKm = 22;
console.log(d.inMiles) // -> 10

and even THEN I'd prefer:

class Distance {
  _inMiles = 0
  getMiles(){
    return this._inMiles
  }
  setMiles(val){
    this._inMiles = val;
  }
  getKm(){
    return this._inMiles * 2.2
  }
  setKm(val){
    this._inMiles = val / 2.2
  }
}
const d1 = new Distance();
d.setMiles(1)
console.log(d.getKm()) // -> 2.2
d.setKm(22)
console.log(d.getMiles()) // -> 10

2

u/Slypenslyde May 29 '19

Booleans have four states.

You need to use === unless you have a really damn good reason.

2

u/Caffeine_Monster May 29 '19

Variables declared with "var" are scoped to their encapsulating function (or global if not encapsulated). You should be using the "let" keyword for most, if not all, declarations.

2

u/FlandersFlannigan May 29 '19

Promises and loops. If you run a map in a promise it will run concurrently, so make sure you have the bandwidth.

6

u/j4afar May 28 '19

Bind and the this keyword

→ More replies (3)

3

u/Hanlonsrazorburns May 28 '19

Promises, ES6, Vanilla JavaScript, Dom manipulation without jQuery, closures, monads, design patterns, event cycle, prototypes.

I'd bet most developers with less than 3 years of experience would struggle with questions on those.

I'd also say that I think the biggest one is that they can't think through a problem logically considering edge cases. Many senior developers can't even do that.

3

u/unixzii May 28 '19

Whether my code could run in IE 8 without being transpiled by babel.

2

u/_brym May 28 '19

Don't start out using libraries or frameworks. If that's where you want to go, go for it. But try to really understand the fundamentals first.

1

u/muussis May 28 '19

sort() without function expression will sort by string, even if you have an array of numbers

1

u/BehindTheMath May 28 '19

How to debug and step through your code to find bugs, instead of just adding a log of logging.

1

u/CARFREESINCE84 May 28 '19

This is arbitrary if you dont work with ethereum, but if you want to make ethereum dapps, you should know that javascript timestamps are millisecond-based, and ethereum timestamps are second-based. You do not know the pain i went through to discover i needed to multiply my ethereum block timestamp by 1000 to get the right value in javascript

1

u/[deleted] May 28 '19

Why this refers to the constructor in a static context

1

u/richieahb May 28 '19 edited May 28 '19

The idea of references. This comes up in so many places:

  • Mutability (and all the associated CS concepts that go with it: pure functions, race conditions etc.)

  • Triple equals equality on objects (which compares their references) an example being: a lot of React (although by no means only React) uses memoization for performance gains and comparison of references (functions, props.children, other objects) is the first place memoization usually fails

  • Garbage collection (and related memory leaks from things not being GCd) and things that build on this like WeakMaps and WeakRefs / FinalizationGroups (the latter currently just being a proposal).

  • Passing by value / reference to functions

  • The reason that there is both let and const.

I’m sure I’m missing some places!

1

u/[deleted] May 28 '19

Accounting for manipulating primitive vs class data types.

1

u/vodlin May 28 '19

Settimeout doesn’t guarantee your function will be called exactly at the timeout time. This is a minimum time after which your function will be invoked

1

u/jun-thong May 29 '19

The following will break, telling myFunc is not defined.
myFunc();
const myFunc = function(){ ... };

The following one won't trigger error.

myFunc();
function myFunc() { ...}

The first one is called "function expression", the second one is called "function declaration". Understanding the difference teach a lot about how js is interpretedby the runtime.

1

u/EastOfHope May 29 '19
typeof null === 'object'

1

u/[deleted] May 29 '19

You can create a date from pretty much any formatted date string without defining the format. Just like D = new Date(dateString). Very handy when comparing timestamps because then you can just call the getTime method on your date var and compare the time in milliseconds.

1

u/[deleted] May 29 '19

Once you go down that road, you will suffer in eternal pain.

1

u/examinedliving May 29 '19

How useful try, catch are, and how to use them

1

u/trouzy May 29 '19

concurrency

1

u/invalidusername119 May 29 '19

The way setTimeout works.

Eg: print 1 to 5 but wait for 5secs between each print.

1

u/DanielGarden May 29 '19

Generator functions and the yield keyword

1

u/wisepresident May 29 '19

getElementsBy.. returns a live collection

let divs = document.getElementsByTagName("div");

document.body.innerHTML = "";
console.log(divs);
-> HTMLCollection []

document.body.innerHTML = "<div></div>";
console.log(divs);
-> HTMLCollection [div]

No need to query again.

As such one might be inclined to remove classes like this, which won't work (as you are actively modifying the size of the array while you loop through it):

let divs = document.body.getElementsByClassName("myclass");

for(let i=0; i<divs.length; i++)
{
    divs[i].classList.remove("myclass");
}

You have to convert it to a non live collection:

let divs = new Array(...document.body.getElementsByClassName("myclass"));

for(let i=0; i<divs.length; i++)
{
    divs[i].classList.remove("myclass");
}

1

u/kor0na May 29 '19

That they should never use == unless they have a very specific reason for it. === is what you want.

1

u/[deleted] May 29 '19

There are effectively 3 versions of JavaScript: Client-side (in-browser), Server-side (Node) and Application/Compiled (TypeScript).

Bonus fact: Most employers don't know the difference, and will typically look for "Front-end Developers" with years of Node and TypeScript experience. It will make finding good work very difficult.

1

u/Standard_Canary2185 Jun 08 '24

is it good to know arrow functions and ternary ? im use to using the old fashion way

1

u/vscde_gtr_thn_jtbrns May 28 '19 edited May 28 '19

I see very few people know how to use the prototype keyword

Edit: Please ignore the autistic douche below here trying to fight over whether or not prototype is a keyword instead of the point of people not knowing how to use it.

11

u/[deleted] May 28 '19

yeah including you because first of all, that's not a keyword. Also trying to understand this bullshit isn't going to get you ANYWHERE in JS.

Source: I've written everything you can imagine in the past +10 years in JS and never needed that horsecrap.

1

u/Gravyness May 28 '19

Were just defining functions on the function itself instead of its prototype for 10 years? That's like avoiding using Promises because you can do things with callbacks.

→ More replies (9)

1

u/PointOneXDeveloper May 28 '19

Tagged template literals. Prototype chain.

0

u/[deleted] May 28 '19

That they should use Typescript instead