Search results

The “if” statement.The if(...) statement evaluates a condition in parentheses and, if the result is true… The else if clause lets us do that.… If that is also falsy, it shows the last alert. There can be more else if blocks.… If true – it returns 'Hi, baby!'.… If that’s true – it returns 'Hello!'.
If any of its arguments are true, it returns true, otherwise it returns false.… statement to test if any of the given conditions is true.… as a “shorter way to write if”.… That is, only if (x > 0) is true.… So we recommend using every construct for its purpose: use if if we want if and use && if we
=Y), it means “look for X, but match only if followed by Y”.… Check if Y is immediately after X (skip if isn’t).… Check if Z is also immediately after X (skip if isn’t).… =Y) Positive lookahead X if followed by Y X(?!Y) Negative lookahead X if not followed by Y (?… <=Y)X Positive lookbehind X if after Y (?<!Y)X Negative lookbehind X if not after Y
Otherwise, if we overuse ?.… must be declared If there’s no variable user at all, then user?.… prop – returns obj.prop if obj exists, otherwise undefined. obj?.… [prop] – returns obj[prop] if obj exists, otherwise undefined. obj.method?.… So that it won’t hide programming errors from us, if they occur.
It has 3 modes: If the regexp doesn’t have flag g, then it returns the first match as an array with… If there are no matches, no matter if there’s flag g or not, null is returned.… If there are no matches, we don’t get an empty array, but null.… If there are no results, it returns an empty iterable object instead of null.… If there are no matches, regexp.exec returns null and resets regexp.lastIndex to 0.
If you’re not familiar with these methods, and their usage in the examples is confusing, you may want… What if the script loading fails? Our callback should be able to react on that.… The convention is: The first argument of the callback is reserved for an error if it occurs.… The second argument (and the next ones if needed) are for the successful result.… there’s no error… We load 2.js, then if there’s no error… We load 3.js, then if there’s no error – do
we set a header If-Modified-Since, If-None-Match, If-Unmodified-Since, If-Match, or If-Range, "… (if the response headers permit this action), "no-cache" – create a conditional request ifIf there’s no response in HTTP-cache, make a regular HTTP-request, behave normally, "only-if-cached… " – use a response from HTTP-cache, even if it’s stale.… We can’t handle the server response if the document is unloaded.
IfIf there’s a chain with multiple .then/catch/finally, then every one of them is executed asynchronously… What if the order matters for us? How can we make code finished appear after promise done?… If we didn’t know about the microtasks queue, we could wonder: “Why did unhandledrejection handler run… If we need to guarantee that a piece of code is executed after .then/catch/finally, we can add it into
element triggers that event. click Triggers after mousedown and then mouseup over the same element if… Even if we’d like to force Mac users to Ctrl+click – that’s kind of difficult.… So that if the visitor uses a keyboard – they work.… Modifier keys (true if pressed): altKey, ctrlKey, shiftKey and metaKey (Mac).… if (e.metaKey || e.ctrlKey).
The idea is that if a user has two pages open: one from john-smith.com, and another one is gmail.com,… So if we do something with the document immediately, that will probably be lost.… If we set any event handlers on it, they will be ignored.… We can immediately source.postMessage(...) back if we want.… If targetOrigin is not '*', then the browser checks if window targetWin has the origin targetOrigin.
But scripts in the main document have no idea about the shadow DOM internals, especially if the component… If… Retargeting does not occur if the event occurs on a slotted element, that physically lives in the light… If it’s true, then the event does cross the boundary.… If we dispatch a CustomEvent, then we should explicitly set composed: true.
It has 3 working modes: If the regular expression has flag g, it returns an array of all matches:… If there’s no such flag it returns only the first match in the form of an array, with the full match… And, finally, if there are no matches, null is returned (doesn’t matter if there’s flag g or not).… If there are no matches, we don’t receive an empty array, but instead receive null.… The method regexp.test(str) returns true if there’s at least one match, otherwise, it returns false.
For other hints: call valueOf, and if it doesn’t exist or if it returns an object instead of a primitive… If toString or valueOf returns an object, then it’s ignored (same as if there were no method).… s no error, but such value is ignored (like if the method didn’t exist).… The conversion algorithm is: Call obj[Symbol.toPrimitive](hint) if the method exists, Otherwise if hint… All these methods must return a primitive to work (if defined).
Otherwise, if one uses another type, such as number, it’s autoconverted to string.… For instance, if we’re working with user objects, that belong to a third-party code.… If the symbol is not global, it won’t be able to find it and returns undefined.… Symbols are always different values, even if they have the same name.… (creates if needed) a global symbol with key as the name.
For instance, let’s test if the text starts with Mary:… Similar to this, we can test if the string ends with snow using snow$:… For instance, to check if the user input is in the right format.… If there’s any deviation or an extra character, the result is false.… Anchors behave differently if flag m is present. We’ll see that in the next article.
If your script may run in other environments, it’s better to use globalThis instead.… If we used let instead, such thing wouldn’t happen:… If… ” variables and produces certain “outcome” is clearer, less prone to errors and easier to test than if… We should store values in the global object only if they’re truly global for our project.
If we access event.relatedTarget.tagName, then there will be an error.… And if it notices changes then triggers the events.… If the movement is fast enough, then the parent element is ignored.… On mouseover – ignore the event if we’re still inside the current <td>.… On mouseout – ignore if we didn’t leave the current <td>.
true, the value can be changed, otherwise it’s read-only. enumerable – if true, then listed in loops… , otherwise not listed. configurable – if true, the property can be deleted and these attributes can… If the property exists, defineProperty updates its flags.… If that’s not what we want then we’d better set them to true in descriptor.… So if we want a “better” clone then Object.defineProperties is preferred.
A switch statement can replace multiple if checks.… If the equality is found, switch starts to execute the code starting from the corresponding case, until… If no case is matched then the default code is executed (if it exists).… If there is no break then the execution continues with the next case without any checks.… For example, if we want the same code to run for case 3 and case 5:
If we handle an event in JavaScript, we may not want the corresponding browser action to happen, and… If we use <button> or <span>, that doesn’t work.… If we prevent the first event, there will be no second.… If we prevent the mousedown event, there’s no focus.… The focusing is still possible if we use another way to enter the input.
If an exception happens, it gets caught and treated as a rejection.… In a regular try..catch we can analyze the error and maybe rethrow it if it can’t be handled.… If we throw inside .catch, then the control goes to the next closest error handler.… You can see it in the console if you run the example above.… It’s ok not to use .catch at all, if there’s no way to recover from an error.
If i++ was missing from the example above, the loop would repeat (in theory) forever.… For example, we can omit begin if we don’t need to do anything at the loop start.… Surely, we can just wrap the code in an if block instead of using continue.… If the code inside of if is longer than a few lines, that may decrease the overall readability.… instead of if.
If a same-named variable is declared inside the function then it shadows the outer one.… In the example above, anotherFunction() isn’t called at all, if the text parameter is provided.… If that thing is big, maybe it’s worth it to split the function into a few smaller functions.… So, functions can be created even if we don’t intend to reuse them.… If it doesn’t, then its result is undefined.
…And what if the loading failed?… We don’t know if it was an error 404 or 500 or something else.… That is: if a script loaded successfully, then onload triggers, even if it has programming errors in… If we’re using a script from another domain, and there’s an error in it, we can’t get error details.… But if a script comes from another origin, then there’s not much information about errors in it, as we
But if any of those objects is not a promise, it’s passed to the resulting array “as is”.… Promise.all rejects as a whole if any promise rejects.… Even if one request fails, we’re still interested in the others.… fulfilled) or reason (if rejected).… If all of the given promises are rejected, AggregateError becomes the error of Promise.any.
That’s possible, but if we’re moving elements to shadow DOM, then CSS styles from the document do not… The browser shows it if there’s no corresponding filler in light DOM.… Updating slots.What if the outer code wants to add/remove menu items dynamically?… If there are many elements for the same slot – they are appended one after another.… It’s shown if there are no light children for the slot.
If we’d like to allow subdomains like forum.site.com to get a cookie set at site.com, that’s possible… , if a cookie doesn’t have one of these attributes, it disappears when the browser/tab is closed.… So if we solely rely on samesite to provide protection, then old browsers will be vulnerable.… But if a cookie is httpOnly, then document.cookie doesn’t see it, so it is protected.… If a website wants to set tracking cookies for everyone.
options – the object with two optional properties: bubbles: true/false – if true, then the event bubbles… . cancelable: true/false – if true, then the “default action” may be prevented.… Then handlers react on it as if it were a regular browser event.… If the event was created with the bubbles flag, then it bubbles.… the event should bubble. cancelable: true if the event.preventDefault() should work.
SAMEORIGIN Allow inside a frame if the parent document comes from the same origin.… ALLOW-FROM domain Allow inside a frame if the parent document is from the given domain.… Other sites won’t be able to show our page in a frame, even if they have good reasons to do so.… That <div> is to be removed if window == top or if we figure out that we don’t need the protection… That’s dangerous if there are important click-activated actions.
If you haven’t selected an IDE yet, consider the following options: Visual Studio Code (cross-platform… an IDE works on a project-level, so it loads much more data on start, analyzes the project structure if… A lightweight editor is much faster if we need only one file.… Vim and Emacs are also cool if you know how to use them.… The author’s personal opinion: I’d use Visual Studio Code if I develop mostly frontend.
So if you specify params, make sure you explicitly set all required features to yes.… To check if a window is closed: win.closed.… The closed property is true if the window is closed.… That’s useful to check if the popup (or the main window) is still open or not.… If we’re going to open a popup, a good practice is to inform the user about it.
, ""); if (n < 0) { alert(`Power ${n} is not supported, please enter a non-negative integer number… A single-line construct, such as if… 😏 One line without braces – acceptable, if… For example: And, for if statements… If the code goes first, then it becomes clear from the start.
b is: if a is defined, then a, if a isn’t defined, then b. In other words, ??… returns the first argument if it’s not null/undefined. Otherwise, the second one.… For example, here we show user if its value isn’t null/undefined, otherwise Anonymous:… All of them may be not defined, if the user decided not to fill in the corresponding values.… If any of these is the first argument of ||, then we’ll get the second argument as the result.
If you click on a stack item (e.g.… If we click it now, alert will be shown.… That’s good if we’re not interested to see what happens inside the function call.… The “Step into” goes into their code, waiting for them if necessary.… An error (if dev tools are open and the button is “on”).
If we want to check if item exists in the array and don’t need the index, then arr.includes is preferred… If nothing is found, undefined is returned.… The value of -1 is returned if nothing is found.… If there may be many, we can use arr.filter(fn).… If it is provided, then the extra elements are ignored.
If you don’t plan on meeting such scripts you may even skip this chapter or postpone it.… If we used let test instead of var test, then the variable would only be visible inside if:… If… As we can see, var pierces through if… So in the example above, if (false) branch never executes, but that doesn’t matter.
Can’t use await in regular functions If we try to use await in a non-async function, there… We may get this error if… But in the case of a rejection, it throws the error, just as if there were a throw statement at that… The await keyword before a promise makes JavaScript wait until that promise settles, and then: If it… ’s an error, an exception is generated — same as if throw error were called at that very place.
If there’s a scrollbar, and it occupies some space, then these two lines show different values:… cases, we need the available window width in order to draw or position something within scrollbars (if… For instance, if we try to scroll the page with a script in <head>, it won’t work.… If top=false, then the page scrolls to make elem appear at the bottom.… If it occupied some space, then that space is now free and the content “jumps” to fill it.
For instance, if the tag is <body id="page">, then the DOM object has body.id="page… But technically no one limits us, and if there aren’t enough, we can add our own.… But that doesn’t happen if the attribute is non-standard.… Quite rarely, even if a DOM property type is a string, it may differ from the attribute.… But if it starts with data-, then we should use dataset.
If there’s a bulky script at the top of the page, it “blocks the page”.… an async script finishes loading after the page is complete) …or after an async script (if an async… Although, it might be that long.js loads first, if cached, then it runs first.… This can be changed if we explicitly set script.async=false.… That happens if scripts are small or cached, and the document is long enough.
If json is malformed, JSON.parse generates an error, so the script “dies”.… If we don’t know how to handle it, we do throw err.… If it exists, it runs in all cases: after try, if there were no errors, after catch, if there were errors… If you say “No”, then try -> finally.… But what if there’s an error during the function call?
map.set(key, value) – stores the value by the key. map.get(key) – returns the value by the key, undefined if… key doesn’t exist in map. map.has(key) – returns true if the key exists, false otherwise. map.delete… Its main methods are: new Set([iterable]) – creates the set, and if an iterable object is provided (… (value) – adds a value, returns the set itself. set.delete(value) – removes the value, returns true if… value existed at the moment of the call, otherwise false. set.has(value) – returns true if the value
So if animal has a lot of useful properties and methods, then they become automatically available in… JavaScript will throw an error if we try to assign __proto__ in a circle.… …But why does hasOwnProperty not appear in the for..in loop like eats and jumps do, if for..in lists… If we call obj.method(), and the method is taken from the prototype, this still references obj.… So methods always work with the current object even if they are inherited.
The latter should only be used if classes “can’t handle it”.… For example, style is acceptable if we calculate coordinates of an element dynamically and want to set… Setting elem.style.width="100px" works the same as if we had in the attribute style a string… Then later we may want to remove the style.display as if it were not set.… normally, as if there were no such style.display property at all.
Even if there are no messages, the server is bombed with requests every 10 seconds, even if the user… So, if we’re talking about a very small service, the approach may be viable, but generally, it needs… If the connection is lost, because of, say, a network error, the browser immediately sends a new request… Demo: a chat.Here’s a demo chat, you can also download it and run locally (if you’re familiar with Node.js… If messages come very often, then the chart of requesting-receiving messages, painted above, becomes
If we’d like to look for lowercase letters as well, we can add the range a-f: [0-9A-Fa-f].… For instance, if we’d like to look for a wordly character \w or a hyphen -, then the set is [\w-].… If we really need them, we can use library XRegExp.… And if we need a backslash, then we use \\, and so on.… The closing square bracket ] is always escaped (if we need to look for that symbol).
This handler is assigned to <div>, but also runs if you click any nested tag like <em> or… Why does the handler on <div> run if the actual click was on <em>?… So if we click on <p>, then we’ll see 3 alerts: p → div → form.… If it’s true, then the handler is set on the capturing phase.… Then higher-level authorities if needed. The same for event handlers.
If there’s already a value with the same key, it will be replaced.… The error is in request.error (if any).… That can lead to strange delays if transactions take a long time. So, what to do?… If the open flags is true, the corresponding key is not included in the range.… if the value on keyPath is an array.
If yes, then all right, go on with XMLHttpRequest. Otherwise, please head on to Fetch.… synchronous, we’ll cover that a bit later. user, password – login and password for basic HTTP auth (if… These three events are the most widely used: load – when the request is complete (even if HTTP status… So, if we want to get an object with name/value pairs, we need to throw in a bit JS.… Or, if we like JSON more, then JSON.stringify and send as a string.
In the example below: The blur handler checks if the field has an email entered, and if not – shows… Also we could automatically send the changed value to the server if it’s correct.… If an element is removed from DOM, then it also causes the focus loss.… If it is reinserted later, then the focus doesn’t return.… Any element becomes focusable if it has tabindex.
Only first 50 results are shown.