Random JavaScript jots
This is just a bunch of jots I’ve made about JavaScript, in no particular order. Posted here, because the alternative was to delete them.
- JavaScript is single-threaded by its nature. Nothing runs in parallel, hence no need for any synchronization or atomics. There is actually an Atomic class, but for use in conjunction with shared memory (which is far away from browser JavaScript).
- In Firefox, use the Web Console for spotting errors: Hamburger > Web Developer > Web Console, or just go Ctrl-Shift-K. Or F12. Make sure that the Errors button is enabled. Requests is also nice.
- Chrome as well as Firefox have a JavaScript debugger which allows inserting breakpoints anywhere in the code as well as when when a DOM element changes. Including stack trace and the ability to watch the calling code. Just use the inspector and right-click on the DOM element, and select “Break on…”. Code breakpoints can be conditional, i.e. the user can write an expression so that the breakpoint is skipped if it isn’t true. Firefox’ debugger is somewhat unstable when resuming execution, so go for Chrome.
- To figure out what code does what, set a breakpoint on a DOM element, and make it change.
- Use console.log() to generate printf-style debug output. alert() is also available, but so 90′s.
- There’s also a JavaScript debugger allowing to print out expressions: Same interface as the Web Developer.
- In particular, enable “Pause on exceptions”, and possibly even “Pause on caught exceptions” (the latter on Chrome only, maybe?). It helps a lot.
- JavaScript’s built-in keys() method returns an Array of keys in the order they were inserted.
- Use “let” rather than “var” to declare variables, so that they are locally scoped (?).
- When assigning callbacks, it’s better to insert execution code rather than to refer to a function, as this allows telling the reason for the call in the debugger’s stack trace.
- [].slice.call(this.domNode.querySelectorAll(‘*’)).forEach(function(node): Runs the function on every node under this current position. See explanation.
- (args) => { code } expressions: Shorthand for function (args) { code }
- Node.js is a standalone JavaScript interpreter, typically appearing as /usr/bin/nodejs. It runs JavaScript files just like Bash, Perl, Python or other script languages.
- npm is the Node.js package manager, allowing installation of JavaScript modules.
- .ts and .tsx are extensions for TypeScript, an extension of JavaScript maintained by Microsoft.
- React is a JavaScript library for building user interfaces.