- Podcasts
- CyberSecurity Summary
- Professional JavaScript for Web Developers
About this episodeThis technical Book explores various aspects of JavaScript for web development. It covers fundamental concepts like data types, operators…
You can listen and download our episodes for free on more than 10 different platforms:
https://linktr.ee/cyber_security_summary
Get the Book now from Amazon:
https://www.amazon.com/Professional-JavaScript-Developers-Matt-Frisbie/dp/1394193211?&linkCode=ll1&tag=cvthunderx-20&linkId=9f47a42864e77ba24205b8a69a9ecb29&language=en_US&ref_=as_li_ss_tl
Discover our free courses in tech and cybersecurity, Start learning today:
https://linktr.ee/cybercode_academy
Transcript
From the publisherThis transcript comes from the podcast’s own feed, shown as the publisher wrote it.
Professional JavaScript for Web Developers
Okay, good starting point. Think of ECMAScript as the official standard. It's the specificating like the rule book for how a scripting language should behave the rulebook okay in JavaScript? Well, JavaScript is the most well known language that actually follows those rules. It implements the ECMAScript standard.
Strict mode is basically a way to opt into a cleaner, safer, less error prone version of JavaScript. You put the string you strict at the very top of a script or a function, and what does it do. It changes certain things. It turned some previously silent errors into throne errors. For example, assigning a value to an undeclared variable throws an error instead of implicitly creating a global variable.
Scope determines where variables are accessible. JavaScript uses lexical scope, meaning scope is defined by where the code is physically written. When you use a variable, the engine first looks in the current innermost scope, and if it's not there, looks in the next scope outwards, then the next, and so on up the chain until it hits the global scope. This sequence of scopes is the.
Oh yeah. Object is the foundation for almost everything complex in JavaScript. It's a dynamic collection of properties where keys are usually strings or symbols, and values can be anything. We usually create them with object literals. It's the basis for prototype based inheritance, which is core to JS.
Literals are the most common and usually the best way. You can also use new array, but it has some weird behavior if you pass just one number argument. A ray out from is super useful for converting array like things like dom modalists or the argument's object or iter like sets or maps into real arrays.
The first index of an item searching forwards last index yeah finds the last index searching backwards. Both return to nus one if not found, and both use strict equality and include just returns true or if false if the item exists in the array. Simpler if you don't need the index. It also uses strict equality index of and last index. Oves can take an optional second argument for the starting search position.
It does. Reduce iterates through an array applying a function you provide to accumulate a single result. The function gets the accumulator, the current value, the index, and the array itself. You can some numbers, build an object, flatten an array really versatile. You usually provide an initial value for the accumulator.
Performance, mainly when dealing with raw binary data. Regular rays are super flexible, but that flexibility has overhead. Type raise give you a direct fixed length view onto a chunk of binary memory an array buffer, where each element is known to be a specific numeric type like eight bit unsigned, editger, thirty two bit float, et cetera.
Exactly WebGL web audio API manipulating file data read into an array buffer. They share many methods with regular arrays, map filter, etc. But they operate within the constraints of their type and fixed length. They also have methods like set for efficiently copying data in and subaray to create a new typed to array view over a portion of the same buffer.
It's great for associating metadata with objects without preventing those objects from being cleaned up if they're removed from say the DOM. If you remove a DOM element and it was in the week set, the weekset reference won't keep it lingering in memory because items can disappear. You can't iterate over a week set.
Every object property has these internal attributes to control its behavior. Configurable means can the property be deleted or can its attributes be changed later? Innumerable means does it show up in four lot loombs, ritable means can its value be changed? And value holds the actual value.
Yes, object dot define property lets you define a new property or modify an existing one and explicitly set these attribute values like innumerable dot false or ritable dot false. You can also define getter and setter functions using this object out defined properties lets you do it for multiple properties at once.
Every object has an internal link, often accessible via proto, though object dot get prototype of is the standard way to read it to its prototype. When you try to access a property on an object, if the object doesn't have it directly, JavaScript looks at its prototype. If the prototype doesn't have it, it looks at its prototype, and so on up the chain.
It just means functions in JavaScript are treated like any other value. You can assign them to variables, store them in arrays or objects, pass them as arguments to other functions callbacks, and return them from functions higher order functions. This is fundamental to functional programming patterns in JS.
The argument's object exists in non arrow functions. It's an array like object holding all past arguments. But rest parameters are generally preferred now because they give you a real array. Arguments dot collie refers to the current function and arguments dot caller or function dot caller refers to the calling function are deprecated, non standard and forbidden in strict mode. Avoid them good to know.
These sound deep, they are core concepts and execution context is like the environment where code runs includes the variables scope this value. When a function is called, a new context is created. The scope chain, as we said, is how JS looks up variables by checking the current scope, then outer scopes.
Oh, definitely. Promises represent the eventual result of an ACINC operation. A promise object is a placeholder for a future value. It starts an appending state, and then it eventually settles into either a fulfilled state if the operation succeeded with the result value, or a rejected state if it failed with an error or reason.
Right. Promise dot race promises settles as soon as the first promise in the terable settles either fulfills or rejects, It takes on the outcome of that first one, a race to the finish and promise. Any promises resolves as soon as the first promise fulfills. It only rejects if all promises reject and it rejects with a special aggregate error.
If a promise rejects and nothing catches that rejection you dot catch or unrejected handler in a dot catch, then it's an unhandled rejection. Modern environments will log errors to the console, and in some cases, like no JS, it might even terminate the process. You always want to handle potential errors to keep your application stable.
No, they aren't part of the official trauma specification. Cancelation the ability to stop an ongoing async operation tied to a promise, and progress notifications getting updates before it finishes are things you usually implement with libraries or custom patterns, often using mechanisms like the abort controller, which we'll touch on with fetch.
Right if you just await promise dot all P one, P two, p three, the whole thing rejects if any of them reject. If you want to get results even if some fail, you could await promise dot all settled, which always results and tells you the status of each. Or you could map your promises and handle errors individually, perhaps using a weight p dot catch EP do or within the mapping or wrapping awights in individual try dot catch blocks if doing them sequentially.
Set time out callback delay runs the callback once after at least delay milliseconds. Set interval runs the callback repeatedly every interval milliseconds. Because JavaScript is single threaded and uses an event loop, the delay is a minimum. The callback actually runs only when the main thread is free after the delay is passed. Set time out returns an ID you can pass to clear timeout to cancel it. Set interval returns an id for clear.
Location gives info about the current url location dot href, location, dot path name, location, dot searchlocation, dot hash, et cetera, and lets you navigate by assigning to location dot h ref or using methods like location dot sign. You all navigates and ads to history location dot replace, heural navigates but replaces current history entry and location dot reload and history history lets you move through the user session history dot backstory, dot forward history dot go in where N can be positive or negative. History dot link tells you how many items are in.
Whole navigator gives you browsersniffinginfo, though user agent is notoriously unreliable. Better info comes from properties like Navigator dot Language, Navigator dot platform. Crucially, it has Navigator dot online booley in for connection status and events online offline. The Navigator Dot Connection object Network Information API provides more tas like connection type, effective type, speed, downlink rtt OTT and a change event.
Now Yeah, the performance API is key for measuring speed. Performance dot now gives high resolution timestamps. You can create name markers with performance dot mark start task, measure durations between marks with performance dot measure task duration, start task and task and retrieve these entries with performance dot get entries. The Navigation Timing API Performance Navigation Timing gives detailed timings for pageload.
You can document dot create element tag name and document dot create text node, then use parentode dot a pen child new node to add it at the end, or parentnode dot insert before new node, reference node to insert before another node. Use parentnode dot remove child node to remove and parentode dot replace child new node old node to replace document dot create. Document fragment is useful for building a chunk of dom off screen before appending it all at once for better performance.
Query selector selector returns the first matching element, and query selectora selector returns a static nodalist of all matching elements. These are incredibly powerful on it available on document fragments and individual elements, much more flexible than the older get elements by methods and.
Inner HTML gets or sets the HTML content inside an element. Setting it parses the string as HTML. Outer HTML includes the element itself. Text content gets or sets only the text content, ignoring HTML tags and encoding entities when setting. Intertext is similar to text content, but is aware of CSS rendering. It omits hidden text and also codes entities differently. Be careful with inner HTML as it can be slow and requires reattaching event listeners to recreated elements.
Style, element dot style accesses the elements inline style attribute. You set properties like element dot style, dot background color red to get the actual computed style including styles from CSS rules. Use window dot get computed style element. You can also access style sheets via document dot style sheets and manipulate CSS rules, CSS rule CSS style directly, though that's less common.
Dimensions to give different measurements offset offset offset with offset left offset top includes borders and padding and position relative to the offset parent client client height client with is the inner size, padding included, border, scroll bars excluded, scroll height scroll width is the total size of the scrollable content, while scroll left scroll top is the current scroll position within the element. Client dimensions are read.
These are for more complex iteration needs. They let you traverse a subtree of the dome, optionally filtering nodes based on criteria you define, especially tree walker, which has a filter function. They give you finer control than simple loops or recursive functions. Sometimes true walker keeps track of the current node.
Yeah. Document dot creator range creates a range object representing a contiguous section of the document, you can set its start and end points. Set start, set end. Then you can manipulate that selected content. Delete contents, extract contents into a document fragment, clone contents, and certain nodes around contents. Useful for things like text editors or highlighting.
Exactly intersection observer new intersection Observer callback efficiently tells you when an element intersects with the viewport or another development. Great for lazy loading images, infinite scroll triggering animations on view resize observer new resize observer callback efficiently tells you when an element size changes, much better than pulling off stwidth constantly. Both are asynchronous in performance focus.
DOM level two introduced element dot ad event listener type listener, use capture This is the standard. You can add multiple listeners. The third argument use capture boolli in or options object lets you choose whether to listen during the capturing phase down the tree or the bubbling phase up the tree. The default you remove listeners with remove event listener, needing the exact same arguments.
Lots of useful stuff? Event dot type like click, event dot target, the element the event originated on, event dot current target the element the listener is attached to. Event dot prevent default, stop to full browseractions, event dot stop propagation to stop bubbling cap Also details like coordinates, client x, clinyy, modifier, keys, feature, l key, old key, event phase, et cetera. Properties vary a bit by event type.
Oh tons load for window, images of scripts, unload, window focused, blur or form fields, window, mouse, events, click, TVL click, mousedown, mouse oup, mouse over, mouse out, mouse enter, mouse leave wheel, keyboard events, key down, keep us key at form events, submit, change input, clipboard events, touch events, many more.
Instead of timers like set timeout, use request animation frame callback. The brow sol so calls your callback function just before it's about to repaint the screen. The sinks your animation logic perfectly with the browser's rendering cycle, making animations much smoother and more efficient. It passes a high resolution timestamp to the callback. You call it recursively within the callback to continue the animation loop. Use cancel animation frame to stop it.
Yes, the canvas element gives you a drawing surface. You get the two D context with canvas dot get context two D. This context object has tons of methods for drawing shapes, rectangles, lines, arcs, curves with begin path moved to a line to arc et cetera. Filling, fil style, fill, stroking, stroke style, stroke struck, drawing text on fill text, applying transformations, translate, rotate, scale, drawing images, dramage, adding shadows, gradients, patterns, clipping, compositing, global composite operation and even pixel manipulation. Get image data, put image data wow.
YEP, canvas, dot get context, WEBNIL or webjail two. It's based on OPENNGLS, providing low level access to the GPU for hardware accelerated two D and three D graphics. You define geometry in buffers, write vertex and fragment shaders in GLSL, link them into programs, past data via attributes and uniforms, and then issue draw calls, drawrays, draw elements. Much more complex than two D canvas, but incredibly powerful.
Time, new input types like email, earle date number with built in UI and validation attributes like required pattern min max, the constraint validation API element dot validity, element dot check, validity, element dot set custom validity, the invalid event programmatic submission with form dot submit. Fans like input change, clipboard events, copycut, paste, ridge text editing via the content editor attribute and document dot exec command, though the latter is getting replaced by newer APIs. So like boxes also have a good API from manipulating options.
Yes. This enables shared memory between multiple web workers and the main thread shared The rebuffer is a buffer whose underlying memory can be accessed by multiple threads simultaneously. Atomics provide special functions atomics, dot ad atomics, dot load atomics, dot store atomics, dot weight atomics, dot notify, et cetera that perform operations on that shared memory in an atomic way, preventing race conditions and ensuring operations aren't interrupted. Very advanced, high performance stuff for parallel computation.
Window dot post message message target origin allows safe communication between different windows I frame are workers, even if they're from different origins. The sender specifies the target origin for security, The receiver listens for the message, event checks event dot origin to verify the sender, and accesses the data via event dot data crucial for secure cross domain communication and things like embedded widgets.
Simple but essential. Textingcoder converts a JavaScript string into a U and data array of UTFA bytes by default. Text cooder decoder, dot decode uit data array converts an array of bytes back into a JavaScript string. Handling different encodings useful when dealing with binary data from files or network requests that represents.
Blob represents immutable raw data like a junk of binary data. File inherits from blob and adds file specific metadata like name, size, type, last modified usually comes from an input type file or drag and drop file reader reads the contents of blobs files asynchronously to text read as air buffer read as dator RRL. With events like onload on air. You can create object URLs url dot create creature l blob for referencing blobs files directly in things like MMG tags, but remember to URL revoke objet url when done.
Element dot request full screen ask the browser to make an element full screen requires user gesture usually document dot a inst full screen to leave document dot full screen. Element tells you what's full screen full screen change event fires when state changes. Good for videos, games, presentations.
Location navigator dot geolocation methods get current positions success ab air CB options and watch position success CB air CB options needs user permission. Success callback gets a position object with chords latitude, longitude accuracy. Error callback gets position aer codes for permission denied, unavailable, timeout, use eaht TPS. Be mindful of privacy.
Requests absolutely fetch EARL options is the standard. Returns a promise that resolves to a response object. Options object controls method header's, body, credentials, cash, mode, et CETERA response object has methods to read the body response dot jason, response dot text, response dot, blob, response dot orra buffer. You check response dot OK or response dot status for success. Handle's cores via options and server headers. Integrates with request header's objects can be aborted using a board controller and a bort signal. Can work with dreams. Integrates with the cache. API caches for service workers. Far superior to XMLHTTP request.
New web socket are established as a persistent two way connection. Ws dot, WS or WSS use eventhandlers dot on open on message gets data in event dot data on air on clothes send data with socket dot, send doses socket dot close. Great for chat, live updates, multiplayer games. Doesn't use ad event listener style. You assigned handlers.
Simple key value storage. In the browser. Local storage persists across browser sessions. Same origin. Session storage allows only for the current tab. Windows session both have set item key value, remove item key clear length limits around five to ten mil us storage event fires and other tabs. When storage changes stores values is strings.
Yes INDEXTB is a full transactional NOSEQL database in the browser, stores complex JavaScript objects, files, blobs, asynchronous API. You work with databases object stores like tables, indexes for query transactions, cursors for iteration. Open with index dB open name version, schema changes happen in the unupgrade needed event powerful for offline apps and large data sets.
Module pattern used iiv's enclosures to simulate modules. Es, modules, import exports, script type module are the native standard, much cleaner syntax, static analysis benefits, better dependency management. Named exports export x inport x, default exports, export default y, import y, dynamic import phrase incloading import maps for controlling resolution. The modern standard.
Run jas off the main UI thread to avoid blocking dedicated workers. New worker for a single script, shared workers, new shared worker accessible by multiple scripts same origin. Service workers act as network proxies for offline support, push notifications, et cetera. Communicate via post message and on message. Data is copied, structured, cloning, or transfer transferable like a ray buffer. Each worker type has different scope in life cycle.
Use try, dot, catch dot finally, throw errors with throw new error or specific types type er, et cetera. Handle global errors with window dot one, air, use browserdeb tools extensively, console debugger breakpoints, stepping, network panel, static analysis linters. Typescript helps catch errors early assertions can help during development. Robust error handling is key.
And parse Gson does stringify value. Replacer space converts a JS value to a JSON string. Json Dot parse text Reviver parses a Jason string back into a JS value. Replacer and reviver functions allow customization during serialization de serialization. Space argument pritifies the string output ubiquitous for data exchange, especially with apisvia.
