Been working with JavaScript on and off since 1998, and I still find tons of values in your videos. Kudos, Kyle, on these excellent tutorials-you’re a real community asset
So in case anyone wondered how decimal numbers can be represented in memory. If we push a 1 to the left, we double its value. If we push it to the right, it's going to be halved. So let's do it, starting with 1: decimal -> binary 1 -> 1 .1 -> 0.5 .01 -> 0.25 .001 -> 0.125 Need 0.75 in decimal? That's 0.5 + 0.25 so it would be .11. Now let's look at the famous 0.1 + 0.2 = 0.30000004. 0.1 (dec) is smaller than 0.125 (1/8) so we need the next 2^-x power, 1/16, that's 0.0625 (.0001 binary). We're left with 0.0375, which is a bit larger than 1/32 (0.03125 dec, .00001 binary). 1/16 + 1/32 is therefore 0.09375 in decimal (.00011 binary). We would need 0.00625 more to 0.1, we're getting closer to 0.1, but in this case, since 0.1 can't be a sum of 2^-x powers, you will reach the maximum number of bits threshold so your value gets truncated. Imagine if he had only 4 bits, the best binary representation for 0.1 would have been 0.0001, which is only 0.0625! 0.2 (dec) is larget than 0.125, so we have .001 for starters, we need 0.075 more, which is between 1/16 and 1/8, so we have 1/8 + 1/16 so far (0.125 + 0.0625 = 0.1875, .0011 in decimal). We would need 0.0125 next, which, again, is not a sum for 2^-x powers and 0.2 representation is again truncated. You get close, but never 0.2 exactly. This is why you're not getting 0.3 for adding 0.1 and 0.2, which also doesn't have an exact binary representation. 0.1 + 0.2 in binary is like adding 2 truncated numbers, the way you would do 975 + 210 in decimal, about 1000 + about 200, that should be about 1200.
I mean, for the "Binary Math" solution I would highly recommend using Math.round and just round the comparing values to 2 decimals or so. Or directly round the values after each math-operation to x decimals so you can then later compare them to 0.35 directly.
I would actually suggest using a library specifically made for dealing with decimals(like decimaljs or bigjs) - especially true if you're working with some financial data and rounding it would be rather risky.
@@huge_letters As always it "depends on the usecase". For financial data that could be worth a shot, but then again you are depending your financial data on some "dude" who has issues open since 2018 which haven't been closed. If you are too lazy to repeat "Math.round()" in your code, you should consider writing util functions yourself, so you drastically reduce the likelyhood of bugs. For example write a "sum([decimalsArray])" function that returns with a precision of 2 by default and can be adjusted by parameters. I also read somewhere that a new datatype is coming that will fix this, but i can't find any info on that so maybe I have faulty memory here...
I'm amazed that after so long of working in JS that I can still learn something new. This time around, the console Timer and debugger option :) Thanks for sharing!
I mean... labels are essentially GOTO statements. Sure, there are times when you want to use them, but they are usually a bad thing because it makes code less readable in more complex examples. For this first example, you can just use a "break" statement to break out of that inner loop.
@@TheGreatMcN GOTO statements are icky. I mean... it's what the compiler is ACTUALLY doing really low level... but yeah, I'd consider rearchitecting the code before using labelled gotos. Like, consider using functions and return statements.
Tip for those trying to compare equality on decimal arithmetic: Use subtraction and an epsilon. IE: let epsilon = 0.00001 (or whatever precision you like) and re-write your equality to if Math.abs(x-Comparison_Value) < epsilon { }. In your example it would be if (Math.abs(x-0.35) < epsilon) { // do stuff }
@@adtc Flooring will truncate the decimal part completely. So if you were to compare 0.9 with 0.3 with a floor it'd be equal. Unless I'm not understanding where you are using the floor function. Math.floor(0.9-0.2) === 0 -> true. But I think most would want that to be falsey
@@arjix8738 Int math is prefered, but not always an option, it will depend on the size of the numbers you are using. If you want precision to 6 decimal places, you'll have to multiply by a million and then divide at the end, which may or may not be ok. But in general, I do agree that if you know that your numbers are safely not going to overflow, that converting to int and back is the best. For money transactions, I leave everything in pennies (or cents or whatever) and then convert on the presentation layer.
That's a really bad idea as you can't assert that Number.EPSILON has a good enough tolerance. Example: Math.abs((0.1 + 0.2) - 0.3) < Number.EPSILON is true. Math.abs((1000000.1 + 0.2) - 1000000.3) < Number.EPSILON is false. Clearly the difference should be the same, yet the tolerance is insufficient. Your best bet when working with things like these would be to use a custom tolerance. The approach is sound, but relying on Number.EPSILON is not. It would also be possible to use Math.abs, multiply by 10^n and then Math.round to get an integer value, after which you can make an assertion. I haven't tested it extensively though, so I can't guarantee it works in all cases, but it's a possibility for some cases I can think of.
9:58 No, it's not hard at all. You can use Object.keys, Object.values and Object.entries to effortlessly loop through anything you want. Being able to use an object as a key is super cool though! Would be even cooler if object comparison wasn't such a pain in JS 😅
Objects should be used for storing data where your keys are pretty much static and known and well-structured - like you have a person entity which has a name, age, location etc. Map was made specifically for situations where you want a relationship between arbitrary number of keys and values. It's optimized such cases too. Object.keys, values, entries create a new object in memory on top of the one you already have.
Worth noting for the sake of other readers that code smell *does not* mean bad code. It's just a potential red flag, something to watch out for and be wary that it might be bad code. Labels are extremely useful when you need them, but overuse is definitely something to be careful of.
@@foxoninetails_ Actually is a smell of bad code. If you have to watch out for that chunk, it is bad, indeed, so you are obligated to put more effort into it in order to maintain the code base. Btw, the nested loop example is easy solved by function extraction (and you are allowed to *return* whenever you want to continue to the next iteration)
@@keenkidash7616 The term "code smell" does not and has never referred to bad code, except when used by people who have no idea what they're talking about. It was coined specifically to refer to code that is often, but not necessarily, indicative of bad design. Labels, like any other code smell, are not inherently bad, but rather should be used sparingly and thoughtfully. They are a valuable tool, but not one which should be used without good reason. And no, "the nested loop example" (which one? I'll assume the most common, breaking out of multiple loops) can't be trivially solved by function extraction. Labels allow you to break or continue from specific levels of a nested loop at any point inside them; to do so via function extraction, in more extreme cases, requires the inner functions to return some form of signal value which tells the previous function that it should also do the same, which becomes an unbelievable mess to manage.
The For labels seem like a great way of documenting what each of your loops is doing without having to use comments. Even if you don't use them in the execution itself. Just like good variable names avoid unnecessary comments.
I often make a helper function to create "enums" in JS (obvs. not real enums, but close enough for most uses). It just takes a list of strings, and then returns a *frozen* object that maps the strings to Symbols of the string, thereby ensuring that (a) they can't be changed, and (b) they are all unique values. Which is like 2/3 of the use of enums. So for instance, I could do: const Directions = make_enum('UP', 'DOWN', 'LEFT', 'RIGHT'); And the resulting frozen object would have unique symbols referenced as Directions.UP, Directions.DOWN, Directions.LEFT, and Directions.RIGHT.
For the loop variables: Is it not just easier and clearer to put the standard continue for i === 1 directly after the first for loop? This would directly increment the i counter.
The point of this was to show the feature, not to show a practical example. This is a feature with a pretty rare use case. It's difficult to come up with a good example until you actually have a use for it
@@purduetom90 I would make the case that break and continue are goto statements. But personally, I try not to use any for loops at all and use map filter and reduce instead
I love your videos, Ive been developing sites and software just as a hobby for over 25 years and been stuck in the old ways of doing things. I'm in the process of teaching myself angular and node and your videos are very helpful and easy to follow.
I have a video idea for you: do all the different Object methods such as Object.freeze Object.assign etc etc. I feel like I keep seeing new ones out in the wild
it's crazy how you apparently always shows some feature I'VE NEVER SEEN BEFORE! which is almost unbelievable to me since I've been around JS for a while lol!
Exactly what @prometheas said below, I still reference your videos after all these years over any other video. You get to the point and you get to the point fast! A+ my man!
A lot of this stuff is great with the exception of labels. Most likely you need to refactor some code to use a reducer if you are running nested loops.
well I definitely didn't know loop labels, so I guess this video actually wasn't clickbait, like all the other ones I've seen with a similar title :) good job!
The labeling loops was very cool. TIL. With that said thou, isn't there something about messing up control flow? Otherwise we could just be using goto instead of increasingly fancy breaks and continues, or even mid-loop returns.
Great video! For me personally, the Set was the big win. I didn't realize that it was in ES6, but it makes creating a unique array muuuch easier without the need for an external library. Simply `[...new Set(array)]` or `Array.from(new Set(array))`. Of course this is only for primitives where value comparison is trivial! Thanks for the help 🙂
the problem with 0.1+0.2 is not only a computer problem. It's also a programmer problem. They forget to round to the same precision of the source numbers. If you have 1 digit on source, you must round to 1 digit on the result (for a addition), so you HAVE to round 0.3000000000004 to 0.3 to stay in the same précision level.
The problem with 0.1+0.2 not equals 0.3 has been very very simplified in this video. Of course you can store 0.3 in binary. One not very effective but obviously possible solution would be as string. And some libraries that enables you to compute arbitrary big numbers (like BigDecimal in Java) do this. But since normally you want some nice compromise between precision, calculation speed and memory size, the primitive data types for floating point numbers are optimized for the most common use cases. They can store either pretty (but not alway perfect) accurate numbers or very big/very small numbers. But not both at the same time. So the real reason why most programming languages get 0.1+0.2 wrong is not, that if can't be represented in binary but that the representation used in most programming languages can't do it. Most programming languages (including JavaScript) use the IEEE 745 specification for storing floating point numbers. You can read all about it in the official specification (web.archive.org/web/20160806053349/www.csee.umbc.edu/~tsimo1/CMSC455/IEEE-754-2008.pdf ) or look on RU-vid for some videos that explain in in a more digestible form since the specification is 70 pages long. Storing floating point numbers efficiently really isn't easy ;)
Thanks as always, can think of a couple of situations where loop labels could've helped me a lot. Somehow feels like a bad practice thing that should be used rarely though
Another way to check number equality is to use Number.EPSILON. So if you want to see if 0.1 + 0.2 equals 0.3, just do: (0.1 + 0.2) - 0.3 < Number.EPSILON // true
So for binary calculations I always use function fix2(x) { return Number.parseFloat(x).toFixed(2); } This way I always have 2 (or as many as I specify) number of decimals.
If you do a lot of floating point comparison, you might be best making a nearly_equal function that does something like this: > nearly_equal = (a, b, ε) => Math.abs(a - b) < ε; [Function: nearly_equal] > nearly_equal(0.35, 0.34, 0.001) false > nearly_equal(0.35, 0.34998, 0.001) true > nearly_equal(0.35, 0.3500001, 0.001) true > nearly_equal(0.35, 0.354, 0.001) false Although, apparently, this is "wrong" according to this guide floating-point-gui.de/errors/comparison/, which offers a more complex and thorough solution if you really care about precision.
wouldn't "continue 2;" break out to the second level? I know it works like that in other languages, like php for allowing to break out of switch blocks inside loops
@@evilwizard7931 There are a lot of cases where the non-label approach just means setting a sentinel variable that the outer loop checks to decide when to break. But that gets a bit spaghetti when you have more than just two nested loops, so labels are better for that use case.
Very interesting stuff. I knew about some of these, but don't use it often. You explain it well and give good examples which makes it easy to understand, I will try to find use cases for these in my projects :)
Hey Kyle, is there any option to purchase just the advanced portion of the course? I already have a job as a full stack JS developer but I'd like to sharpen my skills with advanced knowledge
Regarding the fact that 1/10 in binary is a repeating decimal, I did the math and found out 1/10 = .0{0011} in binary, with the braces representing repeating decimals. 2/10 = 1/5 = .{0011}. 3/10 = .0{1001}.
At 16:30, that example is still a bad example. To check floating point numbers, you have to check for the detla difference. Something like : if (Math.abs(x - 0.35) < delta) where the delta is any precision of tolerence. For example, let's say the tolerence is 0.001, then : if (Math.abs(x - 0.35) < 0.001) will be true if x is between 0.3499 and 0.3501
Its not "much harder" to iterate over an Object compared to a Map, just use Object.keys, Object.values or Object.entries, and you will get an Array of the keys, values or key value pairs respectively. You can use Array.foreach, ...etc
If you're making heavy use of Object.freeze for functional-style programming, I'd also recommend an immutable data structure library like immer, which does a bunch of stuff behind the scenes to make things easier and faster