diff --git a/files/en-us/learn_web_development/core/scripting/functions/index.md b/files/en-us/learn_web_development/core/scripting/functions/index.md index 8e286da72ca248c..64d6ac72fdc593b 100644 --- a/files/en-us/learn_web_development/core/scripting/functions/index.md +++ b/files/en-us/learn_web_development/core/scripting/functions/index.md @@ -8,7 +8,7 @@ sidebar: learnsidebar {{PreviousMenuNext("Learn_web_development/Core/Scripting/Test_your_skills/Loops","Learn_web_development/Core/Scripting/Build_your_own_function", "Learn_web_development/Core/Scripting")}} -Another essential concept in coding is **functions**, which allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it using a single short command — rather than having to type out the same code multiple times. In this article we'll explore fundamental concepts behind functions such as basic syntax, how to invoke and define them, scope, and parameters. +Another essential concept in coding is **functions**, which allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it using a single short command — rather than having to type out the same code multiple times. In this article, we'll explore fundamental function concepts like basic syntax, how to invoke and define them, scope, and parameters. @@ -21,11 +21,12 @@ Another essential concept in coding is **functions**, which allow you to store a
  • The purpose of functions — to enable the creation of reusable blocks of code that can be called wherever needed.
  • -
  • functions are used everywhere in JavaScript and that some are built into the browser and some are user-defined.
  • +
  • Functions are used everywhere in JavaScript.
  • +
  • Some functions are built into the browser, and some are user-defined.
  • The difference between functions and methods.
  • Invoking functions.
  • Anonymous functions and arrow functions.
  • -
  • Defining function parameters, passing in arguments to function calls.
  • +
  • Defining function parameters and passing in arguments to function calls.
  • Global scope and function/block scope.
  • An understanding of what callback functions are.
