Today I Learned - Rocky Kev

Tagged “javascript”

  1. TIL what is npm Script

    Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

  2. TIL fancy methods to transform Javascript Objects

    You can use Object.entries(), Object.keys(), Object.fromEntries()...

  3. TIL how to hide your JS code

    ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.

  4. TIL Why is TextEncoder a class

    My assumed answer - it was for extension. What does reddit commenters have to say about it?

  5. TIL why google recommends you avoid document.write()

    By injecting it with code, it bypasses the preload scanner. This means that the browser can’t request this file until it’s actually run the '<script>' block that inserts it, which is very much just-in-time (and too late).

  6. TIL Using pseudo-classes in your querySelector!

    let notTuna = document.querySelectorAll('.sandwich:not(.tuna)')

  7. TIL using abortController to removing events

    Trying to unhook a eventListener? Don't use `removeEventListener`, instead use AbortController.

  8. TIL detecting if a user is online with JS

    You can use the navigator.onLine api.

  9. TIL prioritizing Javascript

    ... async and defer attributes should be used where possible to avoid render blocking of the DOM. Render blocking is when the browser must halt all rendering of the page in order to process a resource that the page depends on.

  10. TIL problem with AJAX

    Synchronous XHR is harmful for performance because the event loop and main thread is blocked until the request is finished, resulting in the page hanging until the data becomes available. fetch is a much more effective and efficient alternative with a simpler API, and has no support for synchronous fetching of data.

  11. TIL a helper to make things uppercase

    ucWords function converts the first character of each word in a string to uppercase. This function is the same as PHP’s ucWords function.

  12. TIL the core-js spam trolling

    This entire repo is a hilarious rabbit-hole when you combine this with everyone complaining about the console spam that the dev added to it asking if anyone can find him a job. One of my favorite PRs

  13. TIL Web Performance with Javascript

    Overall, we should be loading the most important JS first to get the website working. Then load all your third-party scripts onto your web worker, which then responds with 'Success' once it loads, so you can then interact with it.

  14. TIL Tagged Templates

    Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.

  15. TIL Multiple Fetch Requests

    I've been frequently dealing with this scenario in the past few weeks. I wanted to make multiple fetch requests, and then merge everything together when it's all done. To make multiple/parallel fetch requests:

  16. TIL Scoping with Cypress

    So you wanted to find a specific element called `heading`. But you have a BUNCH of elements called `heading`. By using `within()` helper, you can force it to only look inside `main` elements.

  17. TIL SolidJS reactivity

    SolidJS is a JavaScript framework that supports binding data to elements that it then syncs and displays on web pages.

  18. TIL Computed Properties in Javascript

    Today I learned about Computed Property names.

  19. TIL if TypeScript is worth it

    The answer: No, according to HackerNews. But HackerNews audience aren't exactly representative of average developers? From my perspective, they're the 'startup' and 'ship fast and break things' folks. (I mean, I am too!)

  20. TIL delta time

    Delta time, also known as 'time delta,' refers to the difference between the 'current time' and the 'last time' a piece of code was executed. In JavaScript, delta time can be calculated using the Date object or by using the performance.now() method.

  21. TIL finding the browser being used

    How to detect the browser you're using, with javascript.

  22. TIL Libuv

    Libuv also implements two extremely important features of Nodejs which are the event loop and the thread pool and in simple terms, the event loop is responsible for handling easy tasks like executing callbacks and network I/O while the thread pool deals with heavy work like file access or compression.

  23. TIL brackets breaking elements in JavaScript

    The 'automatic semicolon insertion' it does is an error correction process

  24. TIL RXJchess and how it was built

    How was this chess engine made?

  25. TIL Node.js Event Emitter

    This is kinda like the addEventListener() for browser javascript.

  26. TIL Double Exclamation shorthand for booleans

    JavaScript (and TypeScript) lets you convert a non-Boolean value to Boolean using the double exclamation shorthand. '!!'

  27. TIL how to delete all cookies with Javascript

    If someone selects 'Reject', you want to remove all the tracking cookies. You can easily clear all cookies stored in a web page by accessing the cookie using document.cookie and clearing it.

  28. TIL Sparse Arrays

    The ['Batman', , 'Bane'] array is a sparse array. See how it there is a blank?

  29. TIL accessing different data attributes

    You can access it in javascript using element.getAttribute('data-sandwich'). A better way is to go with the Element.dataset property.

  30. TIL Performance tests

    While doing performance tests, I was curious how long a loop was running. I used the performance.now() trick.

  31. TIL getting the height with Javascript

    Say you wanted the height of a element. getComputedStyle gets you that. BUT -- it may lie about it to avoid css history leak. Instead use computedStyleMap.

  32. TIL not using try/catch block with promises for error catching

    You shouldn't use a try/catch block inside the Promise Definition. Your promise is already doing that.

  33. TIL using proxies for reactivity

    A Proxy let you detect when someone gets, sets, or updates a property on an object, and run code when they do. But why? This usecase -- when you add/update the object, it also updates localStorage!

  34. TIL AggregateError

    I heard the term AggregateError in relations to 'Promise.Any', So it's several errors wrapped in a array. That's all.

  35. TIL adding a helper function for CSS classes

    I like this helper. This lets you quickly add/remove CSS classes to your elements in a easy-to-read way.

  36. TIL JS Cron and process.platform

    Cron is a tool that allows you to execute something on a schedule. This is typically done using the cron syntax. process.platform tells you what platform the user is running. For this usecase, if it's win32, use robocopy. Else use rsync.

  37. TIL the new Temporal API

    Temporal is a TC39 proposal for a non-sucky date time API

  38. TIL multiple ways to deal with extra 0s

    Dealing with lots of 0`s.

  39. TIL the difference between partial application and currying

    Partial application transforms a function into another function with smaller set of arguments. Currying creates nesting functions according to the number of the arguments of the function. Each function receives an argument.

  40. TIL the stack and heap

    The stack is a data structure that JavaScript uses to store static data. The Heap is Dynamic memory allocation, storing objects and functions. Garbage Collection.

  41. TIL loading third-party scripts onto service workers

    An alternative to self-hosting scripts would be using Service Workers to cache them. This can give you greater control over how often they are re-fetched from the network. This could also be used to create a loading strategy where requests for non-essential third parties are throttled until the page reaches a key user moment.

  42. TIL about why Node was invented

    Node.js applications never buffer data, which dramatically reduces the processing time of uploading files, such as videos or audios. In other words, it simply outputs data in chunks, meaning that, for example, a user can watch videos without any interruption.

  43. TIL How to implement two-way binding without a framework

    One of the reasons we use React or Vue is because of that sweet sweet two-way binding. It's the automatic syncing of data between the model (data) and the view (UI) in both directions. Any changes made to the data will automatically update the view, and any changes made to the view will automatically update the data.

  44. TIL Event Delegation

    Event delegation is one of the most helpful patterns for DOM events! Adding too many event listeners means JavaScript is storing it all in memory. Event Delegation lets you store one listener, that then looks for the target.

  45. TIL what matters for JS optimization

    Optimizing your Javascript - Using getElementById() vs querySelector()? Doesn't matter. Loops? Doesn't matter. What matters: Render Blocking code, Repaints and Reflows, Memory allocation

  46. TIL that the max size of a Map/Set is 26843544

    JS Maps and Sets are implemented by OrderedHashTable. OrderedHashTables double in size when they need to grow, and their max size is 26843544. After 16777216 elements, doubling that exceeds the max, so the allocation fails.Currently these data structures are not implemented to be usable for large in-memory datasets. Also note that the JS specification itself doesn't require that Maps and Sets must scale with available memory.

  47. TIL A practical Curry Example

    Currying is a programming technique where you take a function with multiple arguments, and you turn it into smaller sequential functions where you pass one argument at a time. But many use-cases kinda suck

  48. TIL the difference between single-threaded & multi-threaded architecture

    For web dev, we don't need it. We're not bottle-necked by the processing power. We're instead bottlenecked by the ability to read files/databases. We can simulate multi-threading (and improve our app's performance) using async/await.

  49. TIL how outsiders see Javascript

    The bane of my existence - 'SyntaxError: Cannot use import statement outside a module'

  50. TIL Prototypical Inheritance vs return functions

    When to use proto versus return functions?

  51. TIL a code snippet to check if the value is of type

    This short snippet helps us check!"

  52. TIL using defer/async

    So an old and often-touted best practice for performance has been to load your JavaScript in the footer of the document to avoid render blocking of scripts. By putting it in the footer, the DOM is constructed before your scripts have a chance to run. That's dumb.

  53. TIL about console.dir

    If you console.log a element, you will get it's HTML markup. If you want it as a JS object, use console.dir instead

  54. TIL Replace Only Fixes the First Encounter

    Replace only finds the first occurrence. ReplaceAll fixes it all.

  55. TIL Optional chaining broke his mom's site

    Modern browsers get all fancy new features. But what about still-working technology like 1st-gen iPads and old chromebooks that no longer get updates?

  56. TIL Cherry-picking out of bootstrap-vue

    If you are using a component library that uses ES modules like bootstrap-vue, you can cherry pick its components instead of just registering all of them globally.

  57. TIL Avoiding promise chains

    Callbacks are functions that are executed when another function finishes. It can lead to callback hell, which instead, use a promise! But don't make promise chains

  58. TIL use-cases for Generators in Javascript

    Generators are functions that can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.

  59. TIL Memoization performance

    Memorization in a nutshell: You catch the data if it exists already.

  60. TIL filtering DOM elements when you web-scrape

    I love web-scraping. One core technique you have to master is stripping HTML from a string.

  61. TIL event bubbling

    Event bubbling is when an event is in an element inside another element, and both elements have registered a handle to that event. That cause collisions.

  62. TIL about the proposed pipe operator

    In functional programming, you chain functions to provide a result. Witht he Pipe operator, it can look like this: const total = money |> removeOneDollar |> addTwoDollars |> addFiveDollars

  63. TIL different ways to inject content via Javascript

    There's lots of ways to do things in Javascript. It gets difficult to know which way is the 'preferred' way.

  64. TIL using Event Delegation

    It's cheaper for the browser to track one event and fire it on every click that it is to manage multiple events.

  65. TIL Why use Closures

    Now you might be asking, why even use it? Why not just flatten it out so it's just one function with one return statement?

  66. TIL the difference in the JS Event Loop for Browsers and Node

    It took me years to understand this. Someone saying that 'they use Javascript' could mean they use Javascript on the web, or Node, or a different Javascript environment, of which there are MANY!

  67. TIL Promise Constructor edge-case

    The promise constructor has to do a few more workarounds in order to catch errors. Just use a then statement

  68. TIL more Javascript Environments

    This is back to why Web Interop exists! Because we have a specific Javascript standard (via ECMAScript Language Specs, by the TC39), and many many different companies/businesses who implement Javascript.

  69. TIL High Resolution Time

    The Date object is no longer the recognized method for timing events because it is very imprecise and can be modified by the system clock.

  70. TIL Number formatting with Javascript

    Say you wanted to convert this into a string, with all the commas and everything. You can use the browser Intl package to use this.

  71. TIL refactoring object lookups to avoid looking at the prototype chain

    Depending on your lookup method, you can access the prototype chain, which opens up some potential vulnerabilities or terrible side effects!

  72. TIL tips for making a API Wrapper

    The API wrapper should do zero 'interpreting' (or as close to zero as you can get).

  73. TIL about heavy.js

    It downscales all images on your webpage by a factor of 3, takes the RGB values and creates spans with appropriate styles. Yes, this converts your images to HTML p and spans.

  74. TIL about semaphores

    A semaphore limits access to a resource to some number of consumers. Any new requests for the resource will get stalled until later, eventually to be handled.

  75. TIL cancelling promises

    There is a cross-platform (Node, Browsers, etc) cancellation primitive called AbortController. You can use it to cancel functions that return promises rather than promises themselves.

  76. TIL the WebCrypto API

    If you dealing with sensitive applications and need a more secure method of randomization, I’d recommend the Crypto API. Reasons you may want to use WebCrypto include temporary verification codes, random password generation, randomized lottery numbers, etc.

  77. TIL another way to prevent buttons from submitting HTML

    When you have two buttons, you can use 'type=button' to stop them from submitting a form.

  78. TIL ES6 Proxy's apply method

    Using JavaScript proxies you can wrap an existing object and intercept access to its attributes or methods, even if they don’t exist. You can also redefine fundamental operations for that object.

  79. TIL ES6 Proxy

    Using JavaScript proxies you can wrap an existing object and intercept access to its attributes or methods, even if they don’t exist. You can also redefine fundamental operations for that object.

  80. TIL about the Clipboard API

    The Clipboard API can be used to implement cut, copy, and paste features within a web application.

  81. TIL how to explain Typescript like i'm 5

    Typescript is quickly becoming a powerful tool for Javascript developers. Typescript provides optional static typing.

  82. TIL a short explainer of the Execution Context

    It is an abstract concept that represents the environment in which JavaScript runs. What happens inside the execution context is two things basically. The first is parsing the code line by line and the second is storing the variables and functions into the memory.

  83. TIL about this work of beautiful code

    I'm a strong believer in writing code for tomorrow's developer. I'm incredibly anti-code-golf. (It's a beautiful art form, but keep it out of production code!)

  84. TIL addEventListener's third param

    The mysterious useCapture and options.

  85. TIL adding an Event Listener to document

    When an element in the DOM is clicked, the event bubbles all the way up to the parent element (the document and then the window). This allows you to listen for events on the parent item and still detect clicks that happen inside it.

  86. TIL what jQuery's role is today

    Today’s JavaScript frameworks allow us to break the UI into components, making it easier to scale up an application. It creates abstractions for easier synchronization between the data and the view. We don't need to hack the DOM element directly, and instead let the framework handle it.

  87. TIL the history of jQuery

    With the launch of jQuery in 2006, web developers were able to access and manipulate DOM and CSS faster and easier than ever before.

  88. TIL obvious security vulnerabilities and prototype pollution

    Object-based inheritance gives JavaScript the flexibility and efficiency that web programmers have come to love – but it also makes it vulnerable to tampering. Malicious actors can make application-wide changes to all objects by modifying object, hence the name prototype pollution.

  89. TIL the different Javascript Engines

    There's dozens of JS engines. V8 ,Chakra, Spidermonkey, JavascriptCore Webkit, JerryScript...

  90. TIL about what causes Memory leaks in Javascript

    As long as it is possible to reach it, keep it. Everything else gets yeeted.

  91. TIL JS in Google Sheets

    I like this because I do use a lot of Google Sheets, and I write a lot of Javascript. And together, they can be a quite a force to be... calculated.

  92. TIL how Node/V8 works with imports/exports

    This is accurate only up to how JS works in Chrome-based browsers, and NodeJS, as Node uses V8 under the hood. But overall, it's referencing vs live binding

  93. TIL about Micro-frontends

    Micro frontends are a new pattern where web application UIs (front ends) are composed from semi-independent fragments that can be built by different teams using different technologies.

  94. TIL of the difference between || and ??

    The difference between || or ??

  95. TIL about more examples of currying

    Currying is nothing more than a way to transform functions that accept multiple parameters into a sequential list of functions that take only one parameter each.

  96. TIL some more examples of closure

    Five benefits- Private variables and methods. Data hiding and encapsulation. Currying. Function Factories. Performance

  97. TIL about Partial Hydration

    Partial rehydration is an extension of the idea of progressive rehydration where individual pieces of a server-rendered application are 'booted up' over time. This contrasts with the approach of initializing the entire application at once.

  98. TIL what Single Threaded & Non-blocking means in JS

    Javascript is a single-threaded language. This means it has one call stack and one memory heap. Non-blocking means it'll read from top to bottom and throw anything async in the queue.

  99. TIL how to create a delay snippet for JS

    We check for any user interaction. The 'eventList' array has eventlisteners, listening to those movements. Or we wait 5 seconds. Then Switch the 'delay' attribute with 'src' attribute. Run the 'cookie.js' code!

  100. TIL about the element.closest() method

    Using a single event listener is super efficient, but has edge-cases. So using closest instead of match.

  101. TIL some JS tree traversals

    Ah, DOM tree traversal. It's the adventure that keeps on giving.

  102. TIL about switching out of JS Classes and into JS Modules

    A classes are just blueprints for creating objects. A class encapsulates data and functions that manipulate data. A module is a file that exports features, such as variables, objects, and functions, that can be used elsewhere.

  103. TIL about the End of Time! (for Unix)

    On January 19th, 2038 at precisely 03:14:07 UTC, instead of the clock going to 03:14:08 UTC, it will overflow and go to 20:45:52 UTC of December 13th, 1901.

  104. Grouping console messages together

    You can wrap console messages together using console.group('name') and console.groupEnd('name')

  105. TIL about console.assert()

    You can instead use console.assert() to show conditional errors

  106. TIL about wrapping a variable in curly brackets

    Output the key:value pair using curly brackets

  107. TIL how to replace many characters in javascript

    You can use the replace() method to swap one string pattern for another.

  108. TIL about getting how long it takes for JS to execute

    This post took me 7.22 minutes to write.

  109. TIL Spreading a object into another object

    It's copying an object into another object, while also adding a new input.

  110. TIL about the Broadcast Channel API

    Think of a use-case like, once you logout from an app running in a browser tab, you want to broadcast it to the app instances opened in other tabs of the same browser.

  111. TIL ELI5 for Async Await

    If you make a call to a friend across the world, it'll take 20 seconds before they respond. You can't just wait 20 seconds. So you run other code.

  112. TIL that 2^24 items will cause a interesting error

    Obviously there's not much real use-cases. But that's the fun of finding limitations.

  113. TIL about the Image Capture API

    The Image Capture API which helps us to capture an image or grab a frame from the video devices(like webcam). Not only that, you can also perform actions on capturing an image or grabbing a frame.

  114. TIL of this switch shorthand

    Using a switch statement to fire a function? Nah, just fire it.

  115. TIL Numeric Separators

    This is spicy ES2021, and super useful for big numbers.

  116. TIL how to convert a nodeList into an array

    You can use the spread operator to turn a nodelist into an array!

  117. TIL how to pass unlimited arguments to a function

    The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript.

  118. TIL using live regions for autocomplete accessibility

    However, the screen reader does not recognise this as an action to tell the user about. It will announce the header and the input box when they gain focus, but not the search results.

  119. TIL how to get the location of the user with the Geolocation API

    You can get the user's location in the browser. First, the user has to accept this. As it's a security request. Second, you use the Geolocation API.

  120. TIL of someone who missed all the JS pitfalls

    If JS doesn't do it the way they think it works, then... JaVaScRiPT is STUPID!

  121. TIL about the new Intl.NumberFormat browser API

    No more stupid-ass hacks to format numbers correctly.

  122. TIL more scary floats in Javascript

    using floats with parseInt can cause unexpects side effects

  123. TIL startWith

    Getting a boolean result of true or false, depending on if the string startsWith a specific substring

  124. TIL a quick recipe involving Axios and Cheerio

    A quick recipe to http request an api and use cheerio to web-scrape it

  125. TIL end all node processing scripts

    killall node - a sure fire way to kill a node.js server that won't stop running.

  126. TIL map() only when you need it

    The origins of 'map()' was to create methods that allow us to manipulate array data without mutating it. It's part of the whole set of methods to make functional programming easier in Javascript.

  127. TIL solving the this keyword and it's execution context

    The this keyword references the current execution context of the function from where you’re calling using it. If it's used in a regular function, a arrow function, or a method changes the execution context of this.

  128. TIL converting Booleans to Numbers

    This helper is great for APIs. Not every language parses true/false the same. But every language knows that 0 is false, and 1 is true.

  129. TIL Microtask Queue vs the Call Stack Queue

    When everything is done from the 'Call Stack', the Event Loop finds some new tasks to go after. It'll dig through all the 'Microtasks queues', then in the 'Macrotasks queues'.

  130. TIL of a console.log way to avoid [object object]

    you can use JSON.stringify to get a object.

  131. TIL JS Coercion

    In JavaScript, the + operator is used for both numeric addition and string concatenation. When you 'add' a number to a string the interpreter converts your number to a string and concatenates both together.

  132. TIL Avoiding dependencies in your helper functions

    Impure functions for helpers? What is this... 1999?

  133. TIL Find unused JavaScript

    Chrome's Coverage panel allows you to quickly locate JavaScript (and CSS) code that has — and has not — been used. To start, open Coverage from the More tools sub-menu in the DevTools menu

  134. TIL Casting values to JS booleans

    use the !! to casting values to JS

  135. TIL checking falsy values inside an array

    Using the key Boolean to find any true/false statements inside an array

  136. TIL a neat way to clone and object and override the items

    Spread the object into a new object, then override the element later.

  137. TIL mutations and how to sort without mutating

    Mutation isn't bad. It CAN cause side effects and ruin your life. There's times when you want to have your objects mutate. For everything else, switch to functional programming and passing the data.

  138. TIL You can dynamically name objects

    Not all Object keys have to be hard-coded strings. To make it dynamic, use [brackets].

  139. TIL adding properties conditionally using the spread syntax

    You can conditionally add properties to objects by ... in there.

  140. TIL JS commas evaluate operands

    The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand. var a=(2,3,4,5,6,7), result is 7.

  141. TIL Javascript Vs Typescript cheatsheet

    A easy-to-print sheet pointing out the difference between the two.

  142. TIL Adds days to a date

    Maybe you just need some quick date math, and don't want to use a date library.

  143. TIL Grouping Event Handlers

    Group your event handlers together for that sweet cleaner, fresher code.

  144. TIL Pure and Impure Functions

    A important piece of Functional Programming is creating Pure Functions. NO SIDE EFFECTS

  145. TIL all functions create a empty prototype object

    When you create a function in JavaScript, it automatically creates an empty container called prototype for you to stick your methods into.

  146. TIL difference between document.hidden vs document.hasFocus()

    Do you need to check if the tab is currently active/Visible?

  147. TIL Finds the differences between arrays

    Finds the differences between arrays

  148. TIL oncontextmenu feature for right-clicking

    The oncontextmenu property lets us assign an event handler function when the right mouse button is clicked on the browser tab.

  149. TIL writing cleaner If statements

    Graphs and visual flow of various if-else statements

  150. TIL Scroll to the top of the page

    A neat trick to create one of those 'To the top' buttons!

  151. TIL Check if a given element is in focus

    The key ingredient is document.activeElement!

  152. TIL toLocaleDateString that's built into Javascript for dates

    Date().toLocaleDateString('en-US') returns a string with a language sensitive representation of the date portion of this date.

  153. TIL Event Listeners in devtools

    Today I learned that you can identify the Event Listener directly in the Devtools!

  154. TIL CSS variable tricks

    If you want to change the background with Javascript, you can use a CSS variable.

  155. TIL more about destructuring

    Destructuring allows us to extract values from arrays and objects and store them in variables with a more convenient syntax.

  156. TIL why NodeJS in reference to I/O

    Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. tl;dr: bypasses JavaScript single-threaded event loop

  157. TIL LocalForage, a small js library for caching

    An easy to use library to help with web storage. Switches between localStorage/sessionStorage, and also IndexedDB automagically. 178,000 repos can't be wrong.

  158. TIL hoisting based on function declarations & function expressions

    Function declarations get hoisted on load. So you can use it anywhere. Function expressions do not. Neither are better than another

  159. TIL the difference between throttling and debouncing

    Throttling enforces a maximum number of times a function can be called over time. Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called.

  160. TIL how Javascript passes data by value, not by reference

    In JavaScript, primitive types like Number or String are passed by value, not by reference.

  161. TIL find() vs filter()

    `find()` method return the first value which match from the collection. `filter()` method returns the match value from the array.

  162. TIL using code-splitting to improve your First Contentful Paint (FCP) score

    Code splitting is a technique where you send only the necessary modules to the user in the beginning.

  163. TIL super keyword in Javascript classes

    the super keyword is mainly used when we want to access a variable, method, or constructor in the base class from the derived class.

  164. TIL using Object.freeze to simulate enums in Javascript

    Enums are useful to assign names to the integral constants which makes a program easy to read and maintain. The keyword 'enum is used to declare an enumeration.

  165. TIL not using the delete keyword for performance issues

    The delete keyword is used to remove a property from an object. Apparently, there is performance issues with `delete` with V8 Javascript Engine.

  166. TIL Optimizations with closures

    To reduce the number of times a variable gets computed, you can use closures. Closures work by storing references to the outer function’s variables. They do not store the actual value.

  167. TIL the difference of Closures in Javascript vs PHP

    I never knew PHP and Javascript closures were different.

  168. TIL the history of the for, forEach, and for...of loops

    for loop came first. Then forEach. With new iterables, for...of was adopted.

  169. TIL spreading an array into another array

    So to merge an array, use the spread operator. '...' <-- that guy

  170. TIL Deconstructing Objects

    Rather than create a big list of parameters in your function, pass the whole object and deconstruct it.

  171. TIL about some key elements of NestJS

    Controllers, Providers, and Modules OH MY!

  172. TIL ES modules and dynamic imports

    Did you know we can also dynamically load modules based on conditionals? The import(path) returns a promise, it fits great with the async/await syntax.

  173. TIL a clean way to refactor if/else statements

    Not using if-statements gets you closer to the code-as-data concept

  174. TIL that you can chain if/else using ternary conditionals

    Chaining Ternary conditionals are really neat

  175. TIL functions should only do one thing

    The most important rule of programming is - break your code into tiny bite-sized pieces. That makes it easier to compose, test, and add it.

  176. TIL iframe sandbox attribute

    The iframe HTML element represents a nested browsing context, embedding another HTML page into the current one. There's also a sandbox mode.

  177. TIL Automatic Semicolon Insertion

    JavaScript has a 'automatic semicolon insertion' rule. It happens if any of these three scenarios occur.

  178. TIL SmooshGate

    It was a a proposal for a JavaScript language feature called `Array.prototype.flatten`.

  179. TIL what ES modules are

    ES Modules (ESM) is the official, standardize module system to Javascript. What the heck does that mean?

  180. TIL a easy way to generate a lot of fake numbers

    You need lots of array elements. You got it.

  181. TIL why emojis in JS counts as a length of 2

    Characters are written in UTF-16. Emojis are bigger, and require two characters.

  182. TIL how to convert RGB to HEX to RGB again

    It's all just math! AAAAH!

  183. TIL how to make mobile devices vibrate

    The Navigator.vibrate() method pulses the vibration hardware on the device, if such hardware exists.

  184. TIL check if the URL is valid

    Using the Web API URL to check if a link is valid or not.

  185. TIL mysterious with keyword in Javascript

    There's a lot of ancient Javascript code that you really shouldn't use, like with

  186. TIL when to use local storage vs session storage

    We already have the `local storage`, why would we want to use the `session storage`?

  187. TIL how NOT to loop through arrays

    Don't use foreach for these use cases

  188. TIL Eliminating duplicate objects

    Using `Set` datatypes can let you do this with no fuss.

  189. TIL use JS filter like a pro

    To remove falsy items, we use `.filter()` `(Array.prototype.filter())`

  190. TIL how to check if the value is an array

    If the value is an Array, true is returned; otherwise, false is.

  191. TIL How to convert a jQuery plugin to Vanilla JS

    To use [Lettering.js](http://letteringjs.com/), which is a reallky neat library, you need to bundle jQuery with it. How about not?

  192. TIL array fill references the same object in memory

    When you use `array.fill` to create inner arrays, it's actually just referencing the same space in memory.

  193. TIL the XOR operator in Javascript

    The operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones).

  194. TIL How to math the 6 minutes(s) ago without a library

    Sometimes you need something to print a date to '6 minute(s) ago', but don't want to import monster-size libs.

  195. TIL Labels in Javascript

    The 'labeled' statement can be used with break or continue statements.

  196. TIL prohibit inserting text

    You may want to prevent the user from pasting text copied from somewhere in the input fields by calling its method preventDefault().

  197. TIL Short circuiting

    Short circuit conditionals for that sweet one-liner

  198. TIL ES2021 - plus(+) operator as an alternative parseInt & parseFloat

    You can use the + operator in front of any numeric string to parse it as a number.

  199. TIL an easy way to populate an data array

    Bonus - I just had to do this in PHP as well, so you get TWO languages for the price of one TIL!

  200. TIL Deallocating memory in Javascript

    Garbage collection is done automatically in JS. But how does it work?

  201. TIL Console Log trick if a condition is true

    condition && console.log('it's true')

  202. TIL Getting rid of if/else and switch statements

    Getting rid of if/else and switch statements

  203. TIL Lexical Scoping

    Lexical scoping describes how a parser resolves variable names when functions are nested.

  204. TIL making Function Factories

    Functions making functions

  205. TIL Using Set and Map

    Differences between Arrays/Set & Objects/Map

  206. TIL flattening arrays

    How to flatten out arrays

  207. TIL Higher Order functions to reduce loops

    Higher Order Functions like Sum, Map, Filter, Reduce

  208. TIL Avoiding Off-by-one errors and state using Recusion

    Recursion is a function that calls itself.

  209. TIL Stateful and stateless

    An expression in a programming language can be “stateful” or “stateless”.

  210. TIL One-by-one errors

    An off-by-one error is when you expect something to be of value N, but in reality it ends up being `N-1` or `N+1`.

  211. TIL the problem with using Loops

    Loops tend to have some flaws. Instead use Higher Order Functions

  212. TIL javascript async vs defer

    The order of operations in Async and Defer

  213. TIL removing ELSE statements to write clearer code

    Programs are meant to be read by humans and only incidentally for computers to execute. Donald Knuth

  214. TIL globalThis

    `this` doesn't mean the same things depending on environment. Use globalThis

  215. TIL Optional Chaining

    The optional chaining `?.` is to see if the value exists

  216. TIL how to generate a random color using JS

    Randomize Hex Color

  217. TIL Immediately Invoked Function Expression

    This is a design pattern where you create a function expression that is immediately executed.

  218. TIL Closure as a backpack

    The Backpack concept is a mental model to think about how closure saves data behind the scenes.

  219. TIL Closures in Private Methods

    Closure in JS: Private data

  220. TIL a Closure example with class-like methods

    Closure in JS: Nesting functions

  221. TIL Javascript Closures

    The answer to var a = add(2)(3); //5

  222. TIL about console.count and console.table

    Some different ways to show data via your console

  223. TIL how the documentation guides Javascript

    Essentially, the ECMAScript team makes recommendations. And Javascript engines follow the spec to implement.

  224. TIL this one-line script to capitalize the first letter of a word

    Other langauges have this. JS has to do it manually

  225. TIL randomize Arrays

    A one line helper function to randomize array items.

  226. TIL about ESNext

    ESNext is a name that always indicates the next version of JavaScript. Spoiler.

  227. TIL Copy Text to Clipboard

    The user then copies that data, and pastes it somewhere else.

  228. TIL how to scroll to an element in JS

    The normal HTML way is with an anchor link. But sometimes, you need to do it with JS.

  229. TIL Combining JS objects together

    tl;dr: use the spread operator

  230. TIL NVM separates global installs

    NVM is awesome

  231. TIL using underscores to separate numbers

    using underscores to separate numbers

  232. TIL localCompare

    Sort with localComapre

  233. TIL All the Javascript Sandboxes

    You need help? Use a JS sandbox to make their lives easier.

  234. TIL function hoisting in JS

    Hoisting is cray

  235. TIL Equality Comparisons for objects

    Crazy comparisons

  236. TIL the Spread Operator

    The spread operator is pretty awesome.

  237. TIL Loose equality

    Have multiple cursors

  238. TIL not to use === to check for NaN

    Don't use === to check for nan

  239. TIL Exceptions to the === rule

    Exceptions to === rule

  240. TIL Equality in JS

    Why {} === {} is false

  241. TIL Node LTS

    Node only up to the latest version

  242. TIL Rest Parameters

    JS you so crazy

  243. TIL that JS has 8 data types

    JS you so crazy

  244. TIL JS's funky decimal math

    JS you so crazy

  245. TIL Rando.js

    Node Version Manager might be the reason everything's broken in your life.

  246. TIL Github workflows

    Deploy your Github master files to FTP

  247. TIL Static Site Generators

    Easily make websites

  248. TIL Node Version Manager

    Node Version Manager might be the reason everything's broken in your life.

  249. TIL Adding a repo as a dependency in package.js

    If they aren't published as a NPM, you can still do this

  250. TIL JS Template Literal Shortcuts

    Strings and things!

  251. TIL Nestling Data in Vue

    Nestled

  252. TIL JS specifics vs JS-looking APIs

    JS specifics vs JS-looking APIs

  253. TIL Default Params in Javascript

    Default Params

  254. TIL JS Object destructuring

    Object Destructuring

  255. TIL Array Cheatsheet

    Who needs to remember?

  256. TIL about RxJS Observables

    RxJS is a reactive programming library, using Observables which takes in a stream of data and emits multiple bits of data over time. They get 'subscribed' to, and events fire from that.

  257. TIL JS Symbols

    What are symbols

  258. TIL JS Constructors

    JS you so crazy

  259. TIL JS Objects to Classes

    It's all sugar baby

  260. TIL Hamsters

    Java is to JavaScript as ham is to hamster.” –Jeremy Keith, 2009

  261. TIL fetchJSON

    Fetch this data

See all tags.