9 ms·
JavaScript fundamentals before learning React
- wild_preference 8y agoThis article has a lot to offer a JS + React beginner so it feels lame to reply to some tiny part of it, but this bit is a constant error propogated in the ecosystem: > Even though it is possible to mutate the inner properties of objects and arrays when using const, the variable declaration shows the intent of keeping the variable immutable though. let and const only control mutability of the reference. They say nothing of the value mutability. const then can only be a signal that you are not reassigning to the identifier. const is still useful as a default of course since reassignment is generally the exception. Maybe this is what they meant but the language used made it seem otherwise.
- Swizec 8y agoBeginners don't know about references. What you say is exactly what the author meant.
- rwieruch 8y agoAuthor here {: Yes, what you are saying here is what I meant. I didn't want to mix in the whole topic around "passing by value or reference" in this short teaser. Hi Swizec :wave: :)
- pygy_ 8y agoHi, Robin. Then you may want to say that `const` guarantees that the name will remain bound to that object. The great-GP is correct in that `const` has nothing to do with immutability besides that. It doesn't necessarily conveys an intent of inner immutability. It just states that whatever is in the variable will stay there until it goes out of scope. Using `const` whenever possible is good advice, off course.
- rwieruch 8y agoGood point, thank you for the clarification! Somehow I have always thought about showing the intent of keeping the data structure immutable when using const. I have changed it in the article. One more learning for me today :)
- Silhouette 8y agoI've found this is often a problem in languages that pass simple values by value but compound values like objects and arrays by reference. The meaning of a qualifier like const and the inference a reader can draw when they see it can fundamentally change depending on what type of value it is applied to. My experience has been that both the change in value/reference behaviour and the lack of total immutability guarantees when using a const qualifier on a reference type can be a source of bugs. Languages like C and C++ distinguish more explicitly between value and reference semantics, and likewise between constant pointers and [mutable] pointers to constant data. To some extent that removes those sources of bugs, at the expense of having to write more explicit but verbose types like `const SomeType &` instead of `SomeType` all over the place.
- ravenstine 8y agoIt's been astonishing to me how people switched from var to let, but seem confused as to when to use const. I use const wherever I can since it's more appropriate for non-changing variables, and it helps me more easily visualize how a variable is being used in a block. But in other people's code I see a lot of letting all over the place. Maybe it's because of those articles saying to use let instead of var, but glossing over const.
- deleted 8y ago[deleted]
- chocolatemario 8y agoIf you don't know about references, I feel like you shouldn't be touching react. React is quite easy to pickup if you have an understanding of JavaScript and the Dom. The tooling surrounding react is an entirely different story.
- BigJono 8y agoTo be fair, beginners should stay far away from most of the tooling around React. In-fact a lot of veterans should too. Most people only use stuff like Redux or Immutable out of habit rather than necessity, or as a crutch to constrain themselves away from bad habits that they shouldn't have picked up in the first place.
- allover 8y ago'const prevents reassignment' is a much simpler way of saying that. Mutability doesn't need to come into it.
- duncan-donuts 8y agoI agree with you, but I’ve cleared up this confusion with a number of colleagues. People coming from languages that have a truly immutable “const” find the keyword confusing in js.
- jaredklewis 8y agoYea, I think const in JS alludes to the way const works in C++. If someone knows java though, it can always be explained that const in JS is identical to marking a local variable as final in Java. More so than const, I was perplexed by the JS choice of the `let` keyword. Are there any other languages that use let for declarations that can be reassigned? Did BASIC allow lets to be reassigned? Can’t remember...
- andreareina 8y ago`let` in common lisp can be reassigned.
- mikekchar 8y agoWhile it is simpler, I think it's better that people actually understand the difference between a reference to a value and the value itself. "Pointers are hard" is a statement that many beginner programmers make, but if you don't understand the concept, you will always be limited as a programmer. And whether you say "can be reassigned" or "mutable" (which means exactly he same thing, BTW) it doesn't really matter. JS has some surprising mutability rules. Variable references can either be mutable or not (depending on const, let or var), however function parameter references are always mutable (which can cause much hilarity in some circumstances). Even values are a bit strange at times unless you understand what's going on under the hood. It's obvious that boolean or number values are immutable, but it's less obvious that string values are immutable; even more so since it doesn't throw an error (at least in V8) when you try to mutate them. You might assume that function values are immutable (how could you mutate it?), but because of closures, they are completely mutable (as long as the values being closed over are mutable). And, well, functions are also so-called "object" values in JS (which I still think is not a good idea, but I understand why they did it). While, it is more complex to discuss that separation, it's valuable when you get into more difficult discussions -- especially if you are trying to write mostly pure functional code, with a few non-pure bits for performance. You need to be able segregate the pure from the non-pure and if you are passing closures, for instance, it's super important to understand how mutating a value in one place can essentially infect something that you thought was pure.
- sbjs 8y agoI think this idea is propagated by Swift developers because that’s the only place I’ve ever seen const used this way at all, ever. That said I started writing articles on JavaScript and React and TypeScript in medium and please subscribe and check out my post history of you’re interested in this topic! I only did two so far but I plan to do one every day starting tonight, with this very topic!
- AETackaberry 8y ago> let and const only control mutability of the reference. They say nothing of the value mutability. const then can only be a signal that you are not reassigning to the identifier. Wouldn't this definition suggest that the value CAN be reassigned? The reference could be immutable but allow value reassignment, but is not the implementation of const.
- josephg 8y ago> The reference could be immutable but allow value reassignment, but is not the implementation of const. You can reassign values through a const reference in javascript. For example: const x = [1] x[0] = 2 // ok! This just doesn't work with primitive values, because primitive values are immutable and copy-by-value. So this works with lists but not strings (because strings are a primitive and thus immutable). Or, put in C++ friendly terms, javascript doesn't distinguish between pointer reassignment and value reassignment. It only has reassignment, which is illegal for const variables. Variables which hold non-primitives (lists, objects, etc) are actually pointers to those values. const does not affect the mutability of the value stored at the pointer.
- DonHopkins 8y agoPostScript actually stores read, write and execute bits in the references themselves! (Unlike the way Unix files store the access mode attributes in the inode itself, so all hard links to the same inode have the same rwx attributes.) So you can have a reference to a mutable PostScript dictionary representing a font or something, then go "dup readonly" to hand out a read-only reference to the same dictionary, so other code can't modify it, but you can still modify the writable font if you hang onto the original writable reference. You're allowed to change the execute bit of a reference with cvx/cvlit, but you can only downgrade the readability and writability of a reference with readonly, executeonly or noaccess. Since PostScript code is data (homoiconic), protected code in proprietary fonts can be read-only executable arrays. http://www.math.ubc.ca/~cass/courses/ps.html http://www.math.ubc.ca/~cass/courses/ps.html
- MacroChip 8y agoI think the author was going for something like "When you see a const, think twice before changing anything inside that const."
- rwieruch 8y agoHey, author here :) I am curious about your experiences using/learning React. Are there any other JavaScript topics which are important when starting out with React? Would be great hearing your opinion!
- rsyring 8y agoMay want to point out you are the author of the article. :)
- rwieruch 8y agoDone :)
- kansface 8y agoFormatting strings (template literals [1]) comes up frequently for constructing ids/refs/various other props. 1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- rwieruch 8y agoIncluded :)
- vga805 8y agohey there, nice write-up two minor things that you might include are 1: rest in the context of function args 2: short circuiting: e.g. `isLoading && <Loading />`
- rwieruch 8y agoIncluded. Thanks :)
- k__ 8y agoNice writeup! I wrote a tutorial that would be the next step to yours, called React From Zero[0] I try to teach React here with the basic JavaScript knowledge most people already have. [0] https://github.com/kay-is/react-from-zero https://github.com/kay-is/react-from-zero
- lmiller1990 8y agoI had the chance/experience to train a new team in Vue.js (and thus modern JS) which I imagine is similar to people learning React. I noticed the same thing as the author - the new JS frameworks are "all about JavaScript". Without a solid knowledge of how JS works, and ES6, learning any of them is difficult. When realizing this, the main things I focused on what getting people to understand JavaScript, _then_ start to make use of the framework's more powerful features. I also noticed a lot of people interpreting `const` as "you can not change this, ever". It is short for constant, after all.
- noir_lord 8y agoThis was my personal experience learning Vue, I didn't know as much about JS as I thought I did. I went back and started again filling in all the gaps I obviously had. A year later and the frontend for all my stuff at work is TypeScript classes over Vue components and the code is actually simpler to understand. I learnt something and the code got better, a win/win like that is rare ime.
- ggregoire 8y agoAnother basic ES6 trick that beginners usually don't know: handleChange = event => { this.setState({ [event.currentTarget.name]: event.currentTarget.value }) } So you can handle 10 inputs with the same handler.
- spiritcat 8y agojust blue my mind
- coltonv 8y agoThis is great, and a strategy I used a lot in my last code base. If you do this for statically typed JS though, you'll get either error messages or bad typing with lots of `any`s and weak type checks. Here's a great strategy to do the same thing with strong static types, like in flow and typescript: setTextField = (name: 'name' | 'email' | 'phone') => (event: InputEvent) => { this.setState({ user: { ...this.state.user, [name]: event.target.value } }); } setBooleanField = (name: 'isCool') => (event: InputEvent) => { this.setState({ user: { ...this.state.user, [name]: event.target.checked } }); } render() { <div> <input type="text" onChange={ this.setTextField('email')} placeholder="Email" value={this.state.user.email} /> <input type="checkbox" onChange={ this.setBooleanField('isCool')} checked={this.state.user.isCool} /> </div> } More verbose than the non-typed version, but simpler than declaring a function for every field with all the goodness of strong static typing.
- jvain 8y agoShouldn't the doFilter function use query instead of this.state.query? const doFilter = query => user => query === user.name;
- austincheney 8y agoThe biggest fundamental is that you only rarely need new (when forced upon you by a bad API) and you don't need this (not ever). That statement has worked well for me in this language. I know it causes many people to cry and get immediately angry. The bottom line is that they increase the verbosity (substantially) of code, they are completely optional, and they often compound code maintenance through a more convoluted flow control.
- Silhouette 8y agoI can understand not liking `this` in JavaScript, but it seems optimistic to say you never need it. If nothing else, you are bound to encounter large amounts of code that uses it, so being familiar with its behaviour is necessary to understand that code.
- DonHopkins 8y ago"... but it seems optimistic to say you never need it. If nothing else, you are bound to encounter large amounts of code that uses it" Wait -- JavaScript now supports "it"??! Can you iterate over "them"? At least it's not gendered, so you need to use "him" and "her" and "it" depending on the object's gender, or just keep everything in a collection so you can use "them".
- josephg 8y agothis also has some really fun rules that are useful for mad science sometimes. For example, you can recover the JS context's global value via this: (function() { return this })() In a browser this resolves to the window object. In nodejs it resolves to the global object. I've used this a few times to help write isomorphic javascript bundles, though its much less useful than it once was.