@@ -36,9 +37,9 @@ Another essential concept in coding is **functions**, which allow you to store a ## Where do I find functions? -In JavaScript, you'll find functions everywhere. In fact, we've been using functions throughout the course so far; we've just not been talking about them very much. Now is the time, however, for us to start talking about functions explicitly and exploring their syntax. +In JavaScript, you'll find functions everywhere. In fact, we've been using functions throughout the course so far; we've just not talked about them very much. Now is the time, however, for us to start talking about functions explicitly and exploring their syntax. -Pretty much anytime you make use of a JavaScript structure that features a pair of parentheses — `()` — and you're **not** using a common built-in language structure like a [for loop](/en-US/docs/Learn_web_development/Core/Scripting/Loops#the_standard_for_loop), [while or do...while loop](/en-US/docs/Learn_web_development/Core/Scripting/Loops#while_and_do...while), or [if...else statement](/en-US/docs/Learn_web_development/Core/Scripting/Conditionals#if...else_statements), you are making use of a function. +Pretty much anytime you make use of a JavaScript structure that features a pair of parentheses — `()` — and you're **not** using a common language structure like a [for loop](/en-US/docs/Learn_web_development/Core/Scripting/Loops#the_standard_for_loop), [while or do...while loop](/en-US/docs/Learn_web_development/Core/Scripting/Loops#while_and_do...while), or [if...else statement](/en-US/docs/Learn_web_development/Core/Scripting/Conditionals#if...else_statements), you are making use of a function. ## Built-in browser functions @@ -77,15 +78,15 @@ const myNumber = Math.random(); We were using a _function_! > [!NOTE] -> Feel free to enter these lines into your browser's JavaScript console to re-familiarize yourself with their functionality, if needed. +> Feel free to enter these lines into your browser's JavaScript console to re-familiarize yourself with their functionality if needed. -The JavaScript language has many built-in functions that allow you to do useful things without having to write all that code yourself. In fact, some of the code you are calling when you **invoke** (a fancy word for run, or execute) a built-in browser function couldn't be written in JavaScript — many of these functions are calling parts of the background browser code, which is written largely in low-level system languages like C++, not web languages like JavaScript. +The JavaScript language has many built-in functions that allow you to do useful things without writing all that code yourself. In fact, some of the code you are calling when you **invoke** (a fancy word for run, or execute) a built-in browser function couldn't be written in JavaScript — many of these functions are calling parts of the background browser code, which is written largely in low-level system languages like C++, not web languages like JavaScript. Bear in mind that some built-in browser functions are not part of the core JavaScript language — some are defined as part of browser APIs, which build on top of the default language to provide even more functionality (refer to [this early section of our course](/en-US/docs/Learn_web_development/Core/Scripting/What_is_JavaScript#so_what_can_it_really_do) for more descriptions). We'll look at using browser APIs in more detail in a later module. ## Functions versus methods -**Functions** that are part of objects are called **methods**; you'll learn about objects later in the module. For now, we just wanted to clear up any possible confusion about method versus function — you are likely to meet both terms as you look at related resources across the Web. +**Functions** that are part of objects are called **methods**; you'll learn about objects later in the module. For now, we just wanted to clear up any possible confusion about methods versus functions — you are likely to meet both terms as you look at related resources across the Web. The built-in code we've used so far comes in both forms: **functions** and **methods.** You can check the full list of built-in functions, as well as built-in objects and their corresponding methods [in our JavaScript reference](/en-US/docs/Web/JavaScript/Reference/Global_Objects). @@ -103,13 +104,13 @@ function draw() { } ``` -This function draws 100 random circles inside a {{htmlelement("canvas")}} element. Every time we want to do that, we can invoke the function with this: +This function draws 100 random circles inside a {{htmlelement("canvas")}} element. Every time we want to do that, we can invoke the function like this, rather than having to write all that code out again every time we want to repeat it: ```js draw(); ``` -rather than having to write all that code out again every time we want to repeat it. Functions can contain whatever code you like — you can even call other functions from inside functions. For example, the `draw()` function seen above calls the `random()` function three times; `random()` is defined by the following code: +Functions can contain whatever code you like, even other function calls. For example, the `draw()` function seen above calls the `random()` function three times; `random()` is defined by the following code: ```js function random(number) { @@ -133,22 +134,21 @@ myFunction(); ``` > [!NOTE] -> This form of creating a function is also known as _function declaration_. It is always hoisted so that you can call the function above the function definition and it will work fine. +> This form of creating a function is also known as _function declaration_. It is always hoisted, which means you can call the function above its definition and it will work fine. -## Function parameters +## Function arguments and parameters -Some functions require **parameters** to be specified when you invoke them — these are values that need to be included inside the function parentheses, which it needs to do its job properly. +Some functions require **arguments** when you invoke them — values that need to be included inside the function parentheses for the function to do its job properly. -> [!NOTE] -> Parameters are sometimes called arguments, properties, or even attributes. +You'll also hear the term **parameters** used, often interchangeably with _arguments_. This is often OK in informal discussions, but they have different meanings. Parameters are the variables listed in a function definition, while arguments are the values passed to the function to represent the parameters when the function is called. -As an example, the browser's built-in [`Math.random()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) function doesn't require any parameters. When called, it always returns a random number between 0 and 1: +Let's look at some examples. The [`Math.random()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) function doesn't require any arguments. When called, it always returns a random number between 0 and 1: ```js const myNumber = Math.random(); ``` -The browser's built-in string [`replace()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) function however needs two parameters — the substring to find in the main string, and the substring to replace that string with: +The string [`replace()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) function, however, needs two arguments — the substring to find in the main string, and the substring to replace that string with: ```js const myText = "I am a string"; @@ -156,11 +156,11 @@ const newString = myText.replace("string", "sausage"); ``` > [!NOTE] -> When you need to specify multiple parameters, you separate them with commas. +> When you need to specify multiple parameters or arguments, you separate them with commas. ### Optional parameters -Sometimes parameters are optional — you don't have to specify them. If you don't, the function generally adopts some kind of default behavior. As an example, the array [`join()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) function's parameter is optional: +Sometimes parameters are defined as optional — you don't have to specify the equivalent arguments when calling the function. If you don't, the function generally uses a default value. As an example, the array [`join()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) function's parameter is optional: ```js const myArray = ["I", "love", "chocolate", "frogs"]; @@ -173,11 +173,11 @@ console.log(madeAnotherString); // returns 'I,love,chocolate,frogs' ``` -If no parameter is included to specify a joining/delimiting character, a comma is used by default. +If no argument is included to specify a joining/delimiting character, a comma is used by default. ### Default parameters -If you're writing a function and want to support optional parameters, you can specify default values by adding `=` after the name of the parameter, followed by the default value: +If you're writing a function and want to define optional parameters, you can specify default values by adding `=` after the name of the parameter, followed by the default value: ```js function hello(name = "Chris") { @@ -206,19 +206,19 @@ But you can also create a function that doesn't have a name: }); ``` -This is called an **anonymous function**, because it has no name. You'll often see anonymous functions when a function expects to receive another function as a parameter. In this case, the function parameter is often passed as an anonymous function. +This is called an **anonymous function**, because it has no name. You'll often see anonymous functions when a function expects to receive another function as an argument. In this case, an anonymous function is often passed as the argument. > [!NOTE] > This form of creating a function is also known as _function expression_. Unlike function declarations, function expressions are not hoisted. ### Anonymous function example -For example, let's say you want to run some code when the user types into a text box. To do this, you can call the {{domxref("EventTarget/addEventListener", "addEventListener()")}} function of the text box. This function expects you to pass it at least two parameters: +For example, let's say you want to run some code when the user types into a text box. To do this, you can call the {{domxref("EventTarget.addEventListener", "addEventListener()")}} function of the text box. This function expects at least two arguments: -- The name of the event to listen for, which in this case is {{domxref("Element/keydown_event", "keydown")}} +- The name of the event to listen for, which in this case is {{domxref("Element.keydown_event", "keydown")}} - A function to run when the event happens. -When the user presses a key, the browser will call the function you provided, and pass it a parameter containing information about this event, including the particular key that the user pressed: +When the user presses a key, the browser will call the function you provided and pass it a parameter containing information about this event, including the particular key that the user pressed: ```js function logKey(event) { @@ -246,7 +246,7 @@ textBox.addEventListener("keydown", (event) => { }); ``` -If the function only takes one parameter, you can omit the parentheses around the parameter: +If the function only takes one argument, you can omit the parentheses around it: ```js-nolint textBox.addEventListener("keydown", event => { @@ -254,7 +254,7 @@ textBox.addEventListener("keydown", event => { }); ``` -Finally, if your function contains only one line that's a `return` statement, you can also omit the braces and the `return` keyword and implicitly return the expression. In the following example, we're using the {{jsxref("Array.prototype.map()","map()")}} method of `Array` to double every value in the original array: +Finally, if your function contains only a single line that's a `return` statement, you can omit the braces and the `return` keyword, and implicitly return the expression. In the following example, we're using the {{jsxref("Array.prototype.map()","map()")}} method of `Array` to double every value in the original array: ```js-nolint const originals = [1, 2, 3]; @@ -264,7 +264,7 @@ const doubled = originals.map(item => item * 2); console.log(doubled); // [2, 4, 6] ``` -The `map()` method passes each item in the array into the given function, then takes the value returned by the function and adds it to a new array. +The `map()` method passes each item in the array to the given function, then takes the function's return value and adds it to a new array. The arrow function is very concise; rewriting our `map()` code to use a regular anonymous callback function would look like this: @@ -323,11 +323,11 @@ The result - try typing into the text box and see the output: ## Function scope and conflicts -Let's talk a bit about {{glossary("scope")}} — an important concept when dealing with functions. When you create a function, the variables and other things defined inside the function are inside their own separate **scope**. This means that they are locked away in their own separate compartment, unreachable from code outside the functions. +Let's talk a bit about {{glossary("scope")}} — an important concept when dealing with functions. When you create a function, the variables and other things defined inside the function are inside their own separate **scope**. This means that they are locked away in their own separate compartment, unreachable from code outside the function. The top-level outside all your functions is called the **global scope**. Values defined in the global scope are accessible from everywhere in the code. -JavaScript works like this mainly for security and organization. Sometimes you don't want variables to be accessible from everywhere in the code. External scripts called in from elsewhere could start to mess with your code and cause problems if they use the same variable names, causing conflicts. This might be done maliciously or just by accident. +JavaScript works like this mainly for security and organization. Sometimes you don't want variables to be accessible from everywhere in the code. External scripts called in from elsewhere could mess with your code and cause problems if they use the same variable names, causing conflicts. This might be done maliciously or just by accident. For example, say you have an HTML file referencing two external JavaScript files, and both of them have a variable and a function defined that use the same name: @@ -360,7 +360,7 @@ You can see this example [running live on GitHub](https://mdn.github.io/learning - When the example renders in a browser, you will first see an alert box displaying `Hello Chris: welcome to our company.`, meaning that the `greeting()` function defined inside the first script file has been called by the `greeting()` call inside the internal script. -- The second script, however, does not load and run at all, and an error is printed in the console: `Uncaught SyntaxError: Identifier 'name' has already been declared`. This is because the `name` constant is already declared in `first.js`, and you can't declare the same constant twice in the same scope. Because the second script did not load, the `greeting()` function from `second.js` is not available to be called. +- The second script, however, does not load and run at all, and an error is printed in the console: `Uncaught SyntaxError: Identifier 'name' has already been declared`. This is because the `name` constant is already declared in `first.js`, and you can't declare the same constant twice in the same scope. Because the second script did not load, the `greeting()` function from `second.js` is not available to call. - If we were to remove the `const name = "Zaptec";` line from `second.js` and reload the page, both scripts would execute. The alert box would now say `Our company is called Chris.` If a function is _redeclared_, the last declaration in the source order is used. The previous declarations are effectively overwritten. @@ -376,7 +376,7 @@ The zoo keeper is like the global scope — they have the keys to access every e Let's look at a real example to demonstrate scoping. -1. First, make a local copy of our [function-scope.html](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/functions/function-scope.html) example. This contains two functions called `a()` and `b()`, and three variables — `x`, `y`, and `z` — two of which are defined inside the functions, and one in the global scope. It also contains a third function called `output()`, which takes a single parameter and outputs it to a paragraph on the page. +1. First, make a local copy of our [function-scope.html](https://github.com/mdn/learning-area/blob/main/javascript/building-blocks/functions/function-scope.html) example. This contains two functions called `a()` and `b()`, and three variables — `x`, `y`, and `z` — two of which are defined inside the functions, and one in the global scope. It also contains a third function called `output()`, which takes a single argument and outputs it to a paragraph on the page. 2. Open the example up in a browser and in your text editor. 3. Open the JavaScript console in your browser developer tools. In the JavaScript console, enter the following command: @@ -416,7 +416,7 @@ Let's look at a real example to demonstrate scoping. b(); ``` - You should see the `y` and `z` values printed in the browser viewport. This works fine, as the `output()` function is called inside the other functions, in the same scope as the variables it prints are defined in. `output()` itself is available from anywhere, as it is defined in the global scope. + You should see the `y` and `z` values printed in the browser viewport. This works fine because the `output()` function is called inside the other functions, in the same scope as the variables it prints are defined in. `output()` itself is available from anywhere, as it is defined in the global scope. 6. Now try updating your code like this: @@ -439,7 +439,7 @@ Let's look at a real example to demonstrate scoping. b(); ``` - Both the `a()` and `b()` calls should print the value of x to the browser viewport. These work fine because even though the `output()` calls are not in the same scope as `x` is defined in, `x` is a global variable — it is available inside all code, everywhere. + Both the `a()` and `b()` calls should print the value of x to the browser viewport. These work fine because, even though the `output()` calls are not in the same scope as `x` is defined in, `x` is a global variable — it is available inside all code, everywhere. 8. Finally, try updating your code like this: @@ -499,9 +499,9 @@ for (let i = 0; i <= 1; i++) { } ``` -they would be hoisted to the global scope; therefore, outputting them to the console (for example, with `output(c)`) would work. Variables declared with `var` inside functions, however, still have their scope limited to those functions. +They would be hoisted to the global scope; therefore, outputting them to the console (for example, with `output(c)`) would work. Variables declared with `var` inside functions, however, still have their scope limited to those functions. -This inconsistency can cause confusion and errors, and is another reason why you should use `let` and `const` instead of `var`. +This inconsistency can cause confusion and errors and is another reason why `let` and `const` should be used instead of `var`. ## Summary diff --git a/files/en-us/learn_web_development/howto/solve_javascript_problems/index.md b/files/en-us/learn_web_development/howto/solve_javascript_problems/index.md index 63e72e3afd595a6..595bf7404b5a9d9 100644 --- a/files/en-us/learn_web_development/howto/solve_javascript_problems/index.md +++ b/files/en-us/learn_web_development/howto/solve_javascript_problems/index.md @@ -168,7 +168,7 @@ For more information on JavaScript debugging, see [JavaScript debugging and erro - [How do you create your own functions?](/en-US/docs/Learn_web_development/Core/Scripting/Build_your_own_function) - [How do you run (call, or invoke) a function?](/en-US/docs/Learn_web_development/Core/Scripting/Functions#invoking_functions) - [What is an anonymous function?](/en-US/docs/Learn_web_development/Core/Scripting/Functions#anonymous_functions_and_arrow_functions) -- [How do you specify parameters (or arguments) when invoking a function?](/en-US/docs/Learn_web_development/Core/Scripting/Functions#function_parameters) +- [How do you specify parameters (or arguments) when invoking a function?](/en-US/docs/Learn_web_development/Core/Scripting/Functions#function_arguments_and_parameters) - [What is function scope?](/en-US/docs/Learn_web_development/Core/Scripting/Functions#function_scope_and_conflicts) - [What are return values, and how do you use them?](/en-US/docs/Learn_web_development/Core/Scripting/Return_values) diff --git a/files/en-us/mozilla/firefox/releases/153/index.md b/files/en-us/mozilla/firefox/releases/153/index.md index 3e9b92e030cf100..1aade70ded9806e 100644 --- a/files/en-us/mozilla/firefox/releases/153/index.md +++ b/files/en-us/mozilla/firefox/releases/153/index.md @@ -64,7 +64,11 @@ Firefox 153 is the current [Beta version of Firefox](https://www.firefox.com/en- This provides a convenient mechanism for websites to toggle display of a {{htmlelement("video")}} element between a page and a floating always-on-top video window, allowing users to continue watching while they interact with other sites or applications. ([Firefox bug 1463402](https://bugzil.la/1463402)). - +#### DOM + +- The [Popover API](/en-US/docs/Web/API/Popover_API) now has more consistent behavior when [`hint` and `auto` popovers are opened and closed](/en-US/docs/Web/API/Popover_API/Using#popover_openclose_interaction_rules). + This follows the specification update in [whatwg/html#12345](https://github.com/whatwg/html/pull/12345). + ([Firefox bug 2029974](https://bugzil.la/2029974)). #### Media, WebRTC, and Web Audio @@ -82,7 +86,9 @@ Firefox 153 is the current [Beta version of Firefox](https://www.firefox.com/en- - +### WebAssembly + +- JavaScript Promise Integration (JS-PI) is now enabled, allowing [WebAssembly](/en-US/docs/WebAssembly) modules to interoperate with asynchronous, {{jsxref("Promise")}}-based JavaScript APIs. This lets WebAssembly code suspend while waiting for a JavaScript promise and resume when the promise settles. See [`WebAssembly.Suspending`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Suspending) for an explanation and working example. ([Firefox bug 2044809](https://bugzil.la/2044809)). diff --git a/files/en-us/webassembly/reference/javascript_interface/compileerror/compileerror/index.md b/files/en-us/webassembly/reference/javascript_interface/compileerror/compileerror/index.md index c284c3171aa8dd9..a4ac5fcbd84aa20 100644 --- a/files/en-us/webassembly/reference/javascript_interface/compileerror/compileerror/index.md +++ b/files/en-us/webassembly/reference/javascript_interface/compileerror/compileerror/index.md @@ -45,7 +45,7 @@ details to the console: try { throw new WebAssembly.CompileError("Hello", "someFile", 10); } catch (e) { - console.log(e instanceof CompileError); // true + console.log(e instanceof WebAssembly.CompileError); // true console.log(e.message); // "Hello" console.log(e.name); // "CompileError" console.log(e.fileName); // "someFile" diff --git a/files/en-us/webassembly/reference/javascript_interface/compileerror/index.md b/files/en-us/webassembly/reference/javascript_interface/compileerror/index.md index 1f4cdeec105eb0c..423c9428ed6030a 100644 --- a/files/en-us/webassembly/reference/javascript_interface/compileerror/index.md +++ b/files/en-us/webassembly/reference/javascript_interface/compileerror/index.md @@ -45,7 +45,7 @@ The following snippet creates a new `CompileError` instance, and logs its detail try { throw new WebAssembly.CompileError("Hello", "someFile", 10); } catch (e) { - console.log(e instanceof CompileError); // true + console.log(e instanceof WebAssembly.CompileError); // true console.log(e.message); // "Hello" console.log(e.name); // "CompileError" console.log(e.fileName); // "someFile" diff --git a/files/en-us/webassembly/reference/javascript_interface/index.md b/files/en-us/webassembly/reference/javascript_interface/index.md index 162a519081c8781..32be18d633e52eb 100644 --- a/files/en-us/webassembly/reference/javascript_interface/index.md +++ b/files/en-us/webassembly/reference/javascript_interface/index.md @@ -34,6 +34,8 @@ The primary uses for the `WebAssembly` object are: - : Contains stateless WebAssembly code that has already been compiled by the browser and can be efficiently [shared with Workers](/en-US/docs/Web/API/Worker/postMessage), and instantiated multiple times. - [`WebAssembly.RuntimeError`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/RuntimeError) - : Error type that is thrown whenever WebAssembly specifies a [trap](https://webassembly.github.io/simd/core/intro/overview.html#trap). +- [`WebAssembly.Suspending`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Suspending) + - : Represents a suspending function — an asynchronous ({{jsxref("Promise")}}-based) JavaScript function that, when imported into a Wasm module and called from inside, will result in execution being suspended until the promise resolves. - [`WebAssembly.Table`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Table) - : An array-like structure representing a WebAssembly Table, which stores [references](https://webassembly.github.io/spec/core/syntax/types.html#syntax-reftype), such as function references. - [`WebAssembly.Tag`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Tag) @@ -56,6 +58,8 @@ The primary uses for the `WebAssembly` object are: - : The primary API for compiling and instantiating WebAssembly code, returning both a `Module` and its first `Instance`. - [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/instantiateStreaming_static) - : Compiles and instantiates a WebAssembly module directly from a streamed underlying source, returning both a `Module` and its first `Instance`. +- [`WebAssembly.promising()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/promising_static) + - : Wraps an exported Wasm function that relies on an asynchronous operation (that is, an imported suspending function created via the [`WebAssembly.Suspending()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Suspending/Suspending) constructor), turning it into a {{jsxref("Promise")}}. - [`WebAssembly.validate()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/validate_static) - : Validates a given typed array of WebAssembly binary code, returning whether the bytes are valid WebAssembly code (`true`) or not (`false`). diff --git a/files/en-us/webassembly/reference/javascript_interface/linkerror/index.md b/files/en-us/webassembly/reference/javascript_interface/linkerror/index.md index 16901b05876b252..c05fa0484f9af4b 100644 --- a/files/en-us/webassembly/reference/javascript_interface/linkerror/index.md +++ b/files/en-us/webassembly/reference/javascript_interface/linkerror/index.md @@ -45,7 +45,7 @@ The following snippet creates a new `LinkError` instance, and logs its details t try { throw new WebAssembly.LinkError("Hello", "someFile", 10); } catch (e) { - console.log(e instanceof LinkError); // true + console.log(e instanceof WebAssembly.LinkError); // true console.log(e.message); // "Hello" console.log(e.name); // "LinkError" console.log(e.fileName); // "someFile" diff --git a/files/en-us/webassembly/reference/javascript_interface/linkerror/linkerror/index.md b/files/en-us/webassembly/reference/javascript_interface/linkerror/linkerror/index.md index 3a4d30a02f1d0eb..4181cd449798d72 100644 --- a/files/en-us/webassembly/reference/javascript_interface/linkerror/linkerror/index.md +++ b/files/en-us/webassembly/reference/javascript_interface/linkerror/linkerror/index.md @@ -46,7 +46,7 @@ details to the console: try { throw new WebAssembly.LinkError("Hello", "someFile", 10); } catch (e) { - console.log(e instanceof LinkError); // true + console.log(e instanceof WebAssembly.LinkError); // true console.log(e.message); // "Hello" console.log(e.name); // "LinkError" console.log(e.fileName); // "someFile" diff --git a/files/en-us/webassembly/reference/javascript_interface/promising_static/index.md b/files/en-us/webassembly/reference/javascript_interface/promising_static/index.md new file mode 100644 index 000000000000000..93954af96b263fb --- /dev/null +++ b/files/en-us/webassembly/reference/javascript_interface/promising_static/index.md @@ -0,0 +1,64 @@ +--- +title: WebAssembly.promising() +slug: WebAssembly/Reference/JavaScript_interface/promising_static +page-type: webassembly-function +browser-compat: webassembly.api.promising_static +sidebar: webassemblysidebar +--- + +The **`WebAssembly.promising()`** static method is used to wrap an exported Wasm function that relies on an asynchronous operation (that is, an imported suspending function created via the [`WebAssembly.Suspending()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Suspending/Suspending) constructor), turning it into a {{jsxref("Promise")}}. + +See [`WebAssembly.Suspending`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Suspending) for an explanation of how this functionality works. + +## Syntax + +```js-nolint +WebAssembly.promising(function) +``` + +### Parameters + +- `function` + - : A reference to an exported Wasm function, typically available on the [`exports`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Instance/exports) object available in the fulfilled value of a method such as [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/instantiateStreaming_static). + +### Return value + +A function that wraps the original function passed into the `promising()` call, and can itself be called. The wrapper function takes the same arguments as the wrapped function, and returns a promise that fulfills with the wrapped function's results. + +### Exceptions + +- {{jsxref("TypeError")}} + - : The referenced `function` is not callable. + +## Examples + +### Basic usage + +```js +WebAssembly.instantiateStreaming(fetch("module.wasm"), { importObj }).then( + (result) => { + const fromWasm = WebAssembly.promising( + result.instance.exports.exportedFunc, + ); + fromWasm().then((result) => { + // ... + }); + }, +); +``` + +See [`WebAssembly.Suspending`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Suspending) for a full working example. + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [`WebAssembly.Suspending`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Suspending) +- [`WebAssembly.Suspending()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Suspending/Suspending) constructor +- [WebAssembly](/en-US/docs/WebAssembly) overview diff --git a/files/en-us/webassembly/reference/javascript_interface/suspenderror/index.md b/files/en-us/webassembly/reference/javascript_interface/suspenderror/index.md new file mode 100644 index 000000000000000..0e37468425520ed --- /dev/null +++ b/files/en-us/webassembly/reference/javascript_interface/suspenderror/index.md @@ -0,0 +1,70 @@ +--- +title: WebAssembly.SuspendError +slug: WebAssembly/Reference/JavaScript_interface/SuspendError +page-type: webassembly-interface +browser-compat: webassembly.api.SuspendError +sidebar: webassemblysidebar +--- + +The **`WebAssembly.SuspendError`** object indicates an error during WebAssembly [function suspension](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Suspending). + +## Constructor + +- [`WebAssembly.SuspendError()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/SuspendError/SuspendError) + - : Creates a new `WebAssembly.SuspendError` object. + +## Instance properties + +- {{jsxref("Error.prototype.message", "WebAssembly.SuspendError.prototype.message")}} + - : Error message. Inherited from {{jsxref("Error")}}. +- {{jsxref("Error.prototype.name", "WebAssembly.SuspendError.prototype.name")}} + - : Error name. Inherited from {{jsxref("Error")}}. +- {{jsxref("Error.prototype.cause", "WebAssembly.SuspendError.prototype.cause")}} + - : Error cause. Inherited from {{jsxref("Error")}}. +- {{jsxref("Error.prototype.fileName", "WebAssembly.SuspendError.prototype.fileName")}} {{non-standard_inline}} + - : Path to file that raised this error. Inherited from {{jsxref("Error")}}. +- {{jsxref("Error.prototype.lineNumber", "WebAssembly.SuspendError.prototype.lineNumber")}} {{non-standard_inline}} + - : Line number in file that raised this error. Inherited from {{jsxref("Error")}}. +- {{jsxref("Error.prototype.columnNumber", "WebAssembly.SuspendError.prototype.columnNumber")}} {{non-standard_inline}} + - : Column number in line that raised this error. Inherited from {{jsxref("Error")}}. +- {{jsxref("Error.prototype.stack", "WebAssembly.SuspendError.prototype.stack")}} {{non-standard_inline}} + - : Stack trace. Inherited from {{jsxref("Error")}}. + +## Instance methods + +- {{jsxref("Error.prototype.toString", "WebAssembly.SuspendError.prototype.toString()")}} + - : Returns a string representing the specified `Error` object. Inherited from {{jsxref("Error")}}. + +## Examples + +### Creating a new SuspendError instance + +The following snippet creates a new `SuspendError` instance, and logs its details to the console: + +```js +try { + throw new WebAssembly.SuspendError("Hello", "someFile", 10); +} catch (e) { + console.log(e instanceof WebAssembly.SuspendError); // true + console.log(e.message); // "Hello" + console.log(e.name); // "SuspendError" + console.log(e.fileName); // "someFile" + console.log(e.lineNumber); // 10 + console.log(e.columnNumber); // 0 + console.log(e.stack); // The location where the code was run +} +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [`WebAssembly.Suspending`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Suspending) +- [WebAssembly](/en-US/docs/WebAssembly) overview +- [WebAssembly concepts](/en-US/docs/WebAssembly/Guides/Concepts) diff --git a/files/en-us/webassembly/reference/javascript_interface/suspenderror/suspenderror/index.md b/files/en-us/webassembly/reference/javascript_interface/suspenderror/suspenderror/index.md new file mode 100644 index 000000000000000..46005d8ea6715f6 --- /dev/null +++ b/files/en-us/webassembly/reference/javascript_interface/suspenderror/suspenderror/index.md @@ -0,0 +1,70 @@ +--- +title: WebAssembly.SuspendError() constructor +slug: WebAssembly/Reference/JavaScript_interface/SuspendError/SuspendError +page-type: webassembly-constructor +browser-compat: webassembly.api.SuspendError.SuspendError +sidebar: webassemblysidebar +--- + +The **`WebAssembly.SuspendError()`** constructor creates a new +WebAssembly `SuspendError` object, which indicates an error during +WebAssembly [function suspension](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Suspending). + +## Syntax + +```js-nolint +new WebAssembly.SuspendError() +new WebAssembly.SuspendError(message) +new WebAssembly.SuspendError(message, options) +new WebAssembly.SuspendError(message, fileName) +new WebAssembly.SuspendError(message, fileName, lineNumber) +``` + +### Parameters + +- `message` {{optional_inline}} + - : Human-readable description of the error. +- `options` {{optional_inline}} + - : An object that has the following properties: + - `cause` {{optional_inline}} + - : A property indicating the specific cause of the error. + When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. +- `fileName` {{optional_inline}} {{non-standard_inline}} + - : The name of the file containing the code that caused the exception. +- `lineNumber` {{optional_inline}} {{non-standard_inline}} + - : The line number of the code that caused the exception. + +## Examples + +### Creating a new SuspendError instance + +The following snippet creates a new `SuspendError` instance, and logs its +details to the console: + +```js +try { + throw new WebAssembly.SuspendError("Hello", "someFile", 10); +} catch (e) { + console.log(e instanceof WebAssembly.SuspendError); // true + console.log(e.message); // "Hello" + console.log(e.name); // "SuspendError" + console.log(e.fileName); // "someFile" + console.log(e.lineNumber); // 10 + console.log(e.columnNumber); // 0 + console.log(e.stack); // The location where the code was run +} +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [`WebAssembly.Suspending`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Suspending) +- [WebAssembly](/en-US/docs/WebAssembly) overview +- [WebAssembly concepts](/en-US/docs/WebAssembly/Guides/Concepts) diff --git a/files/en-us/webassembly/reference/javascript_interface/suspending/index.md b/files/en-us/webassembly/reference/javascript_interface/suspending/index.md new file mode 100644 index 000000000000000..1ee844927703943 --- /dev/null +++ b/files/en-us/webassembly/reference/javascript_interface/suspending/index.md @@ -0,0 +1,151 @@ +--- +title: WebAssembly.Suspending +slug: WebAssembly/Reference/JavaScript_interface/Suspending +page-type: webassembly-interface +browser-compat: webassembly.api.Suspending +sidebar: webassemblysidebar +--- + +The **`WebAssembly.Suspending`** object represents a suspending function — an asynchronous ({{jsxref("Promise")}}-based) JavaScript function that, when imported into a Wasm module and called from inside, will result in execution being suspended until the promise resolves. + +> [!NOTE] +> The only purpose of `WebAssembly.Suspending` is to mark which imported functions are suspending functions when passing them into a Wasm module imports object. + +## Constructor + +- [`WebAssembly.Suspending()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Suspending/Suspending) + - : Creates a new `Suspending` object instance. + +## Description + +The `Suspending` interface — along with its counterpart [`WebAssembly.promising()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/promising_static) method — enables WebAssembly modules to interact with asynchronous JavaScript host functions. + +To use this functionality, you first need to wrap `Promise`-based functions inside a `WebAssembly.Suspending()` constructor call when importing them: + +```js +function someAsyncFunction() { + return fetch("https://example.com").then((result) => { + // ... + }); +} + +const importObj = { + someAsyncFunction: new WebAssembly.Suspending(someAsyncFunction), +}; +``` + +This creates a suspending function. No changes are necessary to use it inside the Wasm module: when it is called, execution is suspended until the `Promise` resolves, then resumed with the resolving value available on the stack. However, when exporting a Wasm function that relies on the suspending imported function back to the JavaScript host, you need to wrap the export in a `WebAssembly.promising()` call: + +```js +WebAssembly.instantiateStreaming(fetch("module.wasm"), { importObj }).then( + (result) => { + const fromWasm = WebAssembly.promising( + result.instance.exports.exportedFunc, + ); + fromWasm().then((result) => { + // ... + }); + }, +); +``` + +This effectively turns the export into a promise, which resolves once the imported JavaScript function resolves and allows the exported Wasm function's execution to complete. + +## Examples + +### Integrating a promise into a Wasm application + +This example shows how to import a JavaScript `Promise`-based function into a Wasm module, call it inside an exported Wasm function, and then call the exported function from the JavaScript host to obtain a result. + +#### HTML + +In our markup we include a {{htmlelement("button")}} element to start the application, and a {{htmlelement("p")}} element to output the obtained result into. + +```html live-sample___jspi + +
+

+``` + +#### Wasm + +Our Wasm module first imports a `double()` function, which takes an [`i32`](/en-US/docs/WebAssembly/Reference/Value_types/i32) parameter and returns an `i32` result. It then defines an exported `add()` function, which also takes and returns an `i32`. The `add()` function pushes a constant onto the stack and feeds that into the imported `double()` function, then [adds](/en-US/docs/WebAssembly/Reference/Numeric/add) the result to its parameter. + +```wat live-sample___jspi +(module + (import "importObj" "double" (func $double (param i32) (result i32))) + (func (export "add") (param i32) (result i32) + (i32.const 20) + call $double + (local.get 0) + + i32.add ;; add the two values + ) +) +``` + +#### JavaScript + +In our script, we first grab references to the `

` and `