Search completed in 1.24 seconds.
undefined - JavaScript
The global
undefined property represents the primitive value
undefined. It is one of JavaScript's primitive types. Property attributes of
undefined Writable no Enumerable no Configurable no The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax
undefined Description
undefined is a property of the global object. That is, it is a variable in global scope. The initial value of
undefined is the primitive value
undefined. ...
...pository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax
undefined Description
undefined is a property of the global object. That is, it is a variable in global scope. The initial value of
undefined is the primitive value
undefined. In modern browsers (JavaScript 1.8.5 / Firefox 4+),
undefined is a non-configurable, non-writable property, per the ECMAScript 5 specification. (Even when this is not the case, avoid overriding it.) A variable that has not been assigned a value is of type
undefined. A method or statement also returns
undefined if the variable that is being evaluated does not have an assigned value. A function returns
undefined if a value was not returned. Be careful. Whi...
...ase, avoid overriding it.) A variable that has not been assigned a value is of type
undefined. A method or statement also returns
undefined if the variable that is being evaluated does not have an assigned value. A function returns
undefined if a value was not returned. Be careful. While it is possible to use it as an identifier (variable name) in any scope other than the global scope (because
undefined is not a reserved word), doing so is a very bad idea that will make your code difficult to maintain and debug. ...
...And 6 more matches
undefined - MDN Web Docs Glossary: Definitions of Web-related terms
undefined is a primitive value automatically assigned to variables that have just been declared, or to formal arguments for which there are no actual arguments. ...
...
undefined is a primitive value automatically assigned to variables that have just been declared, or to formal arguments for which there are no actual arguments. ...
...
undefined is a primitive value automatically assigned to variables that have just been declared, or to formal arguments for which there are no actual arguments. Example var x; //create a variable but assign it no value console.log("x's value is", x) //logs "x's value is
undefined" Learn more General knowledge
Undefined value on Wikipedia Technical reference JavaScript data types and data structures ...
ReferenceError: reference to undefined property "x" - JavaScript
The JavaScript warning "reference to
undefined property" occurs when a script attempted to access an object property which doesn't exist. Message ReferenceError: reference to
undefined property "x" (Firefox) Error type (Firefox only) ReferenceError warning which is reported only if javascript.options.strict preference is set to true. What went wrong? ...
...refox) Error type (Firefox only) ReferenceError warning which is reported only if javascript.options.strict preference is set to true. What went wrong? The script attempted to access an object property which doesn't exist. There are two ways to access properties; see the property accessors reference page to learn more about them. ...
...ct preference is set to true. What went wrong? ...
JS_SetAllNonReservedSlotsToUndefined
This article covers features introduced in SpiderMonkey 24 Assign
undefined to all of the object's non-reserved slots. Note: This is done for all slots, regardless of the associated property descriptor. Syntax void JS_SetAllNonReservedSlotsTo
Undefined(JSContext *cx, JSObject *objArg); Name Type Description cx JSContext * The context in which to clear the object. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JSObject * Object from which to delete all properties. Description JS_SetAllNonReservedSlotsTo
Undefined assignes
undefined to all of obj's own properties, except the special __proto__ and __parent__ properties, in a single operation. Properties belonging to objects on o...
...SContext. obj JSObject * Object from which to delete all properties. Description JS_SetAllNonReservedSlotsTo
Undefined assignes
undefined to all of obj's own properties, except the special __proto__ and __parent__ properties, in a single operation. ...
JS::UndefinedHandleValue
This article covers features introduced in SpiderMonkey 24 The JS::Value that represents the JavaScript value
undefined. Syntax const JS::HandleValue JS::
UndefinedHandleValue; Description JS::
UndefinedHandleValue is a JS::HandleValue constant that represents the JavaScript value
undefined. See Also MXR ID Search for JS::
UndefinedHandleValue JS::NullHandleValue JS::TrueHandleValue JS::FalseHandleValue bug 865969 ...
JS::UndefinedValue
This article covers features introduced in SpiderMonkey 24 Create a JS::Value that represents the JavaScript value
undefined. Syntax JS::Value JS::
UndefinedValue(); Description JS::
UndefinedValue creates a JS::Value that represents the JavaScript value
undefined. See Also MXR ID Search for JS::
UndefinedValue JS::Value JS::
UndefinedHandleValue ...
Assert.jsm
ion version 1.1, which provides a basic, standardized interface for performing in-code logical assertions with optional, customizable error reporting. To use it, you first need to import the code module into your JavaScript scope: Components.utils.import("resource://testing-common/Assert.jsm"); The Assert class offers methods for performing common logical assertions. ...
..., standardized interface for performing in-code logical assertions with optional, customizable error reporting. To use it, you first need to import the code module into your JavaScript scope: Components.utils.import("resource://testing-common/Assert.jsm"); The Assert class offers methods for performing common logical assertions. ...
...al assertions with optional, customizable error reporting. To use it, you first need to import the code module into your JavaScript scope: Components.utils.import("resource://testing-common/Assert.jsm"); The Assert class offers methods for performing common logical assertions. ...
...And 19 more matches
Bytecode Descriptions
Null Stack: => null Push null. False, True Stack: => true/false Push a boolean constant. Int32 Operands: (int32_t val) Stack: => val Push the int32_t immediate operand as an Int32Value. JSOp::Zero, JSOp::One, JSOp::Int8, JSOp::Uint16, and JSOp::Uint24 are all compact encodings for JSOp::Int32. Zero Stack: => 0 Push the number 0. One Stack: => 1 Push the number 1. Int8 Operands: (int8_t val) Stack: => val Push the int8_t immediate operand as an Int32Value. ...
...h the BigInt constant script->getBigInt(bigIntIndex). String Operands: (uint32_t atomIndex) Stack: => string Push the string constant script->getAtom(atomIndex). Format: JOF_ATOM Symbol Operands: (uint8_t symbol (the JS::SymbolCode of the symbol to use)) Stack: => symbol Push a well-known symbol. symbol must be in range for JS::SymbolCode. Expressions Unary operators Void Stack: val =>
undefined Pop the top value on the stack, discard it, and push
undefined. Implements: The void operator, step 3. Typeof, TypeofExpr Stack: val => (typeof val) The typeof operator. Infallible. The result is always a string that depends on the type of val. JSOp::Typeof and JSOp::TypeofExpr are the same except that--amazingly--JSOp::Typeof affects the behavior of an immediately preceding JSOp::GetName or J...
...eof, TypeofExpr Stack: val => (typeof val) The typeof operator. Infallible. The result is always a string that depends on the type of val. JSOp::Typeof and JSOp::TypeofExpr are the same except that--amazingly--JSOp::Typeof affects the behavior of an immediately preceding JSOp::GetName or JSOp::GetGName instruction! This is how we implement typeof step 2, making typeof nonExistingVariable return "
undefined" instead of throwing a ReferenceError. In a global scope: typeof x compiles to GetGName "x"; Typeof. typeof (0, x) compiles to GetGName "x"; TypeofExpr. Emitting the same bytecode for these two expressions would be a bug. Per spec, the latter throws a ReferenceError if x doesn't exist. Format: JOF_IC Pos Stack: val => (+val) The unary + operator. +val doesn't do any actual math. It just call...
...And 16 more matches
Index - Web APIs
ode.playbackRate API, AudioBufferSourceNode, Property, Reference, Web Audio API, playbackRate The playbackRate property of the AudioBufferSourceNode interface Is a k-rate AudioParam that defines the speed at which the audio asset will be played. 120 AudioBufferSourceNode.start() API, Audio, AudioBufferSourceNode, Media, Method, Reference, Web Audio API, sound, start
undefined. 121 AudioConfiguration API, Audio, AudioConfiguration, Experimental, Interface, Media Capabilities API, Reference, Video The AudioConfiguration dictionary of the Media Capabilities API defines the audio file being tested when calling MediaCapabilities.encodingInfo() or MediaCapabilities.decodingInfo() to query whether a specific audio configuration is supported, smooth, and/...
...ng the AudioNode.channelInterpretation property to speakers or discrete: 160 AudioNode.connect() API, Audio, AudioNode, Media, Method, Reference, Web Audio API, connect If the destination is a node, connect() returns a reference to the destination AudioNode object, allowing you to chain multiple connect() calls. In some browsers, older implementations of this interface return
undefined. 161 AudioNode.context API, AudioNode, Context, Property, Reference, Web Audio API The read-only context property of the AudioNode interface returns the associated BaseAudioContext, that is the object representing the processing graph the node is participating in. 162 AudioNode.disconnect() API, Audio, AudioNode, Disconnect, Method, Reference, Web Audio API ...
... 161 AudioNode.context API, AudioNode, Context, Property, Reference, Web Audio API The read-only context property of the AudioNode interface returns the associated BaseAudioContext, that is the object representing the processing graph the node is participating in. 162 AudioNode.disconnect() API, Audio, AudioNode, Disconnect, Method, Reference, Web Audio API
undefined 163 AudioNode.numberOfInputs API, AudioNode, Property, Reference, Web Audio API, numberOfInputs The numberOfInputs property of the AudioNode interface returns the number of inputs feeding the node. 164 AudioNode.numberOfOutputs API, AudioNode, Property, Reference, Web Audio API, numberOfOutputs The numberOfOutputs property of the AudioNode interface retur...
...And 14 more matches
Debugger.Object - Firefox Developer Tools
cripted proxy or some other sort of exotic object (an opaque wrapper, for example). class A string naming the ECMAScript [[Class]] of the referent. callable true if the referent is a callable object (such as a function or a function proxy); false otherwise. name The name of the referent, if it is a named function. If the referent is an anonymous function, or not a function at all, this is
undefined. This accessor returns whatever name appeared after the function keyword in the source code, regardless of whether the function is the result of instantiating a function declaration (which binds the function to its name in the enclosing scope) or evaluating a function expression (which binds the function to its name only within the function's body). displayName The referent's display name...
...tion is the result of instantiating a function declaration (which binds the function to its name in the enclosing scope) or evaluating a function expression (which binds the function to its name only within the function's body). displayName The referent's display name, if the referent is a function with a display name. If the referent is not a function, or if it has no display name, this is
undefined. If a function has a given name, its display name is the same as its given name. In this case, the displayName and name properties are equal. If a function has no name, SpiderMonkey attempts to infer an appropriate name for it given its context. For example: function f() {} // display name: f (the given name) var g = function () {}; // display name: g o.p = function () {}; // d...
...ion that is assigned toa. For example: function h() { var i = function() {}; // display name: h/i f(function () {}); // display name: h/< } var s = f(function () {}); // display name: s< parameterNames If the referent is a debuggee function, the names of the its parameters, as an array of strings. If the referent is not a debuggee function, or not a function at all, this is
undefined. If the referent is a host function for which parameter names are not available, return an array with one element per parameter, each of which is
undefined. If the referent is a function proxy, return an empty array. If the referent uses destructuring parameters, then the array's elements reflect the structure of the parameters. For example, if the referent is a function declared in this wa...
...And 12 more matches
Index
S::TrueHandleValue JSAPI Reference, Reference, Reference(2), SpiderMonkey JS::TrueHandleValue and JS::FalseHandleValue are JS::HandleValue constants that represent the JavaScript values true and false. 82 JS::TrueValue JSAPI Reference, Reference, Reference(2), SpiderMonkey JS::TrueValue creates a JS::Value that represents the JavaScript value true. 83 JS::
UndefinedHandleValue JSAPI Reference, Reference, Reference(2), SpiderMonkey JS::
UndefinedHandleValue is a JS::HandleValue constant that represents the JavaScript value
undefined. 84 JS::
UndefinedValue JSAPI Reference, Reference, Reference(2), SpiderMonkey JS::
UndefinedValue creates a JS::Value that represents the JavaScript value
undefined. 85 JS::Value JSAPI R...
... 86 JSAutoByteString JSAPI Reference, Reference, Reference(2), SpiderMonkey JSAutoByteString takes the ownership of string and frees it in destructor. ...
...L_IS_NUMBER JSAPI Reference, Obsolete, SpiderMonkey JSVAL_IS_NUMBER(v) is true if v is a JavaScript number. 164 JSVAL_IS_OBJECT JSAPI Reference, Obsolete, SpiderMonkey JSVAL_IS_OBJECT(v) returns true if v is either an object or JSVAL_NULL. This indicates that it is safe to call JSVAL_TO_OBJECT(v) to convert v to type JSObject *. If v is a string, number, boolean, or
undefined, the result is false. 165 JSVAL_IS_PRIMITIVE JSAPI Reference, Obsolete, SpiderMonkey JSVAL_IS_PRIMITIVE(v) is true if v is
undefined, null, a boolean, a number, or a string. Otherwise it is false, and v is an object. 166 JSVAL_IS_STRING JSAPI Reference, Obsolete, SpiderMonkey JSVAL_IS_STRING(v) is true if v is a string. 167 JSVAL_IS_VOID JS...
...And 11 more matches
Grammar and types - JavaScript
ly assign a value to a variable For example, x = 42. This form creates an undeclared global variable. It also generates a strict JavaScript warning. Undeclared global variables can often lead to unexpected behavior. Thus, it is discouraged to use undeclared global variables. Evaluating variables A variable declared using the var or let statement with no assigned value specified has the value of
undefined. ...
... can often lead to unexpected behavior. Thus, it is discouraged to use undeclared global variables. Evaluating variables A variable declared using the var or let statement with no assigned value specified has the value of
undefined. ...
...undeclared global variables. Evaluating variables A variable declared using the var or let statement with no assigned value specified has the value of
undefined. An attempt to access an undeclared variable results in a ReferenceError exception being thrown: var a; console.log('The value of a is ' + a); // The value of a is
undefined console.log('The value of b is ' + b); // The value of b is
undefined var b; // This one may puzzle you until you read 'Variable hoisting' below console.log('The value of c is ' + c); // Uncaught ReferenceError: c is not defined let x; console.log('The value of x is ' + x); // The value of x is
undefined console.log('The value of y is ' + y); // Uncaught ReferenceError: y is not defined let y; You can use
undefined to determine whether a variable has a value. ...
...And 11 more matches
Nullish coalescing operator (??) - JavaScript
In other words, if you use || to provide some default value to another variable foo, you may encounter unexpected behaviors if you consider some falsy values as usable (eg. '' or 0). See below for more examples. The source for this interactive example is stored in a GitHub repository. ...
...In other words, if you use || to provide some default value to another variable foo, you may encounter unexpected behaviors if you consider some falsy values as usable (eg. '' or 0). See below for more examples. The source for this interactive example is stored in a GitHub repository. ...
...stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. See PR #1482 regarding the addition of this example. Syntax leftExpr ?? rightExpr Examples Using the nullish coalescing operator In this example, we will provide default values but keep values other than null or
undefined. ...
...And 11 more matches
jspage - Archive of obsolete content
ngth;b<a;b++){c.call(d,this[b],b,this);}}});Array.alias("forEach","each"); function $A(b){if(b.item){var a=b.length,c=new Array(a);while(a--){c[a]=b[a];}return c;}return Array.prototype.slice.call(b);}function $arguments(a){return function(){return arguments[a]; };}function $chk(a){return !!(a||a===0);}function $clear(a){clearTimeout(a);clearInterval(a);return null;}function $defined(a){return(a!=
undefined);}function $each(c,b,d){var a=$type(c); ((a=="arguments"||a=="collection"||a=="array")?Array:Hash).each(c,b,d);}function $empty(){}function $extend(c,a){for(var b in (a||{})){c[b]=a[b];}return c; }function $H(a){return new Hash(a);}function $lambda(a){return($type(a)=="function")?a:function(){return a;};}function $merge(){var a=Array.slice(arguments); a.unshift({});return $mixin.apply(null,a);}fu...
...;};}function $merge(){var a=Array.slice(arguments); a.unshift({});return $mixin.apply(null,a);}function $mixin(e){for(var d=1,a=arguments.length;d<a;d++){var b=arguments[d];if($type(b)!="object"){continue; }for(var c in b){var g=b[c],f=e[c];e[c]=(f&&$type(g)=="object"&&$type(f)=="object")?$mixin(f,g):$unlink(g);}}return e;}function $pick(){for(var b=0,a=arguments.length; b<a;b++){if(arguments[b]!=
undefined){return arguments[b];}}return null;}function $random(b,a){return Math.floor(Math.random()*(a-b+1)+b);}function $splat(b){var a=$type(b); return(a)?((a!="array"&&a!="arguments")?[b]:b):[];}var $time=Date.now||function(){return +new Date;};function $try(){for(var b=0,a=arguments.length;b<a; b++){try{return arguments[b]();}catch(c){}}return null;}function $type(a){if(a==
undefined){return false;}if(a...
...rn"arguments"; }else{if(a.item){return"collection";}}}}return typeof a;}function $unlink(c){var b;switch($type(c)){case"object":b={};for(var e in c){b[e]=$unlink(c[e]); }break;case"hash":b=new Hash(c);break;case"array":b=[];for(var d=0,a=c.length;d<a;d++){b[d]=$unlink(c[d]);}break;default:return c;}return b;}var Browser=$merge({Engine:{name:"unknown",version:0},Platform:{name:(window.orientation!=
undefined)?"ipod":(navigator.platform.match(/mac|win|linux/i)||["other"])[0].toLowerCase()},Features:{xpath:!!(document.evaluate),air:!!(window.runtime),query:!!(document.querySelector)},Plugins:{},Engines:{presto:function(){return(!window.opera)?false:((arguments.callee.caller)?960:((document.getElementsByClassName)?950:925)); },trident:function(){return(!window.ActiveXObject)?false:((window.XMLHttpReques...
...And 10 more matches
Old Proxy API - Archive of obsolete content
oxy's prototype (defaults to null if none is provided). callTrap is a variable-argument function(args) { return any; } that reifies "proxy(args)". Note: The this-binding of the callTrap function is the this-binding of the call-site. constructTrap is an optional variable-argument function(args) { return any-object; } that reifies "new proxy(args)". The this-binding of the constructTrap is either
undefined (in strict mode) or the global object (in non-strict mode). If no constructTrap is provided, performing new proxy(...args) calls the proxy's callTrap with this bound to a new object delegating to the proxy's prototype. handler is an object that implements the handler API. Handler API There are two kinds of traps: fundamental and derived traps. If one of the fundamental traps isn't implemented...
...ents the handler API. Handler API There are two kinds of traps: fundamental and derived traps. If one of the fundamental traps isn't implemented and the proxy is used in a way that expects the fundamental trap to be defined, then an error is thrown. If a derived trap is implemented, then that trap's code is called whenever the corresponding behavior happens on the proxy. ...
...pens on the proxy. If the derived trap is
undefined, a default implementation using the fundamental traps is used. In other words: fundamental traps are required, derived traps are optional. Fundamental traps Emulated JavaScript code Handler method Description Object.getOwnPropertyDescriptor(proxy, name) getOwnPropertyDescriptor: function(name) -> PropertyDescriptor |
undefined Should return a valid property descriptor object, or
undefined to indicate that no property with name exists in the emulated object. Object.getPropertyDescriptor(proxy, name) getPropertyDescriptor: function(name) -> PropertyDescriptor |
undefined This function doesn't exist in ECMAScript 5. Like getOwnPropertyDescriptor, but should also search the prototype chain. Objec...
...And 10 more matches
Default parameters - JavaScript
Default function parameters allow named parameters to be initialized with default values if no value or
undefined is passed. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) { statements } Description In JavaScript, function parameters default to
undefined. However, it's often useful to set a different default value. This is where default parameters can help. In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are
undefined. In the following example,...
...ipt, function parameters default to
undefined. However, it's often useful to set a different default value. This is where default parameters can help. In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are
undefined. In the following example, if no value is provided for b when multiply is called, b's value would be
undefined when evaluating a * b and multiply would return NaN. ...
... provided for b when multiply is called, b's value would be
undefined when evaluating a * b and multiply would return NaN. function multiply(a, b) { return a * b } multiply(5, 2) // 10 multiply(5) // NaN ! ...
...And 9 more matches
Border-image generator - CSS: Cascading Style Sheets
r_left); node.appendChild(input); node.appendChild(slider_right); this.input = input; sliders[topic] = this; setValue(topic, value); }; InputSlider.prototype.setInputValue = function setInputValue() { this.input.value = this.value.toFixed(this.precision) + this.unit; }; var setValue = function setValue(topic, value, send_notify) { var slider = sliders[topic]; if (slider ===
undefined) return; value = parseFloat(value.toFixed(slider.precision)); if (value > slider.max) value = slider.max; if (value < slider.min) value = slider.min; slider.value = value; slider.node.setAttribute('data-value', value); slider.setInputValue(); if (send_notify === false) return; notify.call(slider); }; var setMax = function setMax(topic, value) { var slider = slider...
...seFloat(value.toFixed(slider.precision)); if (value > slider.max) value = slider.max; if (value < slider.min) value = slider.min; slider.value = value; slider.node.setAttribute('data-value', value); slider.setInputValue(); if (send_notify === false) return; notify.call(slider); }; var setMax = function setMax(topic, value) { var slider = sliders[topic]; if (slider ===
undefined) return; slider.max = value; setValue(topic, slider.value); }; var setMin = function setMin(topic, value) { var slider = sliders[topic]; if (slider ===
undefined) return; slider.min = value; setValue(topic, slider.value); }; var setUnit = function setUnit(topic, unit) { var slider = sliders[topic]; if (slider ===
undefined) return; slider.unit = unit; setValu...
... slider = sliders[topic]; if (slider ===
undefined) return; slider.min = value; setValue(topic, slider.value); }; var setUnit = function setUnit(topic, unit) { var slider = sliders[topic]; if (slider ===
undefined) return; slider.unit = unit; setValue(topic, slider.value); }; var setStep = function setStep(topic, value) { var slider = sliders[topic]; if (slider ===
undefined) return; slider.step = parseFloat(value); setValue(topic, slider.value); }; var setPrecision = function setPrecision(topic, value) { var slider = sliders[topic]; if (slider ===
undefined) return; value = value | 0; slider.precision = value; var step = parseFloat(slider.step.toFixed(value)); if (step === 0) slider.step = 1 / Math.pow(10, value); setValue(topic, sl...
...And 8 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
ports functional programming -- because they are objects, functions may be stored in variables and passed around like any other object. Let's start off by looking at the building blocks of any language: the types. JavaScript programs manipulate values, and those values all belong to a type. JavaScript's types are: Number String Boolean Function Object Symbol (new in ES2015) ... ...
...Things are a lot easier if we stick with the first diagram, however, so we'll discuss the types listed there for now. Numbers Numbers in JavaScript are "double-precision 64-bit format IEEE 754 values", according to the spec -- There's no such thing as an integer in JavaScript (except BigInt), so you have to be a little careful. ...
... JavaScript has a boolean type, with possible values true and fal...
...And 8 more matches
typeof - JavaScript
e typeof operator is followed by its operand: typeof operand typeof(operand) Parameters operand An expression representing the object or primitive whose type is to be returned. Description The following table summarizes the possible return values of typeof. For more information about types and primitives, see also the JavaScript data structure page. ...
...tor is followed by its operand: typeof operand typeof(operand) Parameters operand An expression representing the object or primitive whose type is to be returned. Description The following table summarizes the possible return values of typeof. For more information about types and primitives, see also the JavaScript data structure page. ...
...n toString // Booleans typeof true === 'boolean'; typeof false === 'boolean'; typeof Boolean(1) === 'boolean'; // Boolean() will convert values based on if they're truthy or falsy typeof !!(1) === 'boolean'; // two calls of the ! ...
...And 8 more matches
Using IndexedDB - Web APIs
we're using the shorthand, so it's event.target.result). Then the actual key and value can be found on the key and value properties of the cursor object. If you want to keep going, then you have to call continue() on the cursor. When you've reached the end of the data (or if there were no entries that matched your openCursor() request) you still get a success callback, but the result property is
undefined. One common pattern with cursors is to retrieve all objects in an object store and add them to an array, like this: var customers = []; objectStore.openCursor().onsuccess = function(event) { var cursor = event.target.result; if (cursor) { customers.push(cursor.value); cursor.continue(); } else { console.log("Got all customers: " + customers); } }; Note: Alternatively, y...
...onFailure(this.error); }; } function getBlob(key, store, success_callback) { var req = store.get(key); req.onsuccess = function(evt) { var value = evt.target.result; if (value) success_callback(value.blob); }; } /** * @param {IDBObjectStore=} store */ function displayPubList(store) { console.log("displayPubList"); if (typeof store == '
undefined') store = getObjectStore(DB_STORE_NAME, 'readonly'); var pub_msg = $('#pub-msg'); pub_msg.empty(); var pub_list = $('#pub-list'); pub_list.empty(); // Resetting the iframe so that it doesn't display previous content newViewerFrame(); var req; req = store.count(); // Requests are executed in the order in which they were made against the // transactio...
... var list_item = $('<li>' + '[' + cursor.key + '] ' + '(biblioid: ' + value.biblioid + ') ' + value.title + '</li>'); if (value.year != null) list_item.append(' - ' + value.year); if (value.hasOwnProperty('blob') && typeof value.blob != '
undefined') { var link = $('<a href="' + cursor.key + '">File</a>'); link.on('click', function() { return false; }); link.on('mouseenter', function(evt) { setInViewer(evt.target.getAttribute('href')); }); list_item.append(' / '); list_item.append(link); } else { list_item.append(" / No attached file"); ...
...And 7 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
ickerMode(topic, mode) { if (pickers[topic]) pickers[topic].setPickerMode(mode); }; var setColor = function setColor(topic, color) { if (pickers[topic]) pickers[topic].setColor(color); }; var getColor = function getColor(topic) { if (pickers[topic]) return new Color(pickers[topic].color); }; var subscribe = function subscribe(topic, callback) { if (subscribers[topic] ===
undefined) subscribers[topic] = []; subscribers[topic].push(callback); }; var unsubscribe = function unsubscribe(callback) { subscribers.indexOf(callback); subscribers.splice(index, 1); }; var notify = function notify(topic, value) { if (subscribers[topic] ===
undefined || subscribers[topic].length === 0) return; var color = new Color(value); for (var i in subscribers[topic]) s...
...v'); dropdown.setAttribute('data-topic', topic); dropdown.className = 'ui-dropdown'; for (var i in options) { var x = document.createElement('div'); x.setAttribute('data-value', i); x.textContent = options[i]; dropdown.appendChild(x); } new DropDown(dropdown); return dropdown; }; var setValue = function setValue(topic, index, send_notify) { if (dropdowns[topic] ===
undefined || index >= dropdowns[topic].dropmenu.children.length) return; dropdowns[topic].setNodeValue(dropdowns[topic].dropmenu.children[index], send_notify); }; var subscribe = function subscribe(topic, callback) { if (subscribers[topic] ===
undefined) subscribers[topic] = []; subscribers[topic].push(callback); }; var unsubscribe = function unsubscribe(topic, callback) { var index...
...tify); }; var subscribe = function subscribe(topic, callback) { if (subscribers[topic] ===
undefined) subscribers[topic] = []; subscribers[topic].push(callback); }; var unsubscribe = function unsubscribe(topic, callback) { var index = subscribers[topic].indexOf(callback); subscribers[topic].splice(index, 1); }; var notify = function notify() { if (subscribers[this.topic] ===
undefined) return; for (var i in subscribers[this.topic]) { subscribers[this.topic][i](this.value); } }; var init = function init() { var elem, size; elem = document.querySelectorAll('.ui-dropdown'); size = elem.length; for (var i = 0; i < size; i++) new DropDown(elem[i]); }; return { init : init, setValue : setValue, subscribe : subscribe, unsubscribe : unsubscribe, ...
...And 7 more matches
Debugger.Object - Firefox Developer Tools
type (as a new Debugger.Object instance), or null if it has no prototype. class A string naming the ECMAScript [[Class]] of the referent. callable true if the referent is a callable object (such as a function or a function proxy); false otherwise. name The name of the referent, if it is a named function. If the referent is an anonymous function, or not a function at all, this is
undefined. This accessor returns whatever name appeared after the function keyword in the source code, regardless of whether the function is the result of instantiating a function declaration (which binds the function to its name in the enclosing scope) or evaluating a function expression (which binds the function to its name only within the function's body). displayName The referent's display name...
...tion is the result of instantiating a function declaration (which binds the function to its name in the enclosing scope) or evaluating a function expression (which binds the function to its name only within the function's body). displayName The referent's display name, if the referent is a function with a display name. If the referent is not a function, or if it has no display name, this is
undefined. If a function has a given name, its display name is the same as its given name. In this case, the displayName and name properties are equal. If a function has no name, SpiderMonkey attempts to infer an appropriate name for it given its context. For example: function f() {} // display name: f (the given name) var g = function () {}; // display name: g o.p = function () {}; // d...
...n that is assigned to a. For example: function h() { var i = function() {}; // display name: h/i f(function () {}); // display name: h/< } var s = f(function () {}); // display name: s< parameterNames If the referent is a debuggee function, the names of the its parameters, as an array of strings. If the referent is not a debuggee function, or not a function at all, this is
undefined. If the referent is a host function for which parameter names are not available, return an array with one element per parameter, each of which is
undefined. If the referent is a function proxy, return an empty array. If the referent uses destructuring parameters, then the array's elements reflect the structure of the parameters. For example, if the referent is a function declared in this wa...
...And 6 more matches
Box-shadow generator - CSS: Cascading Style Sheets
d(input); node.appendChild(unit); input.addEventListener('click', function(e) { this.select(); }); input.addEventListener('change', function(e) { setValue(topic, e.target.value | 0); }); subscribe(topic, function(value) { node.children[0].value = value; }); } var increment = function increment(topic) { var slider = sliders[topic]; if (slider === null || slider ===
undefined) return; if (slider.value + slider.step <= slider.max) { slider.value += slider.step; setValue(slider.topic, slider.value) notify.call(slider); } }; var decrement = function decrement(topic) { var slider = sliders[topic]; if (slider === null || slider ===
undefined) return; if (slider.value - slider.step >= slider.min) { slider.value -= slider.step; setValue(to...
... var setMouseTracking = function setMouseTracking(elem, callback) { elem.addEventListener("mousedown", function(e) { callback(e); document.addEventListener("mousemove", callback); }); document.addEventListener("mouseup", function(e) { document.removeEventListener("mousemove", callback); }); } var subscribe = function subscribe(topic, callback) { if (subscribers[topic] ===
undefined) subscribers[topic] = []; subscribers[topic].push(callback); } var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexOf(callback); subscribers[topic].splice(index, 1); } var notify = function notify() { if (subscribers[this.topic] ===
undefined) return; for (var i in subscribers[this.topic]) { subscribers[this.topic][i](this.value); } } v...
...d(this)); buttons[topic] = this; } var getNode = function getNode(topic) { return buttons[topic].node; } var setValue = function setValue(topic, value) { try { buttons[topic].checkbox.checked = value; notify.call(buttons[topic]); } catch(error) { console.log(error, topic, value); } } var subscribe = function subscribe(topic, callback) { if (subscribers[topic] ===
undefined) subscribers[topic] = []; subscribers[topic].push(callback); } var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexOf(callback); subscribers[topic].splice(index, 1); } var notify = function notify() { if (subscribers[this.topic] ===
undefined) return; for (var i = 0; i < subscribers[this.topic].length; i++) subscribers[this.topic][i](this.ch...
...And 6 more matches
Color picker tool - CSS: Cascading Style Sheets
ickerMode(topic, mode) { if (pickers[topic]) pickers[topic].setPickerMode(mode); }; var setColor = function setColor(topic, color) { if (pickers[topic]) pickers[topic].setColor(color); }; var getColor = function getColor(topic) { if (pickers[topic]) return new Color(pickers[topic].color); }; var subscribe = function subscribe(topic, callback) { if (subscribers[topic] ===
undefined) subscribers[topic] = []; subscribers[topic].push(callback); }; var unsubscribe = function unsubscribe(callback) { subscribers.indexOf(callback); subscribers.splice(index, 1); }; var notify = function notify(topic, value) { if (subscribers[topic] ===
undefined || subscribers[topic].length === 0) return; var color = new Color(value); for (var i in subscribers[topic]) s...
...r_left); node.appendChild(input); node.appendChild(slider_right); this.input = input; sliders[topic] = this; setValue(topic, value); }; InputSlider.prototype.setInputValue = function setInputValue() { this.input.value = this.value.toFixed(this.precision) + this.unit; }; var setValue = function setValue(topic, value, send_notify) { var slider = sliders[topic]; if (slider ===
undefined) return; value = parseFloat(value.toFixed(slider.precision)); if (value > slider.max) value = slider.max; if (value < slider.min) value = slider.min; slider.value = value; slider.node.setAttribute('data-value', value); slider.setInputValue(); if (send_notify === false) return; notify.call(slider); }; var setMax = function setMax(topic, value) { var slider = slider...
...seFloat(value.toFixed(slider.precision)); if (value > slider.max) value = slider.max; if (value < slider.min) value = slider.min; slider.value = value; slider.node.setAttribute('data-value', value); slider.setInputValue(); if (send_notify === false) return; notify.call(slider); }; var setMax = function setMax(topic, value) { var slider = sliders[topic]; if (slider ===
undefined) return; slider.max = value; setValue(topic, slider.value); }; var setMin = function setMin(topic, value) { var slider = sliders[topic]; if (slider ===
undefined) return; slider.min = value; setValue(topic, slider.value); }; var setUnit = function setUnit(topic, unit) { var slider = sliders[topic]; if (slider ===
undefined) return; slider.unit = unit; setValu...
...And 6 more matches
Equality comparisons and sameness - JavaScript
numbers, they're considered equal if they're both not NaN and are the same value, or if one is +0 and one is -0. var num = 0; var obj = new String('0'); var str = '0'; console.log(num === num); // true console.log(obj === obj); // true console.log(str === str); // true console.log(num === obj); // false console.log(num === str); // false console.log(obj === str); // false console.log(null ===
undefined); // false console.log(obj === null); // false console.log(obj ===
undefined); // false Strict equality is almost always the correct comparison operation to use. For all values except numbers, it uses the obvious semantics: a value is only equal to itself. For numbers it uses slightly different semantics to gloss over two different edge cases. The first is that floating point zero is either pos...
...ions (one or both sides may undergo conversions), the final equality comparison is performed exactly as === performs it. Loose equality is symmetric: A == B always has identical semantics to B == A for any values of A and B (except for the order of applied conversions). ...
...s performed exactly as === performs it. Loose equality is symmetric: A == B always has identical semantics to B == A for any values of A and B (except for the order of applied conversions). ...
...And 6 more matches
Array.prototype.find() - JavaScript
h value in the array, taking 3 arguments: element The current element in the array. index Optional The index (position) of the current element in the array. array Optional The array that find was called on. thisArg Optional Object to use as this inside callback. Return value The value of the first element in the array that satisfies the provided testing function. Otherwise,
undefined is returned. Description The find method executes the callback function once for each index of the array until the callback returns a truthy value. If so, find immediately returns the value of that element. Otherwise, find returns
undefined. callback is invoked for every index of the array, not just those with assigned values. This means it may be less efficient for sparse arrays, compared to ...
... The find method does not mutate the array on which it is called, but the function provided to callback can. If so, the elements processed by find are set before the first invocation of callback. Therefore: callback will not visit any elements added to the array after the call to find begins. ...
...or not defined'); } var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")). var len = o.length >>> 0; // 3. If IsCallable(predicate) is false, throw a TypeError exception. if (typeof predicate !== 'function') { throw TypeError('predicate must be a function'); } // 4. If thisArg was supplied, let T be thisArg; else let T be
undefined. var thisArg = arguments[1]; // 5. Let k be 0. var k = 0; // 6. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). // b. Let kValue be ? Get(O, Pk). // c. Let testResult be ToBoolean(? Call(predicate, T, << kValue, k, O >>)). // d. If testResult is true, return kValue. var kValue = o[k]; if (predic...
...And 6 more matches
Shell global objects
catchTermination if true, catch termination (failure without an exception value, as for slow scripts or out-of-memory) and return 'terminated' element if present with value v, convert v to an object o and mark the source as being attached to the DOM element o. If the property is omitted or v is null, don't attribute the source to any DOM element. elementAttributeName if present and not
undefined, the name of property of element that holds this code. This is what Debugger.Source.prototype.elementAttributeName returns. sourceMapURL if present with value v, convert v to a string, and provide that as the code's source map URL. If omitted, attach no source map URL to the code (although the code may provide one itself, via a //#sourceMappingURL comment). sourceIsLazy if present and tru...
...o lineNumber starting line number for error messages and debug info columnNumber starting column number for error messages and debug info element if present with value v, convert v to an object o and mark the source as being attached to the DOM element o. If the property is omitted or v is null, don't attribute the source to any DOM element. elementAttributeName if present and not
undefined, the name of property of element that holds this code. This is what Debugger.Source.prototype.elementAttributeName returns. runOffThreadScript() Wait for off-thread compilation to complete. If an error occurred, throw the appropriate exception; otherwise, run the script and return its value. offThreadCompileModule(code) Compile code on a helper thread. To wait for the compilation to finis...
..., for subsumption purposes. If this property is omitted, supply no principal. createMappedArrayBuffer(filename, [offset, [size]]) Create an array buffer that mmaps the given file. addPromiseReactions(promise, onResolve, onReject) Calls the JS::AddPromiseReactions JSAPI function with the given arguments. getMaxArgs() Return the maximum number of supported args for a call. objectEmulating
Undefined() Return a new object obj for which typeof obj === "
undefined", obj == null and obj ==
undefined (and vice versa for !=), and ToBoolean(obj) === false. isCachingEnabled() Return whether JS caching is enabled. setCachingEnabled(b) Enable or disable JS caching. cacheEntry(code) Return a new opaque object which emulates a cache entry of a script. This object encapsulates the code and its cach...
...And 5 more matches
Debugger.Source - Firefox Developer Tools
text. The URL may be passed to the Worker web worker constructor, or the web worker importScripts function. The URL may be the name of a XPCOM JavaScript module or subscript. (Note that code passed to eval, the Function constructor, or a similar function isnot considered to be loaded from a URL; the url accessor on Debugger.Source instances for such sources should return
undefined.) If the instance refers to WebAssembly code, the URL of the script that called new WebAssembly.Module with the string "> wasm" appended. sourceMapURL If the instance refers to JavaScript source, if this source was produced by a minimizer or translated from some other language, and we know the URL of a source map document relating the source positions in this source to the corresponding s...
...fers to WebAssembly code, null. Attempts to write to this property throw a TypeError. displayURL If the script had a special //# sourceURL comment, as described in the source maps specification, then this property's value holds the string that was given. Otherwise, this is null. element The Debugger.Object instance referring to the DOM element to which this source code belongs, if any, or
undefined if it belongs to no DOM element. Source belongs to a DOM element in the following cases: Source belongs to a <script> element if it is the element's text content (that is, it is written out as the body of the <script> element in the markup text), or is the source document referenced by its src attribute. Source belongs to a DOM element if it is an event handler content attribute...
...ched to a DOM element change, the Debugger.Source instances representing superceded code still refer to the DOM element; this accessor only reflects origins, not current relationships.) elementAttributeName If this source belongs to a DOM element because it is an event handler content attribute or an event handler IDL attribute, this is the name of that attribute, a string. Otherwise, this is
undefined. introductionType If the instance refers to JavaScript source, a string indicating how this source code was introduced into the system. This accessor returns one of the following values: "eval", for code passed to eval. "Function", for code passed to the Function constructor. "Function.prototype", for Function.prototype internally generated code. "Worker", ...
...And 5 more matches
Optional chaining (?.) - JavaScript
The optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. The ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is nullish (null or
undefined), the expression short-circuits with a return value of
undefined. When used with function calls, it returns
undefined if the given function does not exist. This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required. The source for thi...
... a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax obj?.prop obj?.[expr] arr?.[index] func?.(args) Description The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be
undefined or null. For example, consider an object obj which has a nested structure. Without optional chaining, looking up a deeply-nested subproperty requires validating the references in between, such as: let nestedProp = obj.first && obj.first.second; The value of obj.first is confirmed to be non-null (and non-
undefined) before then accessing the value of obj.first.second. This prevents the error tha...
...mply accessed obj.first.second directly without testing obj.first. With the optional chaining operator (?.), however, you don't have to explicitly test and short-circuit based on the state of obj.first before trying to access obj.first.second: let nestedProp = obj.first?.second; By using the ?. ...
...And 5 more matches
Download
ut the cancellation process has not finished yet, this method waits for the cancellation to finish, then restarts the download immediately. Note: If you need to start a new download from the same source, rather than restarting a failed or canceled one, you should create a separate Download object with the same source as the current one. Promise start(); Parameters None. Promise resolves to
undefined when the download has finished successfully and you can access the target file. Promise can be rejected with DownloadError if the download failed. launch() Opens or executes the target file after download has completed. If the launcherPath property is null, the file will be opened with the default application for the MIME type specified in the contentType property. If the content type is not...
...erty is null, the file will be opened with the default application for the MIME type specified in the contentType property. If the content type is not available, an attempt will be made to obtain it from the extension of the target file. If the launcherPath property is set, the file will be opened with the specified custom application. Promise launch(); Parameters None. Promise resolves to
undefined when the instruction to launch the file has been successfully given to the operating system. Note that the OS might still take a while until the file is actually launched. showContainingDirectory() Shows the folder containing the target file, or where the target file will be saved. This may be called at any time, even if the download failed or is currently in progress. Promise showContainingDi...
...cessfully given to the operating system. Note that the OS might still take a while until the file is actually launched. showContainingDirectory() Shows the folder containing the target file, or where the target file will be saved. This may be called at any time, even if the download failed or is currently in progress. Promise showContainingDirectory(); Parameters None. Promise resolves to
undefined when the instruction to open the containing folder has been successfully given to the operating system. Note that the OS might still take a while until the folder is actually opened. cancel() Cancels the download. The cancellation request is asynchronous. Until the cancellation process finishes, temporary files or part files may still exist even if they are expected to be deleted. In case the...
...And 4 more matches
Promise
Promise object to which you already have a reference. Internally, a promise can be in one of three states: Pending, when the final value is not available yet. This is the only state that may transition to one of the other two states. Fulfilled, when and if the final value becomes available. A fulfillment value becomes permanently associated with the promise. This may be any value, including
undefined. Rejected, if an error prevented the final value from being determined. A rejection reason becomes permanently associated with the promise. This may be any value, including
undefined, though it is generally an Error object, like in exception handling. Note: You should always handle, forward, or report errors (rejection reasons). If you see the message "A promise chain failed to handle a reje...
... this method does nothing. Note: Calling this method with a pending promise as the aValue argument, and then calling it again with another value before the promise is fulfilled or rejected, will have no effect the second time, as the associated promise is already resolved to the pending promise. void resolve( aValue ); Parameters aValue Optional If this value is not a promise, including
undefined, it becomes the fulfillment value of the associated promise. If this value is a promise, then the associated promise will be resolved to the passed promise, and follow the state as the provided promise (including any future transitions). reject() Rejects the associated promise with the specified reason. If the promise has already been resolved, either to a value, a rejection, or another promis...
... the state as the provided promise (including any future transitions). reject() Rejects the associated promise with the specified reason. If the promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. void reject( aReason ); Parameters aReason Optional The rejection reason for the associated promise. Although the reason can be
undefined, it is generally an Error object, like in exception handling. Note: This argument should not be a promise. Specifying a rejected promise would make the rejection reason equal to the rejected promise itself, and not its rejection reason. Methods then() Calls one of the provided functions as soon as this promise is either fulfilled or rejected. A new promise is returned, whose state evolve...
...And 4 more matches
JS::Value
JS::Value is the type of JavaScript values in the JSAPI. A C++ variable of type JS::Value represents a value in JavaScript: a string, number, object (including arrays and functions), boolean, symbol, null, or
undefined. JS::Value is a class whose internal structure is an implementation detail. Embeddings should not rely on observed representation details or upon the size of JS::Value. ...
...:Value is a class whose internal structure is an implementation detail. Embeddings should not rely on observed representation details or upon the size of JS::Value. ...
...hose internal structure is an implementation detail. Embeddings should not rely on observed representation details or upon the size of JS::Value. ...
...And 4 more matches
JSClass.flags
object of this class points to an XPCOM object (see nsISupports). This is only meaningful if SpiderMonkey is built with XPConnect and the JSCLASS_HAS_PRIVATE flag is also set. MXR ID Search for JSCLASS_PRIVATE_IS_NSISUPPORTS JSCLASS_IS_DOMJSCLASS Added in SpiderMonkey 17 Objects are DOM. MXR ID Search for JSCLASS_IS_DOMJSCLASS JSCLASS_EMULATES_
UNDEFINED Added in SpiderMonkey 24 Causes objects which have this class to emulate
undefined in certain circumstances. An object obj that emulates
undefined behaves like any other object, except in the following ways: typeof obj === "
undefined" obj converts to false when obj is converted to a boolean when used in boolean contexts (if conditions, loop continuation/termination condit...
... Strict equality (=== and !==) comparisons are also unaffected by this flag. ...
... Strict equality (=== and !==) comparisons are also unaffected by this flag. ...
...And 4 more matches
Debugger - Firefox Developer Tools
debuggee code, the engine pauses the debuggee and calls the corresponding debugging handler on each Debugger instance that is observing the debuggee. The handler functions receive the Debugger instance as their this value. Most handler functions can return a resumption value indicating how the debuggee's execution should proceed. On a new Debugger instance, each of these properties is initially
undefined. Any value assigned to a debugging handler must be either a function or
undefined; otherwise a TypeError is thrown. Handler functions run in the same thread in which the event occurred. They run in the compartment to which they belong, not in a debuggee compartment. onNewScript(script,global) New code, represented by the Debugger.Script instancescript, has been loaded in the scope of the d...
...ger.Object instance promise, has been allocated in the scope of the debuggees. The Promise's allocation stack can be obtained using the promiseAllocationStack accessor property of the Debugger.Object instance promise. This handler method should return a resumption value specifying how the debuggee's execution should proceed. However, note that a { return:value } resumption value is treated like
undefined ("continue normally");value is ignored. onPromiseSettled(promise) A Promise object, referenced by the Debugger.Object instance promise that was allocated within a debuggee scope, has settled (either fulfilled or rejected). The Promise's state, fulfillment or rejection value, and the allocation and resolution stacks can be obtained using the Promise-related accessor properties of the Debugge...
...filled or rejected). The Promise's state, fulfillment or rejection value, and the allocation and resolution stacks can be obtained using the Promise-related accessor properties of the Debugger.Object instance promise. This handler method should return a resumption value specifying how the debuggee's execution should proceed. However, note that a { return:value } resumption value is treated like
undefined ("continue normally");value is ignored. onDebuggerStatement(frame) Debuggee code has executed adebugger statement inframe. This method should return a resumption value specifying how the debuggee's execution should proceed. onEnterFrame(frame) The stack frameframe is about to begin executing code. (Naturally,frame is currently the youngest visible frame.) This method should return a resum...
...And 4 more matches
Meta programming - JavaScript
ustom behaviors. For example, getting a property on an object: let handler = { get: function(target, name) { return name in target? target[name] : 42 } } let p = new Proxy({}, handler) p.a = 1 console.log(p.a, p.b) // 1, 42 The Proxy object defines a target (an empty object here) and a handler object, in which a get trap is implemented. Here, an object that is proxied will not return
undefined when getting
undefined properties, but will instead return the number 42. Additional examples are available on the Proxy reference page. Terminology The following terms are used when talking about the functionality of proxies. handler Placeholder object which contains traps. traps The methods that provide property access. (This is analogous to the concept of traps in operating systems.) ...
...t.isExtensible(target). handler.preventExtensions() Object.preventExtensions() Reflect.preventExtensions() Object.preventExtensions(proxy) only returns true if Object.isExtensible(proxy) is false. handler.getOwnPropertyDescriptor() Object.getOwnPropertyDescriptor() Reflect.getOwnPropertyDescriptor() getOwnPropertyDescriptor must return an object or
undefined. A property cannot be reported as non-existent if it exists as a non-configurable own property of target. A property cannot be reported as non-existent if it exists as an own property of target and target is not extensible. A property cannot be reported as existent if it does not exists as an own property of target and target is not extensible. A property cannot be reported as...
... handler.get() Property access proxy[foo] proxy.bar Inherited property access Object.create(proxy)[foo] Reflect.get() The value reported for a property must be the same as the value of the corresponding target property if target's property is a non-writable, non-configurable data property. The value reported for a property must be
undefined if the corresponding target property is non-configurable accessor property that has
undefined as its [[Get]] attribute. handler.set() Property assignment proxy[foo] = bar proxy.foo = bar Inherited property assignment Object.create(proxy)[foo] = bar {jsxref("Reflect.set()")}} Cannot change the value of a property to be...
...And 4 more matches
var - JavaScript
y. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax var varname1 [= value1] [, varname2 [= value2] ... [, varnameN [= valueN]]]; varnameN Variable name. It can be any legal identifier. valueN Optional Initial value of the variable. It can be any legal expression. Default value is
undefined. Description var declarations, wherever they occur, are processed before any code is executed. This is called hoisting, and is discussed further below. The scope of a variable declared with var is its current execution context and closures thereof, which is either the enclosing function and functions declared within it, or, for variables declared outside any function, global. Duplicate variab...
... function bar() { var y = 2; console.log(x); // 1 (function `bar` closes over `x`) console.log(y); // 2 (`y` is in scope) } bar(); console.log(x); // 1 (`x` is in scope) console.log(y); // ReferenceError in strict mode, `y` is scoped to `bar` } foo(); Variables declared using var are created before any code is executed in a process known as hoisting. Their initial value is
undefined. 'use strict'; console.log(x); //
undefined (note: not ReferenceError) console.log('still going...'); // still going... var x = 1; console.log(x); // 1 console.log('still going...'); // still going... In the global context, a variable declared using var is added as a non-configurable property of the global object. This means its property descriptor cannot be change...
...he top of global code and the top of function code) so it's clear which variables are function scoped (local) and which are resolved on the scope chain. It's important to point out that the hoisting will affect the variable declaration, but not its value's initialization. ...
...And 4 more matches
DevTools API - Firefox Developer Tools
ions {Object} - An options object passed to the selected host. See HostType for details. Return value: A Promise that is fulfilled with the Toolbox instance once it has been initialized and the selected tool is loaded. getToolbox(target) Fetch the Toolbox object for the given target. Parameters: target {Target} - The target the toolbox is debugging. Return value: Toolbox object or
undefined if there's no toolbox for the given target.. closeToolbox(target) Closes the toolbox for given target. Parameters: target {Target} - The target of the toolbox that should be closed. Return value: A Promise that is fulfilled once the toolbox has been destroyed. getDefaultTools() Returns an Array of ToolDefinition objects for the built-in tools. getAdditionalTools() Returns ...
...OM Host type for a custom frame host. Methods getCurrentPanel() Get the currently active ToolPanel. Return value: The ToolPanel object that was returned from ToolPanel.build(). getPanel(toolId) Get the ToolPanel for given tool. Parameters: toolId {String} - The tool identifier. Return value: The ToolPanel object if the tool with the given toolId is active, otherwise
undefined. getPanelWhenReady(toolId) Similar to getPanel() but waits for the tool to load first. If the tool is not already loaded or currently loading the returned Promise won't be fulfilled until something triggers the tool to load. Parameters: toolId {String} - The tool identifier. Return value: A Promise that is fulfilled with the ToolPanel object once the tool has finished loading. ge...
...x {Toolbox} - The Toolbox the tool is being built for. Return value: A ToolPanel for the tool. onKey(panel, toolbox) Optional. A method that is called when the keyboard shortcut for the tool is activated while the tool is the active tool. Parameters: panel {ToolPanel} - The ToolPanel for the tool. toolbox {Toolbox} - The toolbox for the shortcut was triggered for. Return value:
Undefined. Properties The ToolDefinition object can contain following properties. Most of them are optional and can be used to customize the presense of the tool in the Browser and the Toolbox. id String, required. An unique identifier for the tool. It must be a valid id for an HTML Element. url String, required. An URL of the panel document. label String, optional. The tool's name. ...
...And 3 more matches
MediaDevices.getUserMedia() - Web APIs
See Security for more information on this and other security issues related to using getUserMedia(). Syntax var promise = navigator.mediaDevices.getUserMedia(constraints); Parameters constraints A MediaStreamConstraints object specifying the types of media to request, along with any requirements for each type. The constraints parameter is a MediaSt...
...rror User media support is disabled on the Document on which getUserMedia() was called. The mechanism by which user media support is enabled and disabled is left up to the individual user agent. TypeError The list of constraints specified is empty, or has all constraints set to false. ...
...A secure context is, in short, a page loaded using HTTPS or the file:/// URL scheme, or a page loaded from localhost. In addition, user permission is always required to access the user's audio and video inputs. ...
...And 3 more matches
Using the Resource Timing API - Web APIs
also calculates the time from the start of the fetch and request start phases (fetchStart and requestStart, respectively), until the response has ended (responseEnd). This timing data provides a detailed profile of the resource loading phases and this data can be used to help identify performance bottlenecks. ...
...oading phases and this data can be used to help identify performance bottlenecks. function calculate_load_times() { // Check performance support if (performance ===
undefined) { console.log("= Calculate Load Times: performance NOT supported"); return; } // Get a list of "resource" performance entries var resources = performance.getEntriesByType("resource"); if (resources ===
undefined || resources.length <= 0) { console.log("= Calculate Load Times: there are NO `resource` performance records"); return; } console.log("= Calculate Load Times"); for (var i=0; i < resources.length; i++) { console.log("== Resource[" + i + "] - " + resources[i].name); // Redirect time var t = resources[i].redirectEnd - resources[i].redirectStart; console.log("... Redir...
...ontent-codings. decodedBodySize returns the size (in octets) received from the fetch (HTTP or cache) of the message body, after removing any applied content-codings. The following example demonstrates using these three properties. function display_size_data(){ // Check for support of the PerformanceResourceTiming.*size properties and print their values // if supported. ...
...And 3 more matches
Using the User Timing API - Web APIs
named performance entry that is created by the application at some location in an application. The mark is a timestamp in the browser's performance timeline. Creating a performance mark The performance.mark() method is used to create a performance mark. The method takes one argument, the name of the mark, as shown in the following example. ...
...d mark = " + marks[i], 0); } Retrieving performance marks The Performance interface has three methods to retrieve marks. The following examples shows how to use each of these methods (performance.getEntries(), performance.getEntriesByType(entryType), and performance.getEntriesByName(name, entryType) ) to retrieve one or more marks. function display_marks(ev) { if (performance.getEntries ===
undefined) { log("Display Marks: performance.getEntries Not supported", 0); return; } log("Display marks", 0); // Display each mark using getEntries() var entries = performance.getEntries(); var j=0; for (var i=0; i < entries.length; i++) { if (entries[i].entryType == "mark") { if (j == 0) { log("= getEntries()", 0); j++ } log("... [" + i + "] = " + entries[i].name, 0);...
...or more marks from the browser's performance timeline. If a specific mark name is given to this method, only the mark(s) with that name will be removed. However, if no argument is given, then all performance entries of type "mark" will be removed from the performance timeline. The following example demostrates both uses of this method. function clear_marks(obj) { if (performance.clearMarks ===
undefined) { log("Clear Marks: performance.clearMarks Not supported", 0); return; } log("Clear marks", 0); if (typeof obj == "string") { log("... cleared '" + obj + "' mark(s)", 0); performance.clearMarks(obj); } else { // No argument specified so clear all marks log("... cleared All marks", 0); performance.clearMarks(); } } Performance measures A measure performan...
...And 3 more matches
JavaScript data types and data structures - JavaScript
Special primitive type having additional usage for its value: if object is not inherited, then null is shown; Obje...
...Special primitive type having additional usage for its value: if object is not inherited, then null is shown; Object : typeof instance === "object"...
...ine immutable values (that is, values which can't be changed). For example (and unlike in C), Strings are immutable. We refer to values of these types as "primitive values". Boolean type Boolean represents a logical entity and can have two values: true and false. See Boolean and Boolean for more details. Null type The Null type has exactly one value: null. See null and Null for more details.
Undefined type A variable that has not been assigned a value has the value
undefined. See
undefined and
Undefined for more details. Number type ECMAScript has two built-in numeric types: Number and BigInt (see below). The Number type is a double-precision 64-bit binary format IEEE 754 value (numbers between -(253 - 1) and 253 - 1). In addition to representing floating-point numbers, the number type has...
...And 3 more matches
Inheritance and the prototype chain - JavaScript
y on o? Yes, and its value is 1. console.log(o.b); // 2 // Is there a 'b' own property on o? Yes, and its value is 2. // The prototype also has a 'b' property, but it's not visited. // This is called Property Shadowing console.log(o.c); // 4 // Is there a 'c' own property on o? No, check its prototype. // Is there a 'c' own property on o.[[Prototype]]? Yes, its value is 4. console.log(o.d); //
undefined // Is there a 'd' own property on o? No, check its prototype. // Is there a 'd' own property on o.[[Prototype]]? No, check its prototype. // o.[[Prototype]].[[Prototype]] is Object.prototype and there is no 'd' property by default, check its prototype. // o.[[Prototype]].[[Prototype]].[[Prototype]] is null, stop searching, // no property found, return
undefined. Code Link Setting a property to...
...oto__ of the __proto__ of doSomeInstancing is looked through. However, there is a problem: the __proto__ of the __proto__ of the __proto__ of doSomeInstancing does not exist. Then, and only then, after the entire prototype chain of __proto__'s is looked through, and there are no more __proto__s does the browser assert that the property does not exist and conclude that the value at the property is
undefined. Let's try entering some more code into the console: function doSomething(){} doSomething.prototype.foo = "bar"; var doSomeInstancing = new doSomething(); doSomeInstancing.prop = "some value"; console.log("doSomeInstancing.prop: " + doSomeInstancing.prop); console.log("doSomeInstancing.foo: " + doSomeInstancing.foo); console.log("doSomething.prop: " + doSomething.prop); con...
...e.log("doSomething.prop: " + doSomething.prop); console.log("doSomething.foo: " + doSomething.foo); console.log("doSomething.prototype.prop: " + doSomething.prototype.prop); console.log("doSomething.prototype.foo: " + doSomething.prototype.foo); This results in the following: doSomeInstancing.prop: some value doSomeInstancing.foo: bar doSomething.prop:
undefined doSomething.foo:
undefined doSomething.prototype.prop:
undefined doSomething.prototype.foo: bar Different ways to create objects and the resulting prototype chain Objects created with syntax constructs var o = {a: 1}; // The newly created object o has Object.prototype as its [[Prototype]] // o has no own property named 'hasOwnProperty' // hasOwnProperty is an own property of Objec...
...And 3 more matches
TypeError: "x" is (not) "y" - JavaScript
The JavaScript exception "x is (not) y" occurs when there was an unexpected type. Oftentimes, unexpected
undefined or null values. Message TypeError: Unable to get property {x} of
undefined or null reference (Edge) TypeError: "x" is (not) "y" (Firefox) Examples: TypeError: "x" is
undefined TypeError: "x" is null TypeError: "
undefined" is not an object TypeError: "x" is not an object or null TypeError: "x" is not a symbol Error type TypeError. What went wrong? ...
... Message TypeError: Unable to get property {x} of
undefined or null reference (Edge) TypeError: "x" is (not) "y" (Firefox) Examples: TypeError: "x" is
undefined TypeError: "x" is null TypeError: "
undefined" is not an object TypeError: "x" is not an object or null TypeError: "x" is not a symbol Error type TypeError. What went wrong? ...
...or: "x" is null TypeError: "
undefined" is not an object TypeError: "x" is not an object or null TypeError: "x" is not a symbol Error type TypeError. What went wrong? ...
...And 3 more matches
Arrow function expressions - JavaScript
ssigning `length` value to the made up property. Instead, the literal name // itself of the variable `length` is used as the property we want to retrieve from the object. elements.map(({ length }) => length); // [8, 6, 7, 9] No separate this Before arrow functions, every new function defined its own this value based on how the function was called: A new object in the case of a constructor.
undefined in strict mode function calls. The base object if the function was called as an "object method". etc. This proved to be less than ideal with an object-oriented style of programming. function Person() { // The Person() constructor defines `this` as an instance of itself. this.age = 0; setInterval(function growUp() { // In non-strict mode, the growUp() function defines `this` //...
...; return f(10); } foo(1); // 11 Arrow functions used as methods As stated previously, arrow function expressions are best suited for non-method functions. ...
... this), c: function() { console.log(this.i, this); } } obj.b(); // prints
undefined, Window {...} (or the global object) obj.c(); // prints 10, Object {...} Arrow functions do not have their own this. Another example involving Object.defineProperty(): 'use strict'; var obj = { a: 10 }; Object.defineProperty(obj, 'b', { get: () => { console.log(this.a, typeof this.a, this); //
undefined '
undefined' Window {...} (or the global object) return this.a + 10; // represents global object 'Window', therefore 'this.a' returns '
undefined' } }); Use of the new operator Arrow functions cannot be used as constructors and will throw an error when used with new. var Foo = () => {}; var foo = new Foo(); // TypeError: Foo is not a constructor Use of prototype property Arrow functions...
...And 3 more matches
Array.prototype.map() - JavaScript
alled upon. thisArgOptional Value to use as this when executing callback. Return value A new array with each element being the result of the callback function. Description map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values (including
undefined). It is not called for missing elements of the array; that is: indexes that have never been set; which have been deleted; or which have never been assigned a value. When not to use map() Since map builds a new array, using it when you aren't using the returned array is an anti-pattern; use forEach or for-of instead. You shouldn't be using map if: you're not using the array it returns...
... for-of instead. You shouldn't be using map if: you're not using the array it returns; and/or you're not returning a value from the callback. Parameters in Detail callback is invoked with three arguments: the value of the element, the index of the element, and the array object being mapped. If a thisArg parameter is provided, it will be used as callback's this value. Otherwise, the value
undefined will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. map does not mutate the array on which it is called (although callback, if invoked, may do so). The range of elements processed by map is set before the first invocation of callback. Elements which are appended to the array afte...
...thod of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11 if (typeof callback !== 'function') { throw new TypeError(callback + ' is not a function'); } // 5. If thisArg was supplied, let T be thisArg; else let T be
undefined. if (arguments.length > 1) { T = arguments[1]; } // 6. Let A be a new array created as if by the expression new Array(len) // where Array is the standard built-in constructor with that name and // len is the value of len. A = new Array(len); // 7. Let k be 0 k = 0; // 8. Repeat, while k < len while (k < len) { var kValue, mappedValue; ...
...And 3 more matches
Object.defineProperty() - JavaScript
rty may be deleted from the corresponding object. Defaults to false. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults to false. A data descriptor also has the following optional keys: value The value associated with the property. Can be any valid JavaScript value (number, object, function, etc). Defaults to
undefined. writable true if and only if the value associated with the property may be changed with an assignment operator. Defaults to false. An accessor descriptor also has the following optional keys: get A function which serves as a getter for the property, or
undefined if there is no getter. When the property is accessed, this function is called without arguments and with this set to the objec...
...s: get A function which serves as a getter for the property, or
undefined if there is no getter. When the property is accessed, this function is called without arguments and with this set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property. Defaults to
undefined. set A function which serves as a setter for the property, or
undefined if there is no setter. When the property is assigned, this function is called with one argument (the value being assigned to the property) and with this set to the object through which the property is assigned. Defaults to
undefined. If a descriptor has neither of value, writable, get and set keys, it is treated as a dat...
...se }); Object.defineProperty(o, 'c', { value: 3 }); // enumerable defaults to false o.d = 4; // enumerable defaults to true // when creating a property by setting it Object.defineProperty(o, Symbol.for('e'), { value: 5, enumerable: true }); Object.defineProperty(o, Symbol.for('f'), { value: 6, enumerable: false }); for (var i in o) { console.log(i); } // logs 'a' and 'd' (in
undefined order) Object.keys(o); // ['a', 'd'] o.propertyIsEnumerable('a'); // true o.propertyIsEnumerable('b'); // false o.propertyIsEnumerable('c'); // false o.propertyIsEnumerable('d'); // true o.propertyIsEnumerable(Symbol.for('e')); // true o.propertyIsEnumerable(Symbol.for('f')); // false var p = { ...o } p.a // 1 p.b //
undefined p.c //
undefined p.d // 4 p[Symbol.for('e')] // 5 p[Symbol.for('f')...
...And 3 more matches
this - JavaScript
Since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser. function f1() { return this; } // In a browser: f1() === window; // true // In Node: f1() === globalThis; // true In strict mode, however, if the value of this is not set when entering an execution context, it remains as
undefined, as shown in the following example: function f2() { 'use strict'; // see strict mode return this; } f2() ===
undefined; // true In the second example, this should be
undefined, because f2 was called directly and not as a method or property of an object (e.g. window.f2()). This feature wasn't implemented in some browsers when they first started to support strict mode. As a result, they inc...
... arguments in the function call add.call(o, 5, 7); // 16 // The first parameter is the object to use as // 'this', the second is an array whose // members are used as the arguments in the function call add.apply(o, [10, 20]); // 34 Note that in non-strict mode, with call and apply, if the value passed as this is not an object, an attempt will be made to convert it to an object. Values null and
undefined become the global object. Primitives like 7 or 'foo' will be converted to an Object using the related constructor, so the primitive number 7 is converted to an object as if by new Number(7) and the string 'foo' to an object as if by new String('foo'), e.g. function bar() { console.log(Object.prototype.toString.call(this)); } bar.call(7); // [object Number] bar.call('foo'); // [object Stri...
...lobal object. Primitives like 7 or 'foo' will be converted to an Object using the related constructor, so the primitive number 7 is converted to an object as if by new Number(7) and the string 'foo' to an object as if by new String('foo'), e.g. function bar() { console.log(Object.prototype.toString.call(this)); } bar.call(7); // [object Number] bar.call('foo'); // [object String] bar.call(
undefined); // [object global] The bind method ECMAScript 5 introduced Function.prototype.bind(). Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used. function f() { return this.a; } var g = f.bind({a:...
...And 3 more matches
let - JavaScript
ole.log(x); // 2 } console.log(x); // 2 } function letTest() { let x = 1; { let x = 2; // different variable console.log(x); // 2 } console.log(x); // 1 } At the top level of programs and functions, let, unlike var, does not create a property on the global object. ...
... Redeclarations Redeclaring the same variabl...
... break; } However, it's important to point out that a block nested inside a case clause will create a new block scoped lexical environment, which will not produce the redeclaration errors shown above. ...
...And 3 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
cal network and adjusts incoming/outgoing network traffic to send data to the right place. 280 NNTP Glossary, Infrastructure NNTP (Network News Transfer Protocol) is a protocol used to transfer Usenet messages from client to server or between servers. 281 NaN CodingScripting, Computing, Glossary, NaN NaN (Not a Number) is a numeric data type that means an
undefined value or value that cannot be represented, especially results of floating-point calculations. 282 Namespace CodingScripting, Glossary, Operating System Namespace is a context for identifiers, a logical grouping of names used in a program. Within the same context and same scope, an identifier must uniquely identify an entity. 283 Native CodingScripting, Glossar...
...le or best practice, which need not be followed as a rule. 292 Null CodingScripting, Glossary In computer science, a null value represents a reference that points, generally intentionally, to a nonexistent or invalid object or address. The meaning of a null reference varies among language implementations. 293 Nullish value Glossary, JavaScript, Null, Primitive,
undefined In JavaScript, a nullish value is the value which is either null or
undefined. Nullish values are always falsy. 294 Number CodingScripting, Glossary, JavaScript In JavaScript, Number is a numeric data type in the double-precision 64-bit floating point format (IEEE 754). In other programming languages different numeric types exist; for example, Integers, Floats, Doubles,...
...ngine used to power the Opera browser until version 15. Since then, the Opera browser is based on Chromium, which uses the Blink layout engine. 331 Primitive CodingScripting, Glossary, JavaScript In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods. There are 6 primitive data types: string, number, bigint, boolean,
undefined, and symbol. There also is null, which is seemingly primitive, but indeed is a special case for every Object: and any structured type is derived from null by the Prototype Chain. 332 Privileged Glossary, Security Users are said to be privileged when they are granted additional rights to a system, or given ultimate access to content in a higher priority level when compared to ...
...And 2 more matches
JSAPI Cookbook
/ NOTE: internal representation, not numeric value bool isNull = v.isNull(); bool isBoolean = v.isBoolean(); bool isObject = v.isObject(); // NOTE: not broken like typeof === "object" is :-) To set a value use a correspondingly named member mutator function, or assign the result of the correspondingly named standalone function: // JavaScript var v; v = 0; v = 0.5; v = someString; v = null; v =
undefined; v = false; /* JSAPI */ JS::RootedValue v(cx); JS::RootedString someString(cx, ...); v.setInt32(0); // or: v = JS::Int32Value(0); v.setDouble(0.5); // or: v = JS::DoubleValue(0.5); v.setString(someString); // or: v = JS::StringValue(someString); v.setNull(); // or: v = JS::NullValue(); v.set
Undefined(); // or: v = JS::
UndefinedValue(); v.setBoolean(false); ...
...se; } return success; Object properties Getting a property // JavaScript var x = y.myprop; The JSAPI function that does this is JS_GetProperty. It requires a JSObject * argument. Since JavaScript values are usually stored in JS::Value variables, a cast or conversion is usually needed. In cases where it is certain that y is an object (that is, not a boolean, number, string, null, or
undefined), this is fairly straightforward. Use JSVAL_TO_OBJECT to cast y to type JSObject *. /* JSAPI */ JS::RootedValue x(cx); assert(y.isObject()); JS::RootedObject yobj(cx, &y.toObject()); if (!JS_GetProperty(cx, yobj, "myprop", &x)) return false; That code will crash if y is not an object. That's often unacceptable. An alternative would be to simulate the behavior of the JavaScript . notation ...
...ty() can be used to define properties in terms of two accessor functions. // JavaScript Object.defineProperty(obj, "prop", {get: GetPropFunc, set: SetPropFunc, enumerable: true}); In the JSAPI version, GetPropFunc and SetPropFunc are C/C++ functions of type JSNative. ...
...And 2 more matches
nsIFile
derlying filesystem, possibly truncating the existing file to specified size. fileSizeOfLink PRInt64 This attribute exposes the size of the symbolic link referenced by this nsIFile. Unlike fileSize, this attribute corresponds to the size of the symbolic link referenced by this nsIFile. If this nsIFile does not reference a symbolic link, then the value of this attribute is
undefined. The value of this attribute is the number of bytes corresponding to the data represented by the symbolic link. Any meta data, such as a resource fork on the Mac, is not included in the measurement of the file size. Read only. followLinks PRBool Determines whether or not the nsIFile will automatically resolve symbolic links. By default, this value is false on all non-U...
...dTime PRInt64 This attribute exposes the time when the file referenced by this nsIFile was last modified. The value of this attribute is milliseconds since midnight (00:00:00), January 1, 1970 Greenwich Mean Time (GMT). Changing the last modified time of a nsIFile operates on the underlying filesystem. As of Gecko 1.7, changing the last modified time of a non-existent file has
undefined behavior. lastModifiedTimeOfLink PRInt64 This attribute exposes the time when the symbolic link referenced by this nsIFile was last modified. Unlike lastModifiedTime, this attribute corresponds to the last modified time of the symbolic link referenced by this nsIFile. If this nsIFile does not reference a symbolic link, then the value of this attribute is
undefined. T...
... leafName AString This attribute exposes the name of the nsIFile without any directory components. Changing the leaf name of a nsIFile does not affect the underlying filesystem. It only changes what this nsIFile references. ...
...And 2 more matches
Debugger.Frame - Firefox Developer Tools
is still on the stack; false if it has completed execution or been popped in some other way. script The script being executed in this frame (a Debugger.Script instance), or null on frames that do not represent calls to debuggee code. On frames whose callee property is not null, this is equal to callee.script. offset The offset of the bytecode instruction currently being executed in script, or
undefined if the frame's script property is null. For a wasmcall frame, this property throws a TypeError. environment The lexical environment within which evaluation is taking place (a Debugger.Environment instance), or null on frames that do not represent the evaluation of debuggee code, like calls non-debuggee functions, host functions or "debugger" frames. callee The function whose application creat...
...dler functions for SpiderMonkey to call when given events occur in the frame. Calls to frames' handler methods are cross-compartment, intra-thread calls: the call takes place in the thread to which the frame belongs, and runs in the compartment to which the handler method belongs. Debugger.Frame instances inherit the following handler method properties: onStep This property must be either
undefined or a function. If it is a function, SpiderMonkey calls it when execution in this frame makes a small amount of progress, passing no arguments and providing this Debugger.Frame instance as the thisvalue. The function should return a resumption value specifying how the debuggee's execution should proceed. What constitutes "a small amount of progress" varies depending on the implementation, but it...
...unt of progress" varies depending on the implementation, but it is fine-grained enough to implement useful "step" and "next" behavior. If multiple Debugger instances each have Debugger.Frame instances for a given stack frame with onStep handlers set, their handlers are run in an unspecified order. If any onStep handler forces the frame to return early (by returning a resumption value other than
undefined), any remaining debuggers' onStep handlers do not run. This property is ignored on frames that are not executing debuggee code, like "call" frames for calls to host functions and "debugger" frames. onPop This property must be either
undefined or a function. If it is a function, SpiderMonkey calls it just before this frame is popped, passing a completion value indicating how this frame's e...
...And 2 more matches
Expressions and operators - JavaScript
; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false. Logical NOT (!) !expr Returns false if its single operand that can be converted to true; otherwise, returns true. Examples of expressions that can be converted to false are those that evaluate to null, 0, NaN, the empty string (""), or
undefined. The following code shows examples of the && (logical AND) operator. var a1 = true && true; // t && t returns true var a2 = true && false; // t && f returns false var a3 = false && true; // f && t returns false var a4 = false && (3 == 4); // f && f returns false var a5 = 'Cat' && 'Dog'; // t && t returns Dog var a6 = false && 'Cat'; // f && t returns false var a7 = 'Cat' && f...
...rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect. Note that for the second case, in modern code you can use the new Nullish coalescing operator (??) that works like ||, but it only returns the second expression, when the first one is "nullish", i.e. null or
undefined. It is thus the better alternative to provide defaults, when values like '' or 0 are valid values for the first expression, too. String operators In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings. For example, console.log('my ...
...here object is the name of an object, property is an existing property, and propertyKey is a string or symbol referring to an existing property. The fourth form is legal only within a with statement, to delete a property from an object, and also for properties of the global object. If the delete operator succeeds, it removes the propery from the object. Trying to access it afterwards will yield
undefined. The delete operator returns true if the operation is possible; it returns false if the operation is not possible. x = 42; // implicitly creates window.x var y = 43; var myobj = {h: 4}; // create object with property h delete x; // returns true (can delete if created implicitly) delete y; // returns false (cannot delete if declared with var) delete Math.PI; // returns false (cannot ...
...And 2 more matches
Indexed collections - JavaScript
lors.forEach(color => console.log(color)) // red // green // blue The function passed to forEach is executed once for every item in the array, with the array item passed as the argument to the function. Unassigned values are not iterated in a forEach loop. ...
...nassigned values are not iterated in a forEach loop. ...
...orEach loop. Note that the elements of an array that are omitted when the array is defined are not listed when iterating by forEach, but are listed when
undefined has been manually assigned to the element: let array = ['first', 'second', , 'fourth'] array.forEach(function(element) { console.log(element) }) // first // second // fourth if (array[2] ===
undefined) { console.log('array[2] is
undefined') // true } array = ['first', 'second',
undefined, 'fourth'] array.forEach(function(element) { console.log(element) }) // first // second //
undefined // fourth Since JavaScript elements are saved as standard object properties, it is not advisable to iterate through JavaScript arrays using for...in loops, because normal elements and all enumerable properties will be listed. Array methods ...
...And 2 more matches
TypeError: "x" has no properties - JavaScript
The JavaScript exception "null (or
undefined) has no properties" occurs when you attempt to access properties of null and
undefined. They don't have any. Message TypeError: Unable to get property {x} of
undefined or null reference (Edge) TypeError: null has no properties (Firefox) TypeError:
undefined has no properties (Firefox) Error type TypeError. What went wrong? ...
... The JavaScript exception "null (or
undefined) has no properties" occurs when you attempt to access properties of null and
undefined. They don't have any. Message TypeError: Unable to get property {x} of
undefined or null reference (Edge) TypeError: null has no properties (Firefox) TypeError:
undefined has no properties (Firefox) Error type TypeError. What went wrong? ...
...ies" occurs when you attempt to access properties of null and
undefined. They don't have any. Message TypeError: Unable to get property {x} of
undefined or null reference (Edge) TypeError: null has no properties (Firefox) TypeError:
undefined has no properties (Firefox) Error type TypeError. What went wrong? ...
...And 2 more matches
Array.from() - JavaScript
. ...
... // 2. Let items be ToObject(arrayLikeOrIterator). var items = Object(arrayLikeOrIterator); var isIterator = isCallable(items[symbolIterator]); // 3. ReturnIfAbrupt(items). if (arrayLikeOrIterator == null && !isIterator) { throw new TypeError( 'Array.from requires an array-like object or iterator - not null or
undefined' ); } // 4. If mapfn is
undefined, then let mapping be false. var mapFn = arguments.length > 1 ? arguments[1] : void
undefined; var T; if (typeof mapFn !== '
undefined') { // 5. else // 5. a If IsCallable(mapfn) is false, throw a TypeError exception. if (!isCallable(mapFn)) ...
... // 5. else // 5. a If IsCallable(mapfn) is false, throw a TypeError exception. if (!isCallable(mapFn)) { throw new TypeError( 'Array.from: when provided, the second argument must be a function' ); } // 5. b. If thisArg was supplied, let T be thisArg; else let T be
undefined. if (arguments.length > 2) { T = arguments[2]; } } // 10. Let lenValue be Get(items, "length"). // 11. Let len be ToLength(lenValue). var len = toLength(items.length); // 13. If IsConstructor(C) is true, then // 13. a. Let A be the result of calling the [[Construct]] inter...
...And 2 more matches
JSON.stringify() - JavaScript
ed in JSON") when trying to stringify a BigInt value. Description JSON.stringify() converts a value to JSON notation representing it: If the value has a toJSON() method, it's responsible to define what data will be serialized. Boolean, Number, and String objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics.
undefined, Functions, and Symbols are not valid JSON values. If any such values are encountered during conversion they are either omitted (when found in an object) or changed to null (when found in an array). JSON.stringify() can return
undefined when passing in "pure" values like JSON.stringify(function(){}) or JSON.stringify(
undefined). All Symbol-keyed properties will be completely ignored, even when u...
...-02T15:04:05.000Z"' JSON.stringify({ x: 5, y: 6 }); // '{"x":5,"y":6}' JSON.stringify([new Number(3), new String('false'), new Boolean(false)]); // '[3,"false",false]' // String-keyed array elements are not enumerable and make no sense in JSON let a = ['foo', 'bar']; a['baz'] = 'quux'; // a: [ 0: 'foo', 1: 'bar', baz: 'quux' ] JSON.stringify(a); // '["foo","bar"]' JSON.stringify({ x: [10,
undefined, function(){}, Symbol('')] }); // '{"x":[10,null,null,null]}' // Standard data structures JSON.stringify([new Set([1]), new Map([[1, 2]]), new WeakSet([{a: 1}]), new WeakMap([[{a: 1}, 2]])]); // '[{},{},{},{}]' // TypedArray JSON.stringify([new Int8Array([1]), new Int16Array([1]), new Int32Array([1])]); // '[{"0":1},{"0":1},{"0":1}]' JSON.stringify([new Uint8Array([1]), new Uint8ClampedArray([1...
...([1])]); // '[{"0":1},{"0":1},{"0":1}]' JSON.stringify([new Uint8Array([1]), new Uint8ClampedArray([1]), new Uint16Array([1]), new Uint32Array([1])]); // '[{"0":1},{"0":1},{"0":1},{"0":1}]' JSON.stringify([new Float32Array([1]), new Float64Array([1])]); // '[{"0":1},{"0":1}]' // toJSON() JSON.stringify({ x: 5, y: 6, toJSON(){ return this.x + this.y; } }); // '11' // Symbols: JSON.stringify({ x:
undefined, y: Object, z: Symbol('') }); // '{}' JSON.stringify({ [Symbol('foo')]: 'foo' }); // '{}' JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]); // '{}' JSON.stringify({ [Symbol.for('foo')]: 'foo' }, function(k, v) { if (typeof k === 'symbol') { return 'a symbol'; } }); //
undefined // Non-enumerable properties: JSON.stringify( Object.create(null, { x: { value: 'x', enumera...
...And 2 more matches
WeakMap - JavaScript
he state of garbage collection, introducing non-determinism. If you want to have a list of keys, you should use a Map. Constructor WeakMap() Creates a new WeakMap object. Instance methods WeakMap.prototype.delete(key) Removes any value associated to the key. WeakMap.prototype.has(key) will return false afterwards. WeakMap.prototype.get(key) Returns the value associated to the key, or
undefined if there is none. WeakMap.prototype.has(key) Returns a Boolean asserting whether a value has been associated to the key in the WeakMap object or not. WeakMap.prototype.set(key, value) Sets the value for the key in the WeakMap object. Returns the WeakMap object. Examples Using WeakMap const wm1 = new WeakMap(), wm2 = new WeakMap(), wm3 = new WeakMap(); const o1 = {}, o2 =...
...type.set(key, value) Sets the value for the key in the WeakMap object. Returns the WeakMap object. ...
...const wm1 = new WeakMap(), wm2 = new WeakMap(), wm3 = new WeakMap(); const o1 = {}, o2 = function() {}, o3 = window; wm1.set(o1, 37); wm1.set(o2, 'azerty'); wm2.set(o1, o2); // a value can be anything, including an object or a function wm2.set(o3,
undefined); wm2.set(wm1, wm2); // keys and values can be any objects. ...
...And 2 more matches
lang/type - Archive of obsolete content
Returns boolean : Boolean indicating if value is
undefined. isNull(value) Returns true if value is null, false otherwise. let { isNull } = require('sdk/lang/type'); isNull(null); // true isNull(false); // false Parameters value : mixed The variable to check. Returns boolean : Boolean indicating if value is null. isString(value) Returns true if value is a String, false otherwise. ...
... { isArguments } = require('sdk/lang/type'); function run () { isArguments(arguments); // true isArguments([]); // false isArguments(Array.slice(arguments)); // false } run(1, 2, 3); Parameters value : mixed The variable to check. Returns boolean : Boolean indicating if value is an arguments object. isPrimitive(value) Returns true if value is a primitive value: that is, any of null,
undefined, number, boolean, or string. Returns false if value is not a primitive value. let { isPrimitive } = require('sdk/lang/type'); isPrimitive(3); // true isPrimitive('foo'); // true isPrimitive({}); // false Parameters value : mixed The variable to check. Returns boolean : Boolean indicating if value is a primitive. isFlat(value) Returns true if value is a direct descendant of Object.prototy...
...arameters value : object The variable to check. Type : object The constructor to compare to value Returns boolean : Boolean indicating if value is an instance of Type. source(value, indent, limit) Returns the textual representation of value, containing property descriptors and types of properties contained within the object. ...
...s contained within the object. ...
Client-side storage - Learn web development
look at in the next section. At the end of the if block, we use the IDBCursor.continue() method to advance the cursor to the next record in the datastore, and run the content of the if block again. If there is another record to iterate to, this causes it to be inserted into the page, and then continue() is run again, and so on. When there are no more records to iterate over, cursor will return
undefined, and therefore the else block will run instead of the if block. This block checks whether any notes were inserted into the <ul> -- if not, it inserts a message to say no note was stored. Deleting a note As stated above, when a note's delete button is pressed, the note is deleted. This is achieved by the deleteItem() function, which looks like so: // Define the deleteItem() function function d...
...: 'pig' }, { 'name' : 'rabbit' } ]; To start with, once the database is successfully opened we run an init() function. This loops through the different video names, trying to load a record identified by each name from the videos database. If each video is found in the database (easily checked by seeing whether request.result evaluates to true -- if the record is not present, it will be
undefined), its video files (stored as blobs) and the video name are passed straight to the displayVideo() function to place them in the UI. If not, the video name is passed to the fetchVideoFromNetwork() function to ... you guessed it -- fetch the video from the network. function init() { // Loop through the video names one by one for(let i = 0; i < videos.length; i++) { // Open transaction, ge...
... function init() { // Loop through the video names one by one for(let i = 0; i < videos.length; i++) { // Open transaction, get object store, and get() each video by name let objectStore = db.transaction('videos_os').objectStore('videos_os'); let request = objectStore.get(videos[i].name); request.onsuccess = function() { // If the result exists in the database (is not
undefined) if(request.result) { // Grab the videos from IDB and display them using displayVideo() console.log('taking videos from IDB'); displayVideo(request.result.mp4, request.result.webm, request.result.name); } else { // Fetch the videos from the network fetchVideoFromNetwork(videos[i]); } }; } } The following snippet is taken from i...
...e worker is registered against. Inside the handler we first log the URL of the requested asset. We then provide a custom response to the request, using the FetchEvent.respondWith() method. Inside this block we use CacheStorage.match() to check whether a matching request (i.e. matches the URL) can be found in any cache. This promise fulfills with the matching response if a match is not found, or
undefined if it isn't. If a match is found, we simply return it as the custom response. If not, we fetch() the response from the network and return that instead. self.addEventListener('fetch', function(e) { console.log(e.request.url); e.respondWith( caches.match(e.request).then(function(response) { return response || fetch(e.request); }) ); }); And that is it for our simple service w...
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
node if (autofocus) nameEl.focus() Now go back to the Todos component, and pass the autofocus prop into the <NewTodo> component call, like so: <!-- NewTodo --> <NewTodo autofocus on:addTodo={e => addTodo(e.detail)} /> If you try your app out now, you'll see that the page is now blank, and in your DevTools web console you'll see an error along the lines of: TypeError: nameEl is
undefined. To understand what's happening here, let's talk some more about that component lifecycle we mentioned earlier. Component lifecycle, and the onMount() function When a component is instantiated, Svelte runs the initialization code (that is, the <script> section of the component). But at that moment, all the nodes that comprise the component are not attached to the DOM, in fact, they don't ev...
...velte <script> section: import { onMount } from 'svelte' And these lines at the end of it: console.log('initializing:', nameEl) onMount( () => { console.log('mounted:', nameEl) }) Now remove the if (autofocus) nameEl.focus() line to avoid throwing the error we were seeing before. The app will now work again, and you'll see the following in your console: initializing:
undefined mounted: <input id="todo-0" class="input input__lg" type="text" autocomplete="off"> As you can see, while the component is initializing nameEl is
undefined, which makes sense because the node input doesn't even exist yet. After the component has been mounted, Svelte assigned a reference to the <input> DOM node to the nameEl variable, thanks to the bind:this={nameEl} directive. To get the...
... So, what is happening here? When you update a component's state in Svelte, it doesn't update the DOM immediately. Instead, it waits until the next microtask to see if there are any other changes that need to be applied, including in other components. Doing so avoids unnecessary work and allows the browser to batch things more effectively. ...
... Svelte uses export let var = ... to declare props. But if instead of using let you export a const, class or function, it is read-only outside the component. Function expressions are valid props, however. ...
Deferred
is. Note: Calling this method with a pending promise as the aValue argument, and then calling it again with another value before the promise is resolved or rejected, will have no effect the second time, as the associated promise is already resolved to the pending promise value as its resolution. void resolve( aValue ); Parameters aValue Optional If this value is not a promise, including
undefined, it becomes the fulfillment value of the associated promise. If this value is a promise, then the associated promise will be resolved to the passed promise, and follow the state as the provided promise (including any future transitions). reject() Rejects the associated promise with the specified reason. If the promise has already been resolved, either to a value, a rejection, or another promis...
...ed reason. If the promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. Note: This function is bound to its associated promise when Promise.defer() is called, and can be called with any value of this. void reject( aReason ); Parameters aReason Optional The rejection reason for the associated promise. Although the reason can be
undefined, it is generally an Error object, like in exception handling. Note: This argument should not be a promise. Specifying a rejected promise would make the rejection reason equal to the rejected promise itself, and not its rejection reason. Backwards and forwards compatible helper This Deferred function can be used for backwards and forwards compatibility, due to a change that took place in Fi...
...ould not be a promise. Specifying a rejected promise would make the rejection reason equal to the rejected promise itself, and not its rejection reason. Backwards and forwards compatible helper This Deferred function can be used for backwards and forwards compatibility, due to a change that took place in Firefox 30. ...
...ble helper This Deferred function can be used for backwards and forwards compatibility, due to a change that took place in Firefox 30. function Deferred() { // update 062115 for typeof if (typeof(Promise) != '
undefined' && Promise.defer) { //need import of Promise.jsm for example: Cu.import('resource:/gree/modules/Promise.jsm'); return Promise.defer(); } else if (typeof(PromiseUtils) != '
undefined' && PromiseUtils.defer) { //need import of PromiseUtils.jsm for example: Cu.import('resource:/gree/modules/PromiseUtils.jsm'); return PromiseUtils.defer(); } else { /* A method to resolve the associated Promise with the value passed. * If the promise is already settled it does nothing. * * @param {anything} value : This value is used to resolve the promise * If the value is a ...
Tutorial: Embedding Rhino
nter. To make sure that it is called even if an exception is thrown, it is put into the finally block corresponding to the try block starting after Context.enter(). Expose Java APIs Using Java APIs No additional code in the embedding needed! The JavaScript feature calledLiveConnect allows JavaScript programs to interact with Java objects: $ java RunScript "java.lang.System.out.println(3)" 3.0
undefined Implementing interfaces Using Rhino, JavaScript objects can implement arbitrary Java interfaces. There's no Java code to write -- it's part of Rhino's LiveConnect implementation. For example, we can see how to implement java.lang.Runnable in a Rhino shell session: js> obj = { run: function() { print("hi"); } } [object Object] js> obj.run() hi js> r = new java.lang.Runnable(obj); [object Objec...
...rt() hi Adding Java objects The next example is RunScript2. This is the same as RunScript, but with the addition of two extra lines of code: Object wrappedOut = Context.javaToJS(System.out, scope); ScriptableObject.putProperty(scope, "out", wrappedOut); These lines add a global variable out that is a JavaScript reflection of the System.out variable: $ java RunScript2 "out.println(42)" 42.0
undefined Using JavaScript objects from Java After evaluating a script it's possible to query the scope for variables and functions, extracting values and calling JavaScript functions. This is illustrated in the RunScript3 example. This example adds the ability to print the value of variable x and the result of calling function f. Both x and f are expected to be defined by the evaluated script. For exam...
...r evaluating a script it's possible to query the scope for variables and functions, extracting values and calling JavaScript functions. This is illustrated in the RunScript3 example. This example adds the ability to print the value of variable x and the result of calling function f. Both x and f are expected to be defined by the evaluated script. For example, $ java RunScript3 "x = 7" x = 7 f is
undefined or not a function. $ java RunScript3 "function f(a) { return a; }" x is not defined. f("my args") = my arg Using JavaScript variables To print out the value of x, we add the following code: Object x = scope.get("x", scope); if (x == Scriptable.NOT_FOUND) { System.out.println("x is not defined."); } else { System.out.println("x = " + Context.toString(x)); } Calling JavaScript functio...
...following code: Object x = scope.get("x", scope); if (x == Scriptable.NOT_FOUND) { System.out.println("x is not defined."); } else { System.out.println("x = " + Context.toString(x)); } Calling JavaScript functions To get the function f, call it, and print the result, we add this code: Object fObj = scope.get("f", scope); if (!(fObj instanceof Function)) { System.out.println("f is
undefined or not a function."); } else { Object functionArgs[] = { "my arg" }; Function f = (Function)fObj; Object result = f.call(cx, scope, scope, functionArgs); String report = "f('my args') = " + Context.toString(result); System.out.println(report); } JavaScript host objects Defining Host Objects Custom host objects can implement special JavaScript features like dynamic properti...
JS_GetProperty
t to search on for the property. name or id const char * or const char16_t * or JS::HandleId Name of the property to look up. namelen size_t (in JS_GetUCProperty only) The length of name, in characters; or -1 to indicate that name is null-terminated. vp JS::MutableHandleValue Out parameter. On success, *vp receives the current value of the property, or
undefined if no such property is found. Description JS_GetProperty examines a specified JS object obj and its prototype chain for a property with the specified name. It behaves like the JavaScript expression obj[name]. JS_GetUCProperty is the Unicode version of the function. JS_GetPropertyById is the same but takes a JS::HandleId for the property name. In the simplest case, JS_GetProperty stores t...
...for the property name. In the simplest case, JS_GetProperty stores the value of the property in *vp and returns true. However, several different hooks can affect property gets. The full algorithm is described below. Details First, a property lookup is performed. If the lookup proceeds without error, exactly one of the following cases applies: If the property is not found, then *vp is set to
undefined. Then the JSClass.getProperty hook of obj's class is called with the arguments (cx, obj, id, vp). For many objects, including objects of standard classes such as Object and Array, this hook does nothing and returns true, so the property get succeeds and
undefined is left in *vp. If the property is found on a non-native object, get handler of Proxy (only if the object is a Proxy) or its JSObjectO...
...For many properties, the getter does nothing and returns true, so the property get succeeds and the property's stored value is left in *vp. ...
... called with the arguments (cx, obj, id, vp). For many properties, the getter does nothing and returns true, so the property get succeeds and the property's stored value is left in *vp. Internally, property retrieval, including all the behavior described above, is implemented by obj's JSObjectOps.getProperty callback. On success, these functions set *vp to the current value of the property, or
undefined if obj has no such property, and return true. On an error or exception, these functions return false, and the value left in *vp is
undefined. See Also MXR ID Search for JS_GetProperty MXR ID Search for JS_GetUCProperty MXR ID Search for JS_GetPropertyById Example in the JSAPI Phrasebook JS_DefineProperty JS_DefinePropertyWithTinyId JS_DeleteProperty JS_DeleteProperty2 JS_LookupPropert...
JSAPI reference
nkey 31 typedef JSExceptionState JS_SaveExceptionState JS_RestoreExceptionState JS_DropExceptionState These functions translate errors into exceptions and vice versa: JS_ReportPendingException JS_ErrorFromException JS_ThrowReportedError Obsolete since JSAPI 29 Values and types typedef jsval JS::Value JS::Value constructors: JS::NullValue Added in SpiderMonkey 24 JS::
UndefinedValue Added in SpiderMonkey 24 JS::BooleanValue Added in SpiderMonkey 24 JS::TrueValue Added in SpiderMonkey 24 JS::FalseValue Added in SpiderMonkey 24 JS::NumberValue Added in SpiderMonkey 24 JS::Int32Value Added in SpiderMonkey 24 JS::DoubleValue Added in SpiderMonkey 24 JS::Float32Value Added in SpiderMonkey 24 JS::StringValue Added in SpiderMonkey 24 JS::ObjectValue Added in SpiderMon...
...dded in SpiderMonkey 24 JS::Int32Value Added in SpiderMonkey 24 JS::DoubleValue Added in SpiderMonkey 24 JS::Float32Value Added in SpiderMonkey 24 JS::StringValue Added in SpiderMonkey 24 JS::ObjectValue Added in SpiderMonkey 24 JS::ObjectOrNullValue Added in SpiderMonkey 24 JS::SymbolValue Added in SpiderMonkey 38 JS::Value constants: JS::NullHandleValue Added in SpiderMonkey 24 JS::
UndefinedHandleValue Added in SpiderMonkey 24 JS::TrueHandleValue Added in SpiderMonkey 38 JS::FalseHandleValue Added in SpiderMonkey 38 jsval constants: JSVAL_NULL Obsolete since JSAPI 42 JSVAL_VOID Obsolete since JSAPI 42 JSVAL_TRUE Obsolete since JSAPI 42 JSVAL_FALSE Obsolete since JSAPI 42 JSVAL_ZERO Obsolete since JSAPI 42 JSVAL_ONE Obsolete since JSAPI 42 Function and macros for checkin...
...ForwardGetPropertyTo Added in SpiderMonkey 17 JS_ForwardGetElementTo Added in SpiderMonkey 17 JS_GetPropertyDescriptor Added in SpiderMonkey 31 JS_GetPropertyDescriptorById Added in SpiderMonkey 1.8.1 JS_GetOwnPropertyDescriptor Added in SpiderMonkey 31 JS_GetOwnPropertyDescriptorById Added in SpiderMonkey 31 JS_GetOwnUCPropertyDescriptor Added in SpiderMonkey 45 JS_SetAllNonReservedSlotsTo
Undefined Added in SpiderMonkey 24 JS_AliasProperty Obsolete since JSAPI 8 JS_ClearScope Obsolete since JSAPI 18 JS_ClearNonGlobalObject Added in SpiderMonkey 18 Obsolete since JSAPI 34 JS_DefineOwnProperty Added in SpiderMonkey 1.8.5 Obsolete since JSAPI 33 JS_DefinePropertyWithTinyId Obsolete since JSAPI 30 JS_DefineUCPropertyWithTinyId Obsolete since JSAPI 30 JS_GetPropertyDefault Obsolete sin...
... in SpiderMonkey 31 JS_PS_END Added in SpiderMonkey 17 JSFastNative Added in SpiderMonkey 1.8 Obsolete since JavaScript 1.8.5 The behavior of a JSClass can be customized using these flags: JSClass.flags JSCLASS_HAS_PRIVATE JSCLASS_PRIVATE_IS_NSISUPPORTS JSCLASS_IS_DOMJSCLASS Added in SpiderMonkey 17 JSCLASS_IMPLEMENTS_BARRIERS Added in SpiderMonkey 17 JSCLASS_EMULATES_
UNDEFINED Added in SpiderMonkey 24 JSCLASS_HAS_RESERVED_SLOTS(n) JSCLASS_GLOBAL_FLAGS JSCLASS_NEW_ENUMERATE Obsolete since JSAPI 37 JSCLASS_NEW_RESOLVE Obsolete since JSAPI 36 JSCLASS_SHARE_ALL_PROPERTIES Obsolete since JavaScript 1.8.5 JSCLASS_NEW_RESOLVE_GETS_START Obsolete since JSAPI 16 JSCLASS_CONSTRUCT_PROTOTYPE Obsolete since JSAPI 11 JSCLASS_IS_EXTENDED Obsolete since JSAPI ...
WebIDL bindings
IDL callback interfaces in sequences, dictionaries, owning unions, and variadic arguments are represented by RefPtr<Foo> if nullable and OwningNonNull<Foo> otherwise. If the interface is a single-operation interface, the object exposes two methods that both invoke the same underlying JS callable. The first of these methods allows the caller to pass in a this object, while the second defaults to
undefined as the this value. In either case, the this value is only used if the callback interface is implemented by a JS callable. If it's implemented by an object with a property whose name matches the operation, the object itself is always used as this. If the interface is not a single-operation interface, it just exposes a single method for every IDL method/getter/setter. The signatures of the method...
...eference is passed in. The object exposes two Call methods, which both invoke the underlying JS callable. The first Call method has the same signature as a throwing method declared just like the callback function, with an additional trailing "mozilla::dom::CallbackObject::ExceptionHandling aExceptionHandling" argument, defaulting to eReportExceptions, and calling it will invoke the callable with
undefined as the this value. The second Call method allows passing in an explicit this value as the first argument. This second call method is a template on the type of the first argument, so the this value can be passed in in whatever form is most convenient, as long as it's either a type that can be wrapped by XPConnect or a WebIDL interface type. If aReportExceptions is set to eReportExceptions, the Ca...
...appens on the object. The signature of this method is: bool DoResolve(JSContext*, JS::Handle<JSObject*>, JS::Handle<jsid>, JS::MutableHandle<JS::Value>). Here the passed-in object is the object the property lookup is happening on (which may be an Xray for the actual DOM object) and the jsid is the property name. The value that the property should have is returned in the MutableHandle<Value>, with
UndefinedValue() indicating that the property does not exist. If this extended attribute is used, then the underlying C++ class must also implement a method called GetOwnPropertyNames with the signature void GetOwnPropertyNames(JSContext* aCx, nsTArray<nsString>& aNames, ErrorResult& aRv). This method will be called by the JS engine's enumerate hook and must provide a superset of all the property names th...
...entation="@mozilla.org/dom/foo;1"] interface Foo { [StaticClassOverride="mozilla::dom::OtherClass"] static Promise<void> doSomething(); }; Rather than calling into a method on the JS implementation; calling Foo.doSomething() will result in calling mozilla::dom::OtherClass::DoSomething(). Checking for Permissions or Preferences With JS-implemented WebIDL, the init method should only return
undefined. If any other value, such as null, is returned, the bindings code will assert or crash. In other words, it acts like it has a "void" return type. Preference or permission checking should be implemented by adding an extended attribute to the WebIDL interface. This has the advantage that if the check fails, the constructor or object will not show up at all. For preference checking, add an extended...
EventTarget.addEventListener() - Web APIs
been optional. Ideally, you should include it for the widest possible browser compatibility. wantsUntrusted A Firefox (Gecko)-specific parameter. If true, the listener receives synthetic events dispatched by web content (the default is false for browser chrome and true for regular web pages). This parameter is useful for code found in add-ons, as well as the browser itself. Return value
undefined Usage notes The event listener callback The event listener can be specified as either a callback function or an object that implements EventListener, whose handleEvent() method serves as the callback function. The callback function itself has the same parameters and return value as the handleEvent() method; that is, the callback accepts a single parameter: an object based on Event describing ...
...his inside a function, called by the code in the attribute value, behaves as per standard rules. This is shown in the following example: <script> function logID() { console.log(this.id); } </script> <table id="my_table" onclick="logID();"><!-- when called, `this` will refer to the global object --> ... </table> The value of this within logID() is a reference to the global object Window (or
undefined in the case of strict mode. Specifying "this" using bind() The Function.prototype.bind() method lets you specify the value that should be used as this for all calls to a given function. This lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called. Note, however, that you'll need to keep a reference to the listener around...
...this will be, depending on the context from which your function was called. Note, however, that you'll need to keep a reference to the listener around so you can remove it later. ...
...t.prototype.stopPropagation=function() { this.cancelBubble=true; }; } if (!Element.prototype.addEventListener) { var eventListeners=[]; var addEventListener=function(type,listener /*, useCapture (will be ignored) */) { var self=this; var wrapper=function(e) { e.target=e.srcElement; e.currentTarget=self; if (typeof listener.handleEvent != '
undefined') { listener.handleEvent(e); } else { listener.call(self,e); } }; if (type=="DOMContentLoaded") { var wrapper2=function(e) { if (document.readyState=="complete") { wrapper(e); } }; document.attachEvent("onreadystatechange",wrapper2); eventListeners.push({object:this,type:type,listener:l...
Page Visibility API - Web APIs
processes are also left unthrottled in order to avoid timeouts. Example View live example (video with sound). ...
... to another tab and plays again when you return to its tab, was created with the following code: // Set the name of the hidden property and the change event for visibility var hidden, visibilityChange; if (typeof document.hidden !== "
undefined") { // Opera 12.10 and Firefox 18 and later support hidden = "hidden"; visibilityChange = "visibilitychange"; } else if (typeof document.msHidden !== "
undefined") { hidden = "msHidden"; visibilityChange = "msvisibilitychange"; } else if (typeof document.webkitHidden !== "
undefined") { hidden = "webkitHidden"; visibilityChange = "webkitvisibilitychange"; } var videoElement = document.getElementById("videoElement"); // If the page is hidden, pause the video; // if the page is shown, play the video function handleVisibilityChange() { if (documen...
... // This shows the paused videoElement.addEventListener("pause", function(){ ...
... // This shows the paused videoElement.addEventListener("pause", function(){ document.title = 'Paused'...
TextEncoder - Web APIs
return a regular Array instead of a TypedArray. In those cases a polyfill might be impractical for large strings. Finally, note that you should run the below code through a minifier (especially closure compiler) to turn sequences like 0x1e << 3 into 0xf0. These sequences are not already precomputed because they serve to aesthetically illustrate how the polyfill works. if (typeof TextEncoder === "
undefined") { TextEncoder=function TextEncoder(){}; TextEncoder.prototype.encode = function encode(str) { "use strict"; var Len = str.length, resPos = -1; // The Uint8Array's length must be at least 3x the length of the string because an invalid UTF-16 // takes up the equivelent space of 3 UTF-8 characters to encode it properly. However, Array's // have an ...
...t"; var Len = str.length, resPos = -1; // The Uint8Array's length must be at least 3x the length of the string because an invalid UTF-16 // takes up the equivelent space of 3 UTF-8 characters to encode it properly. However, Array's // have an auto expanding length and 1.5x should be just the right balance for most uses. ...
...r[resPos += 1] = (0x2/*0b10*/<<6) | (point&0x3f/*0b00111111*/); } else { resArr[resPos += 1] = (0xe/*0b1110*/<<4) | (point>>>12); resArr[resPos += 1] = (0x2/*0b10*/<<6) | ((point>>>6)&0x3f/*0b00111111*/); resArr[resPos += 1] = (0x2/*0b10*/<<6) | (point&0x3f/*0b00111111*/); } } if (typeof Uint8Array !== "
undefined") return resArr.subarray(0, resPos + 1); // else // IE 6-9 resArr.length = resPos + 1; // trim off extra weight return resArr; }; TextEncoder.prototype.toString = function(){return "[object TextEncoder]"}; try { // Object.defineProperty only works on DOM prototypes in IE8 Object.defineProperty(TextEncoder.prototype,"encoding",{ get:function(...
... Living Standard Initial definition. ...
ARIA: button role - Accessibility
ssed Defines the button as a toggle button. The value of aria-pressed describes the state of the button. The values include aria-pressed="false" when a button is not currently pressed, aria-pressed="true" to indicate a button is currently pressed, and aria-pressed="mixed" if the button is considered to be partially pressed. If the attribute is omitted or set to its default value of aria-pressed="
undefined", the element does not support being pressed. aria-expanded If the button controls a grouping of other elements, the aria-expanded state indicates whether the controlled grouping is currently expanded or collapsed. If the button has aria-expanded="false" set, the grouping is not currently expanded; If the button has aria-expanded="true" set, it is currently expanded; if the button has aria-exp...
...element does not support being pressed. aria-expanded If the button controls a grouping of other elements, the aria-expanded state indicates whether the controlled grouping is currently expanded or collapsed. If the button has aria-expanded="false" set, the grouping is not currently expanded; If the button has aria-expanded="true" set, it is currently expanded; if the button has aria-expanded="
undefined" set or the attribute is ommitted, it is not expandable. Basic buttons Buttons should always have an accessible name. For most buttons, this name will be the same as the text inside the button. In some cases, for example buttons represented by icons, the accessible name may be provided from the aria-label or aria-labelledby attributes. Toggle buttons A toggle button typically has two states:...
...d. A third mixed state is available for toggle buttons that control other elements, such as other toggle buttons or checkboxes, which do not all share the same value. Whether an element is a toggle button or not can be indicated with the aria-pressed attribute in addition to the button role (if the element is not already a native button element): If aria-pressed is not used, or is set to the "
undefined" state, the button is not a toggle button. If aria-pressed="false" is used the button is a toggle button that is currently not pressed. If aria-pressed="true" is used the button is a toggle button that is currently pressed. if aria-pressed="mixed" is used, the button is considered to be partially pressed. As an example, the mute button on an audio player labeled "mute" could indicate that s...
...nt raised when the button is activated using a mouse click or touch event. onKeyDown Handles the event raised when the button is activated using the Enter or Space key on the keyboard. (Note not the deprecated onKeyPress) Changing attribute values aria-pressed The value of aria-pressed defines the state of a toggle button. This attribute has one of four possible values: true, false, mixed,
undefined Examples Basic button example In this example, a span element has been given the button role. Because a <span> element is used, the tabindex attribute is required to make the button focusable and part of the page's tab order. The included CSS style is provided to make the <span> element look like a button, and to provide visual cues when the button has focus. The handleBtnClick and handleBtnK...
Border-radius generator - CSS: Cascading Style Sheets
.textContent = name; node.appendChild(info); } node.appendChild(slider_left); node.appendChild(input); node.appendChild(slider_right); node.className = 'ui-input-slider ui-input-slider-container'; this.input = input; sliders[topic] = this; setValue(topic, value); } var setValue = function setValue(topic, value, send_notify) { var slider = sliders[topic]; if (slider ===
undefined) return; if (value > slider.max) value = slider.max; if (value < slider.min) value = slider.min; slider.value = value; slider.node.setAttribute('data-value', value); if (send_notify !==
undefined && send_notify === false) { slider.input.value = value + slider.unit; return; } notify.call(slider); } var setMax = function setMax(topic, value) { var slider = sliders[to...
...ue > slider.max) value = slider.max; if (value < slider.min) value = slider.min; slider.value = value; slider.node.setAttribute('data-value', value); if (send_notify !==
undefined && send_notify === false) { slider.input.value = value + slider.unit; return; } notify.call(slider); } var setMax = function setMax(topic, value) { var slider = sliders[topic]; if (slider ===
undefined) return; slider.max = value; setValue(topic, slider.value); } var setMin = function setMin(topic, value) { var slider = sliders[topic]; if (slider ===
undefined) return; slider.min = value; setValue(topic, slider.value); } var setUnit = function setUnit(topic, unit) { var slider = sliders[topic]; if (slider ===
undefined) return; slider.unit = unit; setValue(...
...n; slider.min = value; setValue(topic, slider.value); } var setUnit = function setUnit(topic, unit) { var slider = sliders[topic]; if (slider ===
undefined) return; slider.unit = unit; setValue(topic, slider.value); } var getNode = function getNode(topic) { return sliders[topic].node; } var subscribe = function subscribe(topic, callback) { if (subscribers[topic] ===
undefined) subscribers[topic] = []; subscribers[topic].push(callback); } var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexOf(callback); subscribers[topic].splice(index, 1); } var notify = function notify() { for (var i in subscribers[this.topic]) { subscribers[this.topic][i](this.value); } } var init = function init() { var elem = document.querySe...
...', function(e) { notify.call(this); }.bind(this)); buttons[topic] = this; } var getNode = function getNode(topic) { return buttons[topic].node; } var setValue = function setValue(topic, value) { try { buttons[topic].checkbox.checked = value; } catch(error) { console.log(error); } } var subscribe = function subscribe(topic, callback) { if (subscribers[topic] ===
undefined) subscribers[topic] = []; subscribers[topic].push(callback); } var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexOf(callback); subscribers[topic].splice(index, 1); } var notify = function notify() { for (var i = 0; i < subscribers[this.topic].length; i++) subscribers[this.topic][i](this.checkbox.checked); } var init = function init() { var...
Functions - JavaScript
function in which it is declared (or the entire program, if it is declared at the top level). Note: This works only when defining the function using the above syntax (i.e. function funcName(){}). The code below will not work. This means that function hoisting only works with function declarations--not with function expressions. console.log(square) // square is hoisted with an initial value
undefined. console.log(square(5)) // Uncaught TypeError: square is not a function const square = function(n) { return n * n; } The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function. The show_props() function (defined in Working with objects) is an example of a function that takes an object as an argument. A function can call itself. For example, ...
... that it has a numbered index and a length property. However, it does not possess all of the array-manipulation methods. See the Function object in the JavaScript reference for more information. Function parameters Starting with ECMAScript 2015, there are two new kinds of parameters: default parameters and rest parameters. Default parameters In JavaScript, parameters of functions default to
undefined. However, in some situations it might be useful to set a different default value. This is exactly what default parameters do. Without default parameters (pre-ECMAScript 2015) In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are
undefined. In the following example, if no value is provided for b, its value ...
..., in some situations it might be useful to set a different default value. This is exactly what default parameters do. Without default parameters (pre-ECMAScript 2015) In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are
undefined. In the following example, if no value is provided for b, its value would be
undefined when evaluating a*b, and a call to multiply would normally have returned NaN. However, this is prevented by the second line in this example: function multiply(a, b) { b = typeof b !== '
undefined' ? b : 1; return a * b; } multiply(5); // 5 With default parameters (post-ECMAScript 2015) With default parameters, a manual check in the function body is no longer necessary. You can simply pu...
...horter functions are welcome. Compare: var a = [ 'Hydrogen', 'Helium', 'Lithium', 'Beryllium' ]; var a2 = a.map(function(s) { return s.length; }); console.log(a2); // logs [8, 6, 7, 9] var a3 = a.map(s => s.length); console.log(a3); // logs [8, 6, 7, 9] No separate this Until arrow functions, every new function defined its own this value (a new object in the case of a constructor,
undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming. function Person() { // The Person() constructor defines `this` as itself. this.age = 0; setInterval(function growUp() { // In nonstrict mode, the growUp() function defines `this` // as the global obje...
TypeError: can't access property "x" of "y" - JavaScript
The JavaScript exception "can't access property" occurs when property access was operated on
undefined or null values. Message TypeError: Unable to get property {x} of
undefined or null reference (Edge) TypeError: can't access property {x} of {y} (Firefox) TypeError: {y} is
undefined, can't access property {x} of it (Firefox) TypeError: {y} is null, can't access property {x} of it (Firefox) Examples: TypeError: x is
undefined, can't access property "prop" of it TypeError: x is null, can't access property "prop" of it TypeError: can't access property "prop" of
undefined TypeError: can't access property "prop" of null Error type TypeError. ...
...ty {x} of it (Firefox) TypeError: {y} is null, can't access property {x} of it (Firefox) Examples: TypeError: x is
undefined, can't access property "prop" of it TypeError: x is null, can't access property "prop" of it TypeError: can't access property "prop" of
undefined TypeError: can't access property "prop" of null Error type TypeError. What went wrong? The property access was operated on
undefined or null value. ...
...ccess property {x} of it (Firefox) Examples: TypeError: x is
undefined, can't access property "prop" of it TypeError: x is null, can't access property "prop" of it TypeError: can't access property "prop" of
undefined TypeError: can't access property "prop" of null Error type TypeError. What went wrong? The property access was operated on
undefined or null value. Examples Invalid cases //
undefined and null cases on which the substring method won't work var foo =
undefined; foo.substring(1); // TypeError: x is
undefined, can't access property "substring" of it var foo = null; foo.substring(1); // TypeError: x is null, can't access property "substring" of it Fixing the issue To fix null pointer to
undefined or null values, you can use the typeof operator, for example. if (typeof foo !==...
...nd null cases on which the substring method won't work var foo =
undefined; foo.substring(1); // TypeError: x is
undefined, can't access property "substring" of it var foo = null; foo.substring(1); // TypeError: x is null, can't access property "substring" of it Fixing the issue To fix null pointer to
undefined or null values, you can use the typeof operator, for example. if (typeof foo !== '
undefined') { // Now we know that foo is defined, we are good to go. } ...
TypeError: "x" is read-only - JavaScript
ct.defineProperty(this, 'LUNG_COUNT', {value: 2, writable: false}); LUNG_COUNT = 3; // TypeError 'use strict'; var frozenArray = Object.freeze([0, 1, 2]); frozenArray[0]++; // TypeError There are also a few read-only properties built into JavaScript. Maybe you tried to redefine a mathematical constant. 'use strict'; Math.PI = 4; // TypeError Sorry, you can't do that. ...
...}); LUNG_COUNT = 3; // TypeError 'use strict'; var frozenArray = Object.freeze([0, 1, 2]); frozenArray[0]++; // TypeError There are also a few read-only properties built into JavaScript. Maybe you tried to redefine a mathematical constant. 'use strict'; Math.PI = 4; // TypeError Sorry, you can't do that. ...
...= Object.freeze([0, 1, 2]); frozenArray[0]++; // TypeError There are also a few read-only properties built into JavaScript. Maybe you tried to redefine a mathematical constant. 'use strict'; Math.PI = 4; // TypeError Sorry, you can't do that. ...
...+; // TypeError There are also a few read-only properties built into JavaScript. Maybe you tried to redefine a mathematical constant. 'use strict'; Math.PI = 4; // TypeError Sorry, you can't do that. ...
Error.prototype.toString() - JavaScript
he specified Error object. Description The Error object overrides the Object.prototype.toString() method inherited by all objects. ...
...ototype.toString() method inherited by all objects. ...
... ...
... ...
Map - JavaScript
operations on the data fail: wrongMap.has('bla') // false wrongMap.delete('bla') // false console.log(wrongMap) // Map { bla: 'blaa', bla2: 'blaaa2' } The correct usage for storing data in the Map is through the set(key, value) method. let contacts = new Map() contacts.set('Jessie', {phone: "213-555-1234", address: "123 N 1st Ave"}) contacts.has('Jessie') // true contacts.get('Hilary') //
undefined contacts.set('Hilary', {phone: "617-555-4321", address: "321 S 2nd St"}) contacts.get('Jessie') // {phone: "213-555-1234", address: "123 N 1st Ave"} contacts.delete('Raymond') // false contacts.delete('Jessie') // true console.log(contacts.size) // 1 Constructor Map() Creates a new Map object. Static properties get Map[@@species] The constructor function that is used to create derive...
...er of key/value pairs in the Map object. Instance methods Map.prototype.clear() Removes all key-value pairs from the Map object. Map.prototype.delete(key) Returns true if an element in the Map object existed and has been removed, or false if the element does not exist. Map.prototype.has(key) will return false afterwards. Map.prototype.get(key) Returns the value associated to the key, or
undefined if there is none. Map.prototype.has(key) Returns a boolean asserting whether a value has been associated to the key in the Map object or not. Map.prototype.set(key, value) Sets the value for the key in the Map object. Returns the Map object. Iteration methods Map.prototype[@@iterator]() Returns a new Iterator object that contains an array of [key, value] for each element in the Map obje...
...Even though every NaN is not equal to itself (NaN !== NaN is true), the following example works because NaNs are indistinguishable from each other: let myMap = new Map() myMap.set(NaN, 'not a number') myMap.get(NaN) // "not a number" let other...
...Even though every NaN is not equal to itself (NaN !== NaN is true), the following example works because NaNs are indistinguishable from each other: let myMap = new Map() myMap.set(NaN, 'not a number') myMap.get(NaN) // "not a number" let otherNaN = Number('foo') myMap.get(otherNaN) // "not a number" I...
Object.prototype.__defineSetter__() - JavaScript
erty. Syntax obj.__defineSetter__(prop, fun) Parameters prop A string containing the name of the property to be bound to the given function. fun A function to be called when there is an attempt to set the specified property. This function takes the form function(val) { . . . } val An alias for the variable that holds the value attempted to be assigned to prop. Return value
undefined. ...
...) { . . . } val An alias for the variable that holds the value attempted to be assigned to prop. Return value
undefined. Description The __defineSetter__ method allows a setter to be defined on a pre-existing object. ...
... to be defined on a pre-existing object. ...
... ...
Object.assign() - JavaScript
s (including their enumerability) into prototypes, use Object.getOwnPropertyDescriptor() and Object.defineProperty() instead. Both String and Symbol properties are copied. In case of an error, for example if a property is non-writable, a TypeError is raised, and the target object is changed if any properties are added before the error is raised. Note: Object.assign() does not throw on null or
undefined sources. Polyfill This polyfill doesn't support symbol properties, since ES5 doesn't have symbols anyway: if (typeof Object.assign !== 'function') { // Must be writable: true, enumerable: false, configurable: true Object.defineProperty(Object, "assign", { value: function assign(target, varArgs) { // .length of function is 2 'use strict'; if (target === null || target === u...
...ol properties, since ES5 doesn't have symbols anyway: if (typeof Object.assign !== 'function') { // Must be writable: true, enumerable: false, configurable: true Object.defineProperty(Object, "assign", { value: function assign(target, varArgs) { // .length of function is 2 'use strict'; if (target === null || target ===
undefined) { throw new TypeError('Cannot convert
undefined or null to object'); } var to = Object(target); for (var index = 1; index < arguments.length; index++) { var nextSource = arguments[index]; if (nextSource !== null && nextSource !==
undefined) { for (var nextKey in nextSource) { // Avoid bugs when hasOwnProperty is shadowed if (Object.prototype.hasOwnProperty.call(nextSource, ...
...ype chain. bar: { value: 2 // bar is a non-enumerable property. }, baz: { value: 3, enumerable: true // baz is an own enumerable property. } }); const copy = Object.assign({}, obj); console.log(copy); // { baz: 3 } Primitives will be wrapped to objects const v1 = 'abc'; const v2 = true; const v3 = 10; const v4 = Symbol('foo'); const obj = Object.assign({}, v1, null, v2,
undefined, v3, v4); // Primitives will be wrapped, null and
undefined will be ignored. // Note, only string wrappers can have own enumerable properties. console.log(obj); // { "0": "a", "1": "b", "2": "c" } Exceptions will interrupt the ongoing copying task const target = Object.defineProperty({}, 'foo', { value: 1, writable: false }); // target.foo is a read-only property Object.assign(target, { b...
...{ bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 }); // TypeError: "foo" is read-only // The Exception is thrown when assigning target.foo console.log(target.bar); // 2, the first source was copied successfully. console.log(target.foo2); // 3, the first property of the second source was copied successfully. console.log(target.foo); // 1, exception is thrown here. console.log(target.foo3); //
undefined, assign method has finished, foo3 will not be copied. console.log(target.baz); //
undefined, the third source will not be copied either. Copying accessors const obj = { foo: 1, get bar() { return 2; } }; let copy = Object.assign({}, obj); console.log(copy); // { foo: 1, bar: 2 } // The value of copy.bar is obj.bar's getter's return value. // This is an assign function that copies ...
Object.create() - JavaScript
this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Object.create(proto, [propertiesObject]) Parameters proto The object which should be the prototype of the newly-created object. propertiesObject Optional If specified and not
undefined, an object whose enumerable own properties (that is, those properties defined upon itself and not enumerable properties along its prototype chain) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of Object.defineProperties(). Return value A new object with the specified prototype obje...
...For example: A simple common debugging function: // display top-level property name:value pairs of given object function ShowProperties(obj){ for(var prop in obj){ console.log(prop + ": " + obj[prop] + "\n" ); } } Not such simple results: (especially if silent error-trapping had hidden the ...
... Function Adding the missing object-method directly to new object's "prototype" does not work either, since the new object does not have a real prototype (which is really the cause of ALL these problems) and one cannot be directly added: ocn = Object.create( null ); // create "null" object (same as before) ocn.prototype.toString = Object.toString; // Error: Cannot set property 'toString' of
undefined ocn.prototype = {}; // try to create a prototype ocn.prototype.toString = Object.toString; // since new object lacks method then try assigning it from standard-object > ocn.toString() // error: ocn.toString is not a function Adding the missing object-method by using the standard-object as new object's prototype does not work either: ocn = Object.create( null ); ...
...This is for a single inherita...
Object - JavaScript
to the Object prototype object are seen by all objects through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain. This provides a very powerful although potentially dangerous mechanism to override or extend object behavior. The Object constructor creates an object wrapper for the given value. If the value is null or
undefined, it will create and return an empty object. Otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value. When called in a non-constructor context, Object behaves identically to new Object(). See also the object initializer / literal syntax. Deleting a property from an object There isn't any method in an Obje...
...hat correspond to all of a given object's own enumerable string properties. Instance properties Object.prototype.constructor Specifies the function that creates an object's prototype. Object.prototype.__proto__ Points to the object which was used as prototype when the object was instantiated. Object.prototype.__noSuchMethod__ Allows a function to be defined that will be executed when an
undefined object member is called as a method. Instance methods Object.prototype.__defineGetter__() Associates a function with a property that, when accessed, executes that function and returns its return value. Object.prototype.__defineSetter__() Associates a function with a property that, when set, executes that function which modifies the property. Object.prototype.__lookupGetter__() Returns t...
... Object.prototype.toLocaleString() Calls toString(). Object.prototype.toString() Returns a string representation of the object. Object.prototype.unwatch() Removes a watchpoint from a property of the object. Object.prototype.valueOf() Returns the primitive value of the specified object. Object.prototype.watch() Adds a watchpoint to a property of the object. ...
...ect. Object.prototype.unwatch() Removes a watchpoint from a property of the object. Object.prototype.valueOf() Returns the primitive value of the specified object. Object.prototype.watch() Adds a watchpoint to a property of the object. ...
Promise.prototype.catch() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
... The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
... onRejected A Function called when the Promise is rejected. This function has one argument: reason The rejection reason. The Promise returned by catch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is resolved. Return value Internally calls Promise.prototype.then on the object upon which it was called, passing the parameters
undefined and the received onRejected handler. Returns the value of that call, which is a Promise. Note the examples below are throwing instances of Error. This is considered good practice in contrast to throwing Strings; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information like stack traces. Demonst...
...Since it returns a Promise, it can be chained in the same way as its sister method, then(). Examples Using and chaining the catch method var p1 = new Promise(function(resolve, reject) { resolve('Success'); }); p1.then(function(value) { console.log(value); // "Success!" throw new Error(...
Proxy - JavaScript
tic methods Proxy.revocable() Creates a revocable Proxy object. Examples Basic example In this simple example, the number 37 gets returned as the default value when the property name is not in the object. It is using the get handler. const handler = { get: function(obj, prop) { return prop in obj ? obj[prop] : 37; } }; const p = new Proxy({}, handler); p.a = 1; p.b =
undefined; console.log(p.a, p.b); // 1,
undefined console.log('c' in p, p.c); // false, 37 No-op forwarding proxy In this example, we are using a native JavaScript object to which our proxy will forward all operations that are applied to it. const target = {}; const p = new Proxy(target, {}); p.a = 37; // operation forwarded to the target console.log(target.a); // 37 // (The operation has been...
...pes[product.type]) { types[product.type].push(product); } else { types[product.type] = [product]; } } // Get a product by name if (result) { return result; } // Get products by type if (prop in types) { return types[prop]; } // Get product types if (prop === 'types') { return Object.keys(types); } return
undefined; } }); console.log(products[0]); // { name: 'Firefox', type: 'browser' } console.log(products['Firefox']); // { name: 'Firefox', type: 'browser' } console.log(products['Chrome']); //
undefined console.log(products.browser); // [{ name: 'Firefox', type: 'browser' }, { name: 'SeaMonkey', type: 'browser' }] console.log(products.types); // ['browser', 'mailer'] console.log(pr...
...d by the "little framework" published on the document.cookie page. /* var docCookies = ... ...
... ...
String.prototype.codePointAt() - JavaScript
If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.codePointAt(pos) Parameters pos Position of an element in str to return the code point value from. Return value A number representing the code point value of the character at the given pos. If there is no element at pos, returns
undefined. Description If there is no element at the specified position,
undefined is returned. If no UTF-16 surrogate pair begins at pos, the code unit at pos is returned. Polyfill The following extends Strings to include the codePointAt() function as specified in ECMAScript 2015 for browsers without native support. /*! https://mths.be/codepointat v0.2.0 by @mathias */ if (!String.prototype.codePoin...
...rned. If no UTF-16 surrogate pair begins at pos, the code unit at pos is returned. Polyfill The following extends Strings to include the codePointAt() function as specified in ECMAScript 2015 for browsers without native support. ...
...ointAt = function(position) { if (this == null) { throw TypeError(); } var string = String(this); var size = string.length; // `ToInteger` var index = position ? ...
... ...
TypedArray.prototype.find() - JavaScript
TypedArray is one of the typed array types here. See also the findIndex() method, which returns the index of a found element in the typed array instead of its value. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
... on each value in the typed array, taking three arguments: element The current element being processed in the typed array. index The index of the current element being processed in the typed array. array The array find was called upon. thisArg Optional. Object to use as this when executing callback. Return value A value in the array if an element passes the test; otherwise,
undefined. Description The find method executes the callback function once for each element present in the typed array until it finds one where callback returns a true value. If such an element is found, find immediately returns the value of that element. Otherwise, find returns
undefined. callback is invoked only for indexes of the typed array which have assigned values; it is not invoked for indexes wh...
...hich have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. callback is invoked with three arguments: the value of the element, the index of the element, and the typed array object being traversed. If a thisArg parameter is provided to find, it will be used as the this for each invocation of the callback. If it is not provided, then
undefined is used. find does not mutate the typed array on which it is called. The range of elements processed by find is set before the first invocation of callback. Elements that are appended to the typed array after the call to find begins will not be visited by callback. If an existing, unvisited element of the typed array is changed by callback, its value passed to the visiting callback will be the ...
...ot be visited by callback. If an existing, unvisited element of the typed array is changed by callback, its value passed to the visiting callback will be the value at the time that find visits that element's index; elements that are deleted are not visited. Examples Find a prime number in a typed array The following example finds an element in the typed array that is a prime number (or returns
undefined if there is no prime number). function isPrime(element, index, array) { var start = 2; while (start <= Math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } var uint8 = new Uint8Array([4, 5, 8, 12]); console.log(uint8.find(isPrime)); // 5 Specifications Specification ECMAScript (ECMA-262)The definition of '%TypedArra...
globalThis - JavaScript
figurable yes Description Historically, accessing the global object has required different syntax in different JavaScript environments. On the web you can use window, self, or frames - but in Web Workers only self will work. In Node.js none of these work, and you must instead use global. The this keyword could be used inside functions running in non-strict mode, but this will be
undefined in Modules and inside functions running in strict mode. You can also use Function('return this')(), but environments that disable eval(), like CSP in browsers, prevent use of Function in this way. The globalThis property provides a standard way of accessing the global this value (and hence the global object itself) across environments. Unlike similar properties such as window and self, it's guar...
...language proposal's "naming" document for more details. Examples Search for the global across environments Prior to globalThis, the only reliable cross-platform way to get the global object for an environment was Function('return this')(). ...
.... Examples Search for the global across environments Prior to globalThis, the only reliable cross-platform way to get the global object for an environment was Function('return this')(). ...
...Prior to globalThis, the only reliable cross-platform way to get the global object for an environment was Function('return this')(). ...
null - JavaScript
alsy for boolean operations. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax null Description The value null is written with a literal: null. null is not an identifier for a property of the global object, like
undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object. In APIs, null is often retrieved in a place where an object can be expected but no object is relevant. // foo does not exist. It is not defined and has never been initialized: foo; //ReferenceError: foo is not defined // foo is known to exist now but it has no type or value: var foo = null...
...ion, indicating that a variable points to no object. In APIs, null is often retrieved in a place where an object can be expected but no object is relevant. // foo does not exist. ...
...s to no object. In APIs, null is often retrieved in a place where an object can be expected but no object is relevant. // foo does not exist. ...
...eferenceError: foo is not defined // foo is known to exist now but it has no type or value: var foo = null; foo; //null Examples Difference between null and
undefined When checking for null or
undefined, beware of the differences between equality (==) and identity (===) operators, as the former performs type-conversion. typeof null // "object" (not "null" for legacy reasons) typeof
undefined // "
undefined" null ===
undefined // false null ==
undefined // true null === null // true null == null // true !null // true isNaN(1 + null) // false isNaN(1 +
undefined) // true Specifications Specification ECMAScript (ECMA-262)The definition of 'null value' in that specification. ...
Equality (==) - JavaScript
e clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax x == y Description The equality operators (== and !=) use the Abstract Equality Comparison Algorithm to compare two operands. This can be roughly summarised as follows: If the operands are both objects, return true only if both operands reference the same object. If one operand is null and the other is
undefined, return true. If the operands are of different types, try to convert them to the same type before comparing: When comparing a number to a string, try to convert the string to a numeric value. If one of the operands is Boolean, convert the Boolean operand to 1 if it is true and +0 if it is false. If one of the operands is an object and the other is a number or a string, try to convert...
... does not attempt type conversion. Instead, the strict equality operator always considers operands of different types to be different. ...
...rands of different types to be different. ...
...If you compare ...
delete operator - JavaScript
ers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property value is indeed set to
undefined, if one later adds back a property with the same name, the property will be iterated in its old position--not at the end of the iteration sequence as one might expect after having deleted the property and then added it back. If you want to use an ordered associative array in a cross-browser environment, use a Map object if available, or simulate this structure with two separate arrays (one for t...
...onsole.log(foo.bar); // 10 // Delete the own property within the // foo object. delete foo.bar; // returns true // foo.bar is still available in the // prototype chain. console.log(foo.bar); // 42 // Delete the property on the prototype. delete Foo.prototype.bar; // returns true // The "bar" property can no longer be // inherited from Foo since it has been // deleted. console.log(foo.bar); //
undefined Deleting array elements When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array. When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete. var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; delete trees[3]; if (3 in trees) { ...
...not affected. This holds even if you delete the last element of the array. When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete. ...
...even if you delete the last element of the array. When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete. var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; delete trees[3]; if (3 in trees) { // this is not executed } If you want an array element to exist but have an
undefined value, use the
undefined value instead of the delete operator. In the following example, trees[3] is assigned the value
undefined, but the array element still exists: var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; trees[3] =
undefined; if (3 in trees) { // this is executed } If instead, you want to remove an array element by changing the contents of the array, use the splice() method. In the following exa...
void operator - JavaScript
The void operator evaluates the given expression and then returns
undefined. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax void expression Description This operator allows evaluating expressions that produce a value into places where an expression that evaluates to
undefined is desired. The void operator is often used merely to obtain the
undefined primitive value, usually using "void(0)" (which is equivalent to "void 0"). In these cases, the global variable
undefined can be used. It should be noted that the precedence of the void operator should be taken into account and that parentheses can help clarify t...
...ly using "void(0)" (which is equivalent to "void 0"). In these cases, the global variable
undefined can be used. It should be noted that the precedence of the void operator should be taken into account and that parentheses can help clarify the resolution of the expression following the void operator: void 2 == '2'; // (void 2) == '2', returns false void (2 == '2'); // void (2 == '2'), returns
undefined Examples Immediately Invoked Function Expressions When using an immediately-invoked function expression, void can be used to force the function keyword to be treated as an expression instead of a declaration. void function iife() { console.log("Executed!"); }(); // Output: "Executed!" Executing the above function without the void keyword will result in an Uncaught SyntaxError. JavaSc...
...sion instead of a declaration. void function iife() { console.log("Executed!"); }(); // Output: "Executed!" Executing the above function without the void keyword will result in an Uncaught SyntaxError. JavaScript URIs When a browser follows a javascript: URI, it evaluates the code in the URI and then replaces the contents of the page with the returned value, unless the returned value is
undefined. The void operator can be used to return
undefined. For example: <a href="javascript:void(0);"> Click here to do nothing </a> <a href="javascript:void(document.body.style.backgroundColor='green');"> Click here for green background </a> Note: javascript: pseudo protocol is discouraged over other alternatives, such as unobtrusive event handlers. Non-leaking Arrow Functions Arrow functio...
...de effects by returning the result of a function call that previously returned nothing. To be safe, when the return value of a function is not intended to be used, it can be passed to the void operator to ensure that (for example) changing APIs do not cause arrow functions' behaviors to change. button.onclick = () => void doSomething(); This ensures the return value of doSomething changing from
undefined to true will not change the behavior of this code. Specifications Specification ECMAScript (ECMA-262)The definition of 'The void Operator' in that specification. ...
function declaration - JavaScript
nes. statements Optional The statements which comprise the body of the function. Description A function created with a function declaration is a Function object and has all the properties, methods and behavior of Function objects. See Function for detailed information on functions. A function can also be created using an expression (see function expression). By default, functions return
undefined. To return any other value, the function must have a return statement that specifies the value to return. Conditionally created functions Functions can be conditionally declared, that is, a function statement can be nested within an if statement, however the results are inconsistent across implementations and therefore this pattern should not be used in production code. For conditional function...
...s are inconsistent across implementations and therefore this pattern should not be used in production code. For conditional function creation, use function expressions instead. var hoisted = "foo" in this; console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`); if (false) { function foo(){ return 1; } } // In Chrome: // 'foo' name is hoisted. typeof foo is
undefined // // In Firefox: // 'foo' name is hoisted. typeof foo is
undefined // // In Edge: // 'foo' name is not hoisted. typeof foo is
undefined // // In Safari: // 'foo' name is hoisted. typeof foo is function The results are exactly the same for a condition that evaluates to true var hoisted = "foo" in this; console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`);...
...typeof foo is function Function declaration hoisting Function declarations in JavaScript are hoisted to the top of the enclosing function or global scope. ...
... is hoisted. typeof foo is function The results are exactly the same for a condition that evaluates to true var hoisted = "foo" in this; console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`); if (true) { function foo(){ return 1; } } // In Chrome: // 'foo' name is hoisted. typeof foo is
undefined // // In Firefox: // 'foo' name is hoisted. typeof foo is
undefined // // In Edge: // 'foo' name is not hoisted. typeof foo is
undefined // // In Safari: // 'foo' name is hoisted. typeof foo is function Function declaration hoisting Function declarations in JavaScript are hoisted to the top of the enclosing function or global scope. You can use the function before you declared it: hoisted(); // logs "foo" function hoisted() { console.log('foo'); } Note t...
Strict mode - JavaScript
to NaN does nothing; the developer receives no failure feedback. In strict mode assigning to NaN throws an exception. ...
...manner, substantially reduce the need for those runtime checks. First, the value passed as this to a function in strict mode is not forced into being an object (a.k.a. "boxed"). For a normal function, this is always an object: either the provided object if called with an object-valued this; the value, boxed, if called with a Boolean, string, or number this; or the global object if called with an
undefined or null this. (Use call, apply, or bind to specify a particular this.) Not only is automatic boxing a performance cost, but exposing the global object in browsers is a security hazard because the global object provides access to functionality that "secure" JavaScript environments must restrict. Thus for a strict mode function, the specified this is not boxed into an object, and if unspecified, th...
...is. (Use call, apply, or bind to specify a particular this.) Not only is automatic boxing a performance cost, but exposing the global object in browsers is a security hazard because the global object provides access to functionality that "secure" JavaScript environments must restrict. ...
...boxing a performance cost, but exposing the global object in browsers is a security hazard because the global object provides access to functionality that "secure" JavaScript environments must restrict. Thus for a strict mode function, the specified this is not boxed into an object, and if unspecified, this will be
undefined: 'use strict'; function fun() { return this; } console.assert(fun() ===
undefined); console.assert(fun.call(2) === 2); console.assert(fun.apply(null) === null); console.assert(fun.call(
undefined) ===
undefined); console.assert(fun.bind(true)() === true); That means, among other things, that in browsers it's no longer possible to reference the window object through this inside a strict mode function. Second, in strict mode it's no longer possible to "walk" the JavaScript sta...
LiveConnect Overview - Archive of obsolete content
Connect. These conversions are described in the following sections: JavaScript to Java Conversions Java to JavaScript Conversions JavaScript to Java Conversions When you call a Java method and pass it parameters from JavaScript, the data types of the parameters you pass in are converted according to the rules described in the following sections: Number Values Boolean Values String Values
Undefined Values Null Values JavaArray and JavaObject objects JavaClass objects Other JavaScript objects The return values of methods of netscape.javascript.JSObject are always converted to instances of java.lang.Object. The rules for converting these return values are also described in these sections. For example, if JSObject.eval returns a JavaScript number, you can find the rules for converting thi...
...cording to the rules described in ECMA-262. char JavaScript 1.4: One-character strings are converted to Unicode characters. All other values are converted to numbers. JavaScript 1.3 and earlier: All values are converted to numbers. boolean The empty string becomes false. All other values become true.
Undefined Values When you pass
undefined JavaScript values as parameters to Java methods, Java converts the values according to the rules described in the following table: Java parameter type Conversion rules java.lang.String java.lang.Object The value is converted to an instance of java.lang.String whose value is the string "
undefined". boolean The value becomes...
...following table: Java parameter type Conversion rules java.lang.String java.lang.Object The value is converted to an instance of java.lang.String whose value is the string "
undefined". boolean The value becomes false. double float The value becomes NaN. byte char int long short The value becomes 0. The
undefined value conversion is possible in JavaScript 1.3 and later versions only. Earlier versions of JavaScript do not support
undefined values. When a JavaScript
undefined value is passed as a parameter to a Java method which expects an instance of java.lang.String, the
undefined value is converted to a string. Use the == operator to compare the result of this conversion with other string values. Null Va...
Falsy - MDN Web Docs Glossary: Definitions of Web-related terms
Boolean in contexts that require it, such as conditionals and loops. There are 8 falsy values: false The keyword false 0 The number zero -0 The number negative zero 0n BigInt, when used as a boolean, follows the same rule as a Number. 0n is falsy. ...
...ontexts that require it, such as conditionals and loops. There are 8 falsy values: false The keyword false 0 The number zero -0 The number negative zero 0n BigInt, when used as a boolean, follows the same rule as a Number. 0n is falsy. ...
...
undefined undefined - the primitive value NaN NaN - not a number Objects are falsy if and only if they have the [[IsHTMLDDA]] internal slot. This slot only exists in document.all and cannot be set using JavaScript. Examples Examples of falsy values in JavaScript (which are coerced to false in Boolean contexts, and thus bypass the if block): if (false) if (null) if (
undefined) if (0) if (-0) if (0n) if (NaN) if ("") The logical AND operator, && If the first object is falsy, it returns that object false && "dog" // ? false 0 && "dog" // ? 0 Specifications Specification ECMAScript (ECMA-262)The definition of 'ToBoolean abstract operation' in that specification. Learn more Truthy Boolean ...
TypeScript support in Svelte - Learn web development
The same thing is happening wit...
... </script> TodosStatus.svelte We are encountering the following errors related to passing todos to the TodosStatus.svelte (and Todo.svelte) components: ./src/components/Todos.svelte:70:39 Error: Type 'TodoType[]' is not assignable to type '
undefined'. (ts) <TodosStatus bind:this={todosStatus} {todos} /> ./src/components/Todos.svelte:76:12 Error: Type 'TodoType' is not assignable to type '
undefined'. (ts) <Todo {todo} This is because the todos prop in the TodosStatus component has no default value, so TypeScript has inferred it to be of type
undefined, which is not compatible with an array of TodoType. The same thing is happening with our Todo component. Let's fix it. Open the file TodosStatus.svelte and add the lang='ts' attribute. Then import the TodoType and declare th...
...he file to localStore.ts. TypeScript is telling us to specify the type of the key, initial, and value variables. The first one is easy -- the key of our local web storage should be a string. But initial and value should be any object that could be converted to a valid JSON string with the JSON.stringify method. So it is in fact any JavaScript object with a couple limitations, for example
undefined, functions, and symbols are not valid JSON values. So we'll create the type JsonValue to specify these conditions. Create the file json.type.ts in the types folder. Give it the following content: export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue } The | operator lets us declare variables that could store values of two or more typ...
Handling common JavaScript problems - Learn web development
s more powerful too. Browser developer tools Browser developer tools have many useful features for helping to debug JavaScript. For a start, the JavaScript console will report errors in your code. Make a local copy of our broken-ajax.html example (see the source code also). If you look at the console, you'll see the error message "Uncaught TypeError: can't access property "length", heroes is
undefined", and the referenced line number is 49. If we look at the source code, the relevant code section is this: function showHeroes(jsonObj) { let heroes = jsonObj['members']; for(i = 0; i < heroes.length; i++) { ... So the code falls over as soon as we try to access a property of jsonObj (which as you might expect, is supposed to be a JSON object). This is supposed to be fetched from an exter...
...u'll see the currently active scope for the function we are looking at. We only have three -- showHeroes, block, and Window (the global scope). Each scope can be expanded to show the values of variables inside the scope when execution of the code was stopped. We can find out some very useful information in here. Expand the showHeroes scope -- you can see from this that the heroes variable is
undefined, indicating that accessing the members property of jsonObj (first line of the function) didn't work. You can also see that the jsonObj variable is storing a text string, not a JSON object. Exploring further down the call stack, click onload in the Call Stack section. The view will update to show the request.onload function in the center panel, and its scopes in the Scopes section. If you expan...
... if("geolocation" in navigator) { navigator.geolocation.getCurrentPosition(function(position) { // show the location on a map, perhaps using the Google Maps API }); } else { // Give the user a choice of static maps instead perhaps } You could also write such a test for a CSS feature, for example by testing for the existence of element.style.property (e.g. paragraph.style.transform !==
undefined). But for both CSS and JavaScript, it is probably better to use an established feature detection library rather than writing your own all the time. Modernizr is the industry standard for feature detection tests. As a last point, don't confuse feature detection with browser sniffing (detecting what specific browser is accessing the site) -- this is a terrible practice that should be discouraged a...
Building SpiderMonkey with UBSan
1. Compile a recent version of LLVM & Clang. 2. Save the following bash script, fixing LLVM_ROOT to point to your installation. #! /bin/sh if [ -z $1 ] ; then echo "usage: $0 <dirname>" elif [ -d $1 ] ; then echo "directory $1 already exists" else autoconf2.13 autoconf213 mkdir $1 cd $1 LLVM_ROOT="$HOME/llvm" SANFLAG="-fsanitize=
undefined -fno-sanitize=alignment,float-cast-overflow,float-divide-by-zero,vptr -Dxmalloc=myxmalloc" \ CC="$LLVM_ROOT/build/Release+Asserts/bin/clang" \ CXX="$LLVM_ROOT/build/Release+Asserts/bin/clang++" \ CFLAGS="$SANFLAG" \ CXXFLAGS="$SANFLAG" \ MOZ_LLVM_HACKS=1 \ ../configure --enable-debug --disable-optimize make -j 8 fi 3. Use the script to compile SpiderMonkey. This enables all the cheap unde...
...serts/bin/clang++" \ CFLAGS="$SANFLAG" \ CXXFLAGS="$SANFLAG" \ MOZ_LLVM_HACKS=1 \ ../configure --enable-debug --disable-optimize make -j 8 fi 3. Use the script to compile SpiderMonkey. This enables all the cheap
undefined behavior checks other than: alignment, which hits known bugs in SpiderMonkey, and is more implementation-defined (slow on x86 / crash on ARM) than
undefined behavior float-cast-overflow, which hits known bugs in SpiderMonkey, and isn't exploited by today's compilers float-divide-by-zero, which Jesse doesn't think is actually
undefined behavior (aside from the question of whether CPU overflow flags are set) vptr, a check that requires RTTI, which is disabled by default in SpiderMonkey 4. When you hit a bug and want a stack trace, run under gdb ...
...res RTTI, which is disabled by default in SpiderMonkey 4. When you hit a bug and want a stack trace, run under gdb with a breakpoint at the end of __ubsan::Diag::~Diag(). The stack trace should show a function such as __ubsan_handle_load_invalid_value or __ubsan_handle_type_mismatch being called by the buggy C++ code. (For automated testing outside of gdb, you can instead build with -fsanitize=
undefined-trap -fsanitize-
undefined-trap-on-error, but then you lose UBSan's diagnostics and the ability to continue past errors.) Known bugs. Please file new bugs with e.g. [-fsanitize=float-cast-overflow] in the status whiteboard. ...
JNI.jsm
ing ReadString( aJenv, aJavaString ); Parameters aJenv The return value of GetForThread(). aJavaString A CData object that is a Java string. Return Value A Javascript String. UnloadClasses() blah blah void UnloadClasses(); Parameters This function takes no arguments. Return value This function has no return value, if you try to store the return value in a variable, it will be
undefined. Working with arrays Creating/preallocating a typed array Methods CData .get(Number aIndex); CData .getElements(Number aStart, Number aLength); void .set(Number aIndex, CData aValue); void .setElements(Number aStart, [array, size_is(arr.length > Number anyNumber > 0)] in CData aValsArray); .get() Gets the value of the element in the array at given...
...Data array is returned. Return value A new CData array object based on the array. .set() Sets an element in the array at given aIndex to the given aVal. void set(Number aIndex, CData aVal); Parameters aIndex The position in the array to change. aVal A value to set it to. Return value This function has no return value, if you try to store the return value in a variable, it will be
undefined. .setElements() Sets a section of a typed array to specified values. This function starts on the position of aStart in the array and sets it to the values in aValsArray. This is done by calling .set for each element with the respective value in the aValsArray. void setElements(Number aStart, [array, size_is(arr.length > Number anyNumber > 0)] in CData aValsArray); Parameters aStart The p...
...the respective value in the aValsArray. void setElements(Number aStart, [array, size_is(arr.length > Number anyNumber > 0)] in CData aValsArray); Parameters aStart The position to start setting elements of the array in. aValsArray A Javascript array holding the values to set. Return value This function has no return value, if you try to store the return value in a variable, it will be
undefined. Attributes Attribute Type Description length Number The number of elements in the array Demonstration var my_jenv = null; try { my_jenv = JNI.GetForThread(); var SIG = { String: 'Ljava/lang/String;', int: 'I' }; JNI.LoadClass(my_jenv, '[' + SIG.String); var StringArray = JNI.classes.java.lang.String.array; // Object { ...
Examples
se { console.log("You don't have file.txt in your temporary directory."); } }); // Unexpected errors should always be reported at the end of a promise chain. let lastPromise = newPromise.then(null, Components.utils.reportError); In this case, if the file existence check succeeds, the onFulfill callback is invoked. When the callback finishes execution, newPromise will be fulfilled with an
undefined fulfillment value, because the callback does not return any value. When newPromise is fulfilled, nothing happens, because no fulfillment callback is specified and the return value of the last then method is ignored. If the file existence check fails, for example because access is denied, promise is rejected with an OS.File.Error instance. This state will propagate to newPomise, and Components.ut...
...on in pareallel, how return when last done? Simple Example User Defined Promise Function 2 Whenever you want to make a function a promise. Always wrap that function in a try catch and make that catch return Promise.reject(ex) otherwise it will not trigger the rejection function of the promise.then. This way if any error happens it will reject the promise. In the example below we try alerting an
undefined variable. Components.utils.import("resource://gre/modules/Promise.jsm"); var myPromise = myUserDefinedPromise(); myPromise.then( function(aSuccessReason) { alert('myPromise was SUCCESFUL and reason was = "' + aSuccessReason + '"'); }, function(aRejectReason) { alert('myPromise FAILED for reason = "' + uneval(aRejectReason) + '"'); } ); function myUserDefinedPromise() { try { ...
...uncommet the var 2 lines above to see the promise succesfully return } catch(ex...
Promise.jsm
ect representing a value that may not be available yet. Internally, a promise can be in one of three states: Pending, when the final value is not available yet. This is the only state that may transition to one of the other two states. Fulfilled, when and if the final value becomes available. A fulfillment value becomes permanently associated with the promise. This may be any value, including
undefined. Rejected, if an error prevented the final value from being determined. A rejection reason becomes permanently associated with the promise. This may be any value, including
undefined, though it is generally an Error object, like in exception handling. A reference to an existing promise may be received by different means, for example as the return value of a call into an asynchronous API. In th...
...bject, containing the new promise in the promise property, and the methods to change its state in the resolve and reject properties. See the Deferred documentation for details. resolve() Creates a new promise fulfilled with the specified value, or propagates the state of an existing promise. Promise resolve( aValue ); Parameters aValue Optional If this value is not a promise, including
undefined, it becomes the fulfillment value of the returned promise. If this value is a promise, then the returned promise will be resolved with the value, i.e. it will eventually assume the same state as the provided promise. Return value A promise that can be pending, fulfilled, or rejected. reject() Creates a new promise rejected with the specified reason. Promise reject( aReason ); Parameters...
...eturned promise will be resolved with the value, i.e. it will eventually assume the same state as the provided promise. Return value A promise that can be pending, fulfilled, or rejected. reject() Creates a new promise rejected with the specified reason. Promise reject( aReason ); Parameters aReason Optional The rejection reason for the returned promise. Although the reason can be
undefined, it is generally an Error object, like in exception handling. Note: This argument should not be a promise. Specifying a rejected promise would make the rejection reason equal to the rejected promise itself, and not its rejection reason. Return value A rejected promise. Examples See the examples page. ...
nsIContentPrefService2
ence. If no such preferences exist, handleResult is not called at all. getCachedByDomainAndName() Synchronously retrieves from the in-memory cache the preference with the given domain and name. In addition to caching preference values, the cache also keeps track of preferences that are known not to exist. If the preference is known not to exist, the value attribute of the returned object will be
undefined (nsIDataType.VTYPE_VOID()). If the preference is neither cached nor known not to exist, then null is returned, and get() must be called to determine whether the preference exists. nsIContentPref getCachedByDomainAndName( in AString domain, in AString name, in nsILoadContext context ); Parameters domain The preference's domain. name The preference's name. ...
...mory cache all preferences with the given name whose domains are either the same as or subdomains of the given domain. The preferences are returned in an array through the out-parameter. If a preference for a particular subdomain is known not to exist, then an object corresponding to that preference will be present in the array, and, as with getCachedByDomainAndName(), its value attribute will be
undefined. void getCachedBySubdomainAndName( in AString domain, in AString name, in nsILoadContext context, out unsigned long len, [retval,array,size_is(len)] out nsIContentPref prefs ); Parameters domain The preferences' domain. name The preferences' name. context The private-browsing context, if any. len The length of the returned array.
.... len The length of the returned array. prefs The array of preferences. getCachedGlobal() Synchronously retrieves from the in-memory cache the preference with no domain and the given name. As with getCachedByDomainAndName(), if the preference is cached then it is returned; if the preference is known not to exist, then the value attribute of the returned object will be
undefined; if the preference is neither cached nor known not to exist, then null is returned. nsIContentPref getCachedGlobal( in AString name, in nsILoadContext context ); Parameters name The preference's name. context The private-browsing context, if any. Return value The preference, or null if no such preference is known to exist. getGlobal() Gets the preference with no...
nsIHttpServer
*/ void start(in long port); /** * Shuts down this server if it is running (including the period of time after * stop() has been called but before the provided callback has been called). * * @param callback * an asynchronous callback used ...
... a user-defined error * handler if one exists or the server default handler otherwise. Fallback * will never occur from a user-provided handler that throws to the same * handler as provided by the server, e.g. a throwing user 404 falls back to * 400, not a server-provided 404 that might not throw. * @note * If the error handler handles HTTP 500 and throws, behavior is
undefined. */ void registerErrorHandler(in unsigned long code, in nsIHttpRequestHandler handler); /** * Maps all requests to paths beneath path to the corresponding file beneath * dir. * * @param path * the absolute path on the server against which requests will be served * from dir (e.g., "/", "/foo/", etc.); must begin and end with a forward * slash * @param dir *...
... * * @throws NS_ERROR_INVALID_ARG * if the given type is not a valid header field value, i.e. if it doesn't * match the field-value production in RFC 2616 * @note * No syntax checking is done of the given type, beyond ensuring that it is * a valid header field value. Behavior when not given a string matching * the media-type production in RFC 2616 section 3.7 is
undefined. * Implementations may choose to define specific behavior for types which do * not match the production, such as for CGI functionality. * @note * Implementations MAY treat type as a trusted argument; users who fail to * generate this string from trusted data risk security vulnerabilities. */ void registerContentType(in string extension, in string type); /** * Set...
Working with data
ts. Creating uninitialized CData objects There are three forms of the syntax for creating CData objects without immediately assigning them a value: var myCDataObj = new type; var myCDataObj = new type(); var myCDataObj = type(); These all do the same thing: they return a new CData object of the specified type, whose data buffer has been populated entirely with zeroes. ...
...If the conversion isn't possible, TypeError is thrown. The resulting data is then copied into a new CData object. If the original value is already a CData object, the original object is simply duplicated directly into the new one. ...
...sArr)` myCArr.addressOfElement(0).contents; // outputs: 4 myCArr.addressOfElement(1).contents; // outputs: 10 Type casting You can type cast data from one type to another by using the ctypes.cast() function: var newObj = ctypes.cast(origObj, newType); This will return a new object whose data block is shared with the original object, but whose type is newType. If the size of the new type is
undefined or larger than the size of the original object's data block, TypeError is thrown. This works very much like a standard C type cast or C++ reinterpret_cast. Example: Cast an array This example shows how to cast an array of a certain type to another type. // lets create an array of long's var my = ctypes.long.array()([1, 2, 3, 4]); my.toString(); // this outputs to browser console: `"ctypes.lon...
ArrayType
elements or variable which is going to be present in an array length Optional It denotes the number of entries present in an array or the number of elements that an array should contain. If you don't specify this parameter, the array's length is unspecified. Return value A CType represents the newly declared array type. Exceptions thrown TypeError type is not a CType, or type.size is
undefined.If the length is specifed but if it is not a valid one,then it is also thrown RangeError The size of the resulting array can't be represented as both a size_t and as a JavaScript number. Properties Property Type Description elementType CType The data type of the elements in an array type. Read only. length Number The number of elements in the arr...
... length is specifed but if it is not a valid one,then it is also thrown RangeError The size of the resulting array can't be represented as both a size_t and as a JavaScript number. Properties Property Type Description elementType CType The data type of the elements in an array type. Read only. length Number The number of elements in the array, or
undefined if the array type doesn't have a specified length. Read only. Properties inherited from CType These properties are available on all CType objects. Property Type Description name String The type's name. Read only. For primitive types, this is just the name of the corresponding C type. For structure and opaque pointer types, this is simply the string...
... other function, pointer, and array types, this should be a valid C type expression. ptr CType Returns a CType representing the data type "pointer to this type". This is the result of calling ctypes.PointerType(the_type). Read only. size Number The size of the type, in bytes. This is the same value as the C sizeof. Read only. Note: ctypes.void_t.size is
undefined. Method overview Methods inherited from CType CType array([n]) String toSource() String toString() ArrayType CData Syntax CData sized_arraytype(); CData unsized_arraytype(length); sized_arraytype and unsized_arraytype are ArrayType CType. Parameters length The number of entries the array type should be able to contain. Only for unsized ArrayT...
Using the CSS Typed Object Model - Web APIs
We didn't declare a width or a height for the paragraph, both of which default to auto and therefore return a CSSKeywordValue instead of a CSSUnitValue. CSSKeywordValues do not have a uni...
... We didn't declare a width or a height for the paragraph, both of which default to auto and therefore return a CSSKeywordValue instead of a CSSUnitValue. CSSKeywordValues do not have a unit property, so in these cases our get...
...ote the <length> unit returned is px, the <percentage> unit returned is percent, the <time> unit is s for 'seconds', and the unitless <number> unit is number. We didn't declare a width or a height for the paragraph, both of which default to auto and therefore return a CSSKeywordValue instead of a CSSUnitValue. CSSKeywordValues do not have a unit property, so in these cases our get().unit returns
undefined. Had the width or height been defined in a <length> or <percent>, the CSSUnitValue unit would have been px or percent respectively. There are other types available: An <image> will return a CSSImageValue. A <color> would return a CSSStyleValue. A transform returns a CSSTransformValue. A custom property returns a CSSUnparsedValue. You can use a CSSUnitValue or CSSKeywordValue to create ...
CacheStorage.match() - Web APIs
You can access CacheStorage through the global caches property. Cache objects are searched in creation order. Note: caches.match() is a convenience method. Equivalent functionality is to call cache.match() on each cache (in the order returned by caches.keys()) until a Response is returned. ...
... VARY header matching. In other words, if the URL matches you will get a match regardless of whether the Response object has a VARY header or not. It defaults to false. cacheName: A DOMString that represents a specific cache to search within. Return value a Promise that resolves to the matching Response. If no matching response to the specified request is found, the promise resolves with
undefined. Examples This example is from the MDN sw-test example (see sw-test running live). Here we wait for a FetchEvent to fire. We construct a custom response like so: Check whether a match for the request is found in the CacheStorage using CacheStorage.match(). If so, serve that. If not, open the v1 cache using open(), put the default network request in the cache using Cache.put() and return a c...
...esponse.clone(). The last is necessary because put() consumes the response body. If this fails (e.g., because the network is down), return a fallback response. ...
SpeechSynthesis.getVoices() - Web APIs
l the available voices on the current device. Syntax speechSynthesisInstance.getVoices(); Parameters None. Return value A list (array) of SpeechSynthesisVoice objects. Note: The spec wrongly lists this method as returning as a SpeechSynthesisVoiceList object, but this was in fact removed from the spec. ...
... Draft Initial definition ...
... Draft Initial definition ...
Using readable streams - Web APIs
ect -- this has the results of our read in it, in the form { done, value }: return reader.read().then(({ done, value }) => { The results can be one of three different types: If a chunk is available to read, the promise will be fulfilled with an object of the form { value: theChunk, done: false }. ...
...o read, the promise will be fulfilled with an object of the form { value: theChunk, done: false }. If the stream becomes closed, the promise will be fulfilled with an object of the form { value:
undefined, done: true }. If the stream becomes errored, the promise will be rejected with the relevant error. Next, we check whether done is true. If so, there are no more chunks to read (the value is
undefined) so we return out of the function and close the custom stream with ReadableStreamDefaultController.close(): if (done) { controller.close(); return; } Note: close() is part of the new custom stream, not the original stream we are discussing here. We'll explain more about the custom stream in the next section. If done is not true, we process the new chunk we've read (contained in the value...
... read() method again. function readStream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always
undefined when done is true. if (done) { console.log("Stream complete"); para.textContent = result; return; } charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Read ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list2.appendChild(listItem); result += chunk; //...
Classes - JavaScript
heir class and cannot be called through a class instance. Static methods are often used to create utility functions for an application. class Point { constructor(x, y) { this.x = x; this.y = y; } static distance(a, b) { const dx = a.x - b.x; const dy = a.y - b.y; return Math.hypot(dx, dy); } } const p1 = new Point(5, 5); const p2 = new Point(10, 10); p1.distance; //
undefined p2.distance; //
undefined console.log(Point.distance(p1, p2)); // 7.0710678118654755 Binding this with prototype and static methods When a static or prototype method is called without a value for this, such as by assigning a variable to the method and then calling it, the this value will be
undefined inside the method. This behavior will be the same even if the "use strict" directive isn't pre...
...In strict mode, autobinding will not happen; the value of this remains as passed. ...
...ame even if the "use strict" directive isn't present, because code within the class body's syntactic boundary is always executed in strict mode. class Animal { speak() { return this; } static eat() { return this; } } let obj = new Animal(); obj.speak(); // the Animal object let speak = obj.speak; speak(); //
undefined Animal.eat() // class Animal let eat = Animal.eat; eat(); //
undefined If we rewrite the above using traditional function-based syntax in non-strict mode, then this method calls is automatically bound to the initial this value, which by default is the global object. In strict mode, autobinding will not happen; the value of this remains as passed. function Animal() { } Animal.prototype.speak = function() { return this; } Animal.eat = function() { return this;...
Functions - JavaScript
n on properties and methods of Function objects. To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is
undefined. The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as s...
... "a,b". functionBody A string containing the JavaScript statements comprising the function definition. Invoking the GeneratorFunction constructor as a function (without using the new operator) has the same effect as invoking it as a constructor. Function parameters Default parameters Default function parameters allow formal parameters to be initialized with default values if no value or
undefined is passed. For more details, see default parameters. Rest parameters The rest parameter syntax allows representing an indefinite number of arguments as an array. For more details, see rest parameters. The arguments object You can refer to a function's arguments within the function by using the arguments object. See arguments. arguments: An array-like object containing the arguments passed ...
... do approximately the same thing, with a few subtle differences: There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or
undefined if the function name was previously declared via a var statement). For example: var y = function x() {}; alert(x); // throws an error The function name also appears when the function is serialized via Function's toString method. On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function is declared. ...
Array.prototype.every() - JavaScript
s invoked only for array indexes which have assigned values. It is not invoked for indexes which have been deleted, or which have never been assigned values. callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed. If a thisArg parameter is provided to every, it will be used as callback's this value. Otherwise, the value
undefined will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. every does not mutate the array on which it is called. The range of elements processed by every is set before the first invocation of callback. Therefore, callback will not run on elements that are appended to the array after t...
... of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If IsCallable(callbackfn) is false, throw a TypeError exception. if (typeof callbackfn !== 'function' && Object.prototype.toString.call(callbackfn) !== '[object Function]') { throw new TypeError(); } // 5. If thisArg was supplied, let T be thisArg; else let T be
undefined. if (arguments.length > 1) { T = thisArg; } // 6. Let k be 0. k = 0; // 7. Repeat, while k < len while (k < len) { var kValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal // method of O with argument Pk. // This ...
... // This step can be combined with c // c. If kPresent is true, then if (k in O) { var testResult; // i. Let kValue be the result of calling the Get internal method // of O with argument Pk. kValue = O[k]; // ii. Let testResult be the result of calling the Call internal method // of callbackfn with T as the this value if T is not
undefined // else is the result of calling callbackfn // and argument list containing kValue, k, and O. if(T) testResult = callbackfn.call(T, kValue, k, O); else testResult = callbackfn(kValue,k,O) // iii. If ToBoolean(testResult) is false, return false. if (!testResult) { return false; } } k++; } return true; }; } E...
Array.prototype.filter() - JavaScript
d or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array. callback is invoked with three arguments: the value of the element the index of the element the Array object being traversed If a thisArg parameter is provided to filter, it will be used as the callback's this value. Otherwise, the value
undefined will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. filter() does not mutate the array on which it is called. The range of elements processed by filter() is set before the first invocation of callback. Elements which are appended to the array (from callback) after the call to fil...
...ush() has its original value. ...
...num % i == 0) { return false; } } return num > 1; } console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13] Filtering invalid entries from JSON The following example uses filter() to create a filtered json of all elements with non-zero, numeric id. ...
Array.prototype.indexOf() - JavaScript
present in all browsers. You can work around this by utilizing the following code at the beginning of your scripts. This will allow you to use indexOf() when there is still no native support. This algorithm matches the one specified in ECMA-262, 5th edition, assuming TypeError and Math.abs() have their original values. ...
...imize by only checking for "in" when looking for
undefined and // skipping the definitely fruitless NaN search. Other parts are merely cosmetic conciseness. // Whether it is actually faster remains to be seen. ...
... definitely fruitless NaN search. Other parts are merely cosmetic conciseness. // Whether it is actually faster remains to be seen. if (!Array.prototype.indexOf) Array.prototype.indexOf = (function(Object, max, min) { "use strict" return function indexOf(member, fromIndex) { if (this === null || this ===
undefined) throw TypeError("Array.prototype.indexOf called on null or
undefined") var that = Object(this), Len = that.length >>> 0, i = min(fromIndex | 0, Len) if (i < 0) i = max(0, Len + i) else if (i >= Len) return -1 if (member === void 0) { //
undefined for (; i !== Len; ++i) if (that[i] === void 0 && i in that) return i } else if (member !== member) { // NaN return -1 // Since NaN !== NaN, it will never be found. Fa...
Array.prototype.sort() - JavaScript
fines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. firstEl The first element for comparison. secondEl The second element for comparison. Return value The sorted array. Note that the array is sorted in place, and no copy is made. Description If compareFunction is not supplied, all non-
undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All
undefined elements are sorted to the end of the array. Note : In UTF-16, Unicode characters above \uFFFF are encod...
...fined elements are sorted to the end of the array. Note : In UTF-16, Unicode characters above \uFFFF are encoded as two surrogate code units, of the range \uD800-\uDFFF. The value of each code unit is taken separately into account for the comparison. Thus the character formed by the surrogate pair \uD655\uDE55 will be sorted before the character \uFF3A. If compareFunction is supplied, all non-
undefined array elements are sorted according to the return value of the compare function (all
undefined elements are sorted to the end of the array, with no call to compareFunction). If a and b are two elements being compared, then: If compareFunction(a, b) returns less than 0, sort a to an index lower than b (i.e. a comes first). If compareFunction(a, b) returns 0, leave a and b unchanged with respec...
...tee this behavior, thus, not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this. If compareFunction(a, b) returns greater than 0, sort b to an index lower than a (i.e. b comes first). compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned, then the sort order is
undefined. So, the compare function has the following form: function compare(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; } To compare numbers instead of strings, the compare function can simply subtract b from a. The following function will sort the array i...
Array - JavaScript
.log(removedItems) // ["Turnip", "Radish"] Copy an Array let shallowCopy = fruits.slice() // this is how to make a copy // ["Strawberry", "Mango"] Accessing array elements JavaScript arrays are zero-indexed. The first element of an array is at index 0, and the last element is at the index value equal to the value of the array's length property minus 1. Using an invalid index number returns
undefined. let arr = ['this is the first element', 'this is the second element', 'this is the last element'] console.log(arr[0]) // logs 'this is the first element' console.log(arr[1]) // logs 'this is the second element' console.log(arr[arr.length - 1]) // logs 'this is the last element' Array elements are object properties in the same way that toString is a property (to be sp...
...its[5]) // 'mango' console.log(Object.keys(fruits)) // ['0', '1', '2', '5'] console.log(fruits.length) // 6 Increasing the length. fruits.length = 10 console.log(fruits) // ['banana', 'apple', 'peach', empty x 2, 'mango', empty x 4] console.log(Object.keys(fruits)) // ['0', '1', '2', '5'] console.log(fruits.length) // 10 console.log(fruits[8]) //
undefined Decreasing the length property does, however, delete elements. fruits.length = 2 console.log(Object.keys(fruits)) // ['0', '1'] console.log(fruits.length) // 2 This is explained further on the Array.length page. Creating an array using the result of a match The result of a match between a RegExp and a string can create a JavaScript array. This array has properties and elements which ...
...ction. Array.prototype.fill() Fills all the elements of an array from a start index to an end index with a static value. Array.prototype.filter() Returns a new array containing all elements of the calling array for which the provided filtering function returns true. Array.prototype.find() Returns the found element in the array, if some element in the array satisfies the testing function, or
undefined if not found. Array.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the testing function, or -1 if not found. Array.prototype.forEach() Calls a function for each element in the array. Array.prototype.includes() Determines whether the array contains a value, returning true or false as appropriate. Array.prototype.indexOf() Returns the first ...
Map.prototype.forEach() - JavaScript
orEach(callback([value][,key][,map])[, thisArg]) Parameters callback Function to execute for each entry of myMap. It takes the following arguments: value Optional Value of each iteration. key Optional Key of each iteration. map Optional The map being iterated (myMap in the above Syntax box). thisArg Optional Value to use as this when executing callback. Return value
undefined. Description The forEach method executes the provided callback once for each key of the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value
undefined. callback is invoked with three arguments: the entry's value the entry's key the Map object being traversed If a thisArg parameter is provide...
... The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. ...
... forEach has finished will be visited. forEach executes the callback function once for each element in the Map object. It does not return a value. Examples Printing the contents of a Map object The following code logs a line for each element in an Map object: function logMapElements(value, key, map) { console.log(`map.get('${key}') = ${value}`) } new Map([['foo', 3], ['bar', {}], ['baz',
undefined]]).forEach(logMapElements) // logs: // "map.get('foo') = 3" // "map.get('bar') = [object Object]" // "map.get('baz') =
undefined" Specifications Specification ECMAScript (ECMA-262)The definition of 'Map.prototype.forEach' in that specification. ...
Object.defineProperties() - JavaScript
deleted from the corresponding object. Defaults to false. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults to false. A data descriptor also has the following optional keys: value The value associated with the property. Can be any valid JavaScript value (number, object, function, etc). Defaults to
undefined. ...
...e value associated with the property. Can be any valid JavaScript value (number, object, function, etc). Defaults to
undefined. writable true if and only if the value associated with the property may be changed with an assignment operator. Defaults to false. An accessor descriptor also has the following optional keys: get A function which serves as a getter for the property, or
undefined if there is no getter. The function's return value will be used as the value of the property. Defaults to
undefined. set A function which serves as a setter for the property, or
undefined if there is no setter. The function will receive as its only argument the new value being assigned to the property. Defaults to
undefined. If a descriptor has neither of value, writable, get and set ...
...sProperty(desc, 'enumerable')) d.enumerable = !!desc.enumerable; if (hasProperty(desc, 'configurable')) d.configurable = !!desc.configurable; if (hasProperty(desc, 'value')) d.value = desc.value; if (hasProperty(desc, 'writable')) d.writable = !!desc.writable; if (hasProperty(desc, 'get')) { var g = desc.get; if (!isCallable(g) && typeof g !== '
undefined') throw new TypeError('bad get'); d.get = g; } if (hasProperty(desc, 'set')) { var s = desc.set; if (!isCallable(s) && typeof s !== '
undefined') throw new TypeError('bad set'); d.set = s; } if (('get' in d || 'set' in d) && ('value' in d || 'writable' in d)) throw new TypeError('identity-confused descriptor'); return d; } if...
Object.getOwnPropertyDescriptor() - JavaScript
nteractive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Object.getOwnPropertyDescriptor(obj, prop) Parameters obj The object in which to look for the property. prop The name or Symbol of the property whose description is to be retrieved. Return value A property descriptor of the given property if it exists on the object,
undefined otherwise. Description This method permits examination of the precise description of a property. A property in JavaScript consists of either a string-valued name or a Symbol and a property descriptor. Further information about property descriptor types and their attributes can be found in Object.defineProperty(). A property descriptor is a record with some of the following attributes: value...
...descriptor types and their attributes can be found in Object.defineProperty(). A property descriptor is a record with some of the following attributes: value The value associated with the property (data descriptors only). writable true if and only if the value associated with the property may be changed (data descriptors only). get A function which serves as a getter for the property, or
undefined if there is no getter (accessor descriptors only). set A function which serves as a setter for the property, or
undefined if there is no setter (accessor descriptors only). configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. enumerable true if and only if this property shows up during enumerat...
... from the corresponding object. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. ...
Promise.prototype.then() - JavaScript
he respective handler function (onFulfilled or onRejected) will be called asynchronously (scheduled in the current thread loop). The behavior of the handler function follows a specific set of rules. If a handler function: returns a value, the promise returned by then gets resolved with the returned value as its value. doesn't return anything, the promise returned by then gets resolved with an
undefined value. throws an error, the promise returned by then gets rejected with the thrown error as its value. returns an already fulfilled promise, the promise returned by then gets fulfilled with that promise's value as its value. returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value. returns another pending promise object, the resolu...
...d after the end of the main stack. the value received and returned is: " + value); return value; }); // instantly logging the value of thenProm console.log(thenProm); // using setTimeout we can postpone the execution of a function to the moment the stack is empty setTimeout(() => { console.log(thenProm); }); // logs, in order: // Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]:
undefined} // "this gets called after the end of the main stack. the value received and returned is: 33" // Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: 33} Description As the then and Promise.prototype.catch() methods return promises, they can be chained -- an operation called composition. Examples Using the then method var p1 = new Promise((resolve, reject) => { resolve('Success!'); ...
...d polyfill Using a Function.prototype.bind() Reflect.apply (Reflect.apply()) method to create a (non-cancellable) window.setImmediate-style function. const nextTick = (() => { const noop = () => {}; // literally const nextTickPromise = () => Promise.resolve().then(noop); const rfab = Reflect.apply.bind; // (thisArg, fn, thisArg, [...args]) const nextTick = (fn, ...args) => ( fn !==
undefined ? Promise.resolve(args).then(rfab(null, fn, null)) : nextTickPromise(),
undefined ); nextTick.ntp = nextTickPromise; return nextTick; })(); Specifications Specification ECMAScript (ECMA-262)The definition of 'Promise.prototype.then' in that specification. ...
Reflect.getOwnPropertyDescriptor() - JavaScript
The static Reflect.getOwnPropertyDescriptor() method is similar to Object.getOwnPropertyDescriptor(). It returns a property descriptor of the given property if it exists on the object,
undefined otherwise. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Reflect.getOwnPropertyDescriptor(target, propertyKey) Parameters target The target object in which to look for the property. propertyKey The name of the property to get an own property descriptor for. Return value A property descriptor object if the property exists in target object; otherwise,
undefined. Exceptions A TypeError, if target is not an Obj...
... the property. propertyKey The name of the property to get an own property descriptor for. Return value A property descriptor object if the property exists in target object; otherwise,
undefined. Exceptions A TypeError, if target is not an Object. Description The Reflect.getOwnPropertyDescriptor method returns a property descriptor of the given property if it exists in the target object,
undefined otherwise. The only difference to Object.getOwnPropertyDescriptor() is how non-object targets are handled. ...
...ven property if it exists in the target object,
undefined otherwise. The only difference to Object.getOwnPropertyDescriptor() is how non-object targets are handled. Examples Using Reflect.getOwnPropertyDescriptor() Reflect.getOwnPropertyDescriptor({x: 'hello'}, 'x') // {value: "hello", writable: true, enumerable: true, configurable: true} Reflect.getOwnPropertyDescriptor({x: 'hello'}, 'y') //
undefined Reflect.getOwnPropertyDescriptor([], 'length') // {value: 0, writable: true, enumerable: false, configurable: false} Difference to Object.getOwnPropertyDescriptor() If the target argument to this method is not an object (a primitive), then it will cause a TypeError. With Object.getOwnPropertyDescriptor, a non-object first argument will be coerced to an object at first. Reflect.getOwnProperty...
RegExp - JavaScript
and no more match. With the global flag g, all 6 digits would be matched, not just 3. Regular expression and Unicode characters \w and \W only matches ASCII based characters; for example, a to z, A to Z, 0 to 9, ...
...and no more match. With the global flag g, all 6 digits would be matched, not just 3. Regular expression and Unicode characters \w and \W only matches ASCII based characters; for example, a to z, A to Z, 0 to 9, and _. To match characters from other languages such as Cyrillic or Hebrew, ...
...and no more match. With the global flag g, all 6 digits would be matched, not just 3. ...
Set.prototype.forEach() - JavaScript
t.forEach(callback[, thisArg]) Parameters callback Function to execute for each element, taking three arguments: currentValue, currentKey The current element being processed in the Set. As there are no keys in Set, the value is passed for both arguments. set The Set object which forEach() was called upon. thisArg Value to use as this when executing callback. Return value
undefined. Description The forEach() method executes the provided callback once for each value which actually exists in the Set object. It is not invoked for values which have been deleted. However, it is executed for values which are present but have the value
undefined. callback is invoked with three arguments: the element value the element key the Set object being traversed There are no keys i...
... the element value the element key the Set object being traversed There are no keys in Set objects, however, so the first two arguments are both values contained in the Set. This is to make it consistent with other forEach() methods for Map and Array. If a thisArg parameter is provided to forEach(), it will be passed to callback when invoked, for use as its this value. Otherwise, the value
undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. Each value is visited once, except in the case when it was deleted and re-added before forEach() has finished. callback is not invoked for values deleted before being visited. New values added before forEach() has fini...
...ded before forEach() has finished will be visited. forEach() executes the callback function once for each element in the Set object; it does not return a value. Examples Logging the contents of a Set object The following code logs a line for each element in a Set object: function logSetElements(value1, value2, set) { console.log('s[' + value1 + '] = ' + value2); } new Set(['foo', 'bar',
undefined]).forEach(logSetElements); // logs: // "s[foo] = foo" // "s[bar] = bar" // "s[
undefined] =
undefined" Specifications Specification ECMAScript (ECMA-262)The definition of 'Set.prototype.forEach' in that specification. ...
TypedArray.prototype.findIndex() - JavaScript
have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. callback is invoked with three arguments: the value of the element, the index of the element, and the typed array object being traversed. If a thisArg parameter is provided to findIndex, it will be used as the this for each invocation of the callback. If it is not provided, then
undefined is used. findIndex does not mutate the typed array on which it is called. The range of elements processed by findIndex is set before the first invocation of callback. Elements that are appended to the typed array after the call to findIndex begins will not be visited by callback. If an existing, unvisited element of the typed array is changed by callback, its value passed to the visiting callba...
...alue passed to the visiting callback will be the value at the time that findIndex visits that element's index; elements that are deleted are not visited. ...
... if (typeof(evaluator) !== 'function') { if (typeof(evaluator) === 'string') { // Attempt to convert it to a function if ( ! ...
TypedArray.prototype.forEach() - JavaScript
, thisArg]) Parameters callback Function that produces an element of the new typed array, taking three arguments: currentValue The current element being processed in the typed array. index The index of the current element being processed in the array. array The array forEach() was called upon. thisArg Optional. Value to use as this when executing callback. Return value
undefined. Description The forEach() method executes the provided callback once for each element present in the typed array in ascending order. It is not invoked for indexes that have been deleted or elided. However, it is executed for elements that are present and have the value
undefined. callback is invoked with three arguments: the element value the element index the typed array being traversed...
...The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. ...
...l to forEach() begins will not be visited by callback. If the values of existing elements of the typed array are changed, the value passed to callback will be the value at the time forEach() visits them; elements that are deleted before being visited are not visited. forEach() executes the callback function once for each typed array element; unlike every() and some() it, always returns the value
undefined. Examples Logging the contents of a typed array The following code logs a line for each element in a typed array: function logArrayElements(element, index, array) { console.log('a[' + index + '] = ' + element); } new Uint8Array([0, 1, 2, 3]).forEach(logArrayElements); // logs: // a[0] = 0 // a[1] = 1 // a[2] = 2 // a[3] = 3 Specifications Specification ECMAScript (ECMA...
WeakMap() constructor - JavaScript
ly referenced. The keys must be objects and the values can be arbitrary values. You can learn more about WeakMaps in the section WeakMap object in Keyed collections. Syntax new WeakMap([iterable]) Parameters iterable Iterable is an Array or other iterable object whose elements are key-value pairs (2-element Arrays). Each key-value pair will be added to the new WeakMap. null is treated as
undefined. Examples Using WeakMap const wm1 = new WeakMap(), wm2 = new WeakMap(), wm3 = new WeakMap(); const o1 = {}, o2 = function() {}, o3 = window; wm1.set(o1, 37); wm1.set(o2, 'azerty'); wm2.set(o1, o2); // a value can be anything, including an object or a function wm2.set(o3,
undefined); wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps! wm1.get(o2);...
...const wm1 = new WeakMap(), wm2 = new WeakMap(), wm3 = new WeakMap(); const o1 = {}, o2 = function() {}, o3 = window; wm1.set(o1, 37); wm1.set(o2, 'azerty'); wm2.set(o1, o2); // a value can be anything, including an object or a function wm2.set(o3,
undefined); wm2.set(wm1, wm2); // keys and values can be any objects. ...
... new WeakMap(); const o1 = {}, o2 = function() {}, o3 = window; wm1.set(o1, 37); wm1.set(o2, 'azerty'); wm2.set(o1, o2); // a value can be anything, including an object or a function wm2.set(o3,
undefined); wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps! wm1.get(o2); // "azerty" wm2.get(o2); //
undefined, because there is no key for o2 on wm2 wm2.get(o3); //
undefined, because that is the set value wm1.has(o2); // true wm2.has(o2); // false wm2.has(o3); // true (even if the value itself is '
undefined') wm3.set(o1, 37); wm3.get(o1); // 37 wm1.has(o1); // true wm1.delete(o1); wm1.has(o1); // false Specifications Specification ECMAScript (ECMA-262)The definition of 'WeakMap constructor' in that specification. ...
WeakRef - JavaScript
e object and reclaim its memory. If that happens, you can't get the object from a weak reference anymore. Note: Please see the Avoid where possible section below. Correct use of WeakRef takes careful thought, and it's best avoided if possible. Constructor WeakRef() Creates a new WeakRef object. Instance methods WeakRef.prototype.deref() Returns the WeakRef object's target object, or
undefined if the target object has been reclaimed. Avoid where possible Correct use of WeakRef takes careful thought, and it's best avoided if possible. It's also important to avoid relying on any specific behaviors not guaranteed by the specification. When, how, and whether garbage collection occurs is down to the implementation of any given JavaScript engine. Any behavior you observe in one engine may...
...or's behavior changed. (Garbage collection is a hard problem; JavaScript engine implementers are constantly refining and improving how it works.) If multiple WeakRefs have the same target, they're consistent with one another. The result of calling deref on one of them will match the result of calling deref on another of them (in the same job), you won't get the target object from one of them but
undefined from another. If the target of a WeakRef is also in a FinalizationRegistry, the WeakRef's target is cleared at the same time or before any cleanup callback associated with the registry is called; if your cleanup callback calls deref on a WeakRef for the object, it will receive
undefined. You cannot change the target of a WeakRef, it will always only ever be the original target object or undefin...
...gistry, the WeakRef's target is cleared at the same time or before any cleanup callback associated with the registry is called; if your cleanup callback calls deref on a WeakRef for the object, it will receive
undefined. You cannot change the target of a WeakRef, it will always only ever be the original target object or
undefined when that target has been reclaimed. A WeakRef might never return
undefined from deref, even if nothing strongly holds the target, because the garbage collector may never decide to reclaim the object. Examples Using a WeakRef object This example starts a counter shown in a DOM element, stopping when the element doesn't exist anymore: class Counter { constructor(element) { // Remember a weak reference to the DOM element this.ref = new WeakRef(element); ...
eval() - JavaScript
s project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax eval(string) Parameters string A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. Return value The completion value of evaluating the given code. If the completion value is empty,
undefined is returned. Description eval() is a function property of the global object. The argument of the eval() function is a string. If the string represents an expression, eval() evaluates the expression. If the argument represents one or more JavaScript statements, eval() evaluates the statements. Do not call eval() to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions a...
...at the code being evaluated doesn't have access to local variables within the scope where it's being called. function test() { var x = 2, y = 4; console.log(eval('x + y')); // Direct call, uses local scope, result is 6 var geval = eval; // equivalent to calling eval in the global scope console.log(geval('x + y')); // Indirect call, uses global scope, throws ReferenceError because `x` is
undefined (0, eval)('x + y'); // another example of Indirect call } Never use eval()! eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, a third-pa...
... expression evaluated. var str = 'if ( a ) { 1 + 1; } else { 1 + 2; }'; var a = true; var b = eval(str); // returns 2 console.log('b is : ' + b); a = false; b = eval(str); // returns 3 console.log('b is : ' + b); eval as a string defining function requires "(" and ")" as prefix and suffix var fctStr1 = 'function a() {}' var fctStr2 = '(function a() {})' var fct1 = eval(fctStr1) // return
undefined var fct2 = eval(fctStr2) // return a function Specifications Specification ECMAScript (ECMA-262)The definition of 'eval' in that specification. ...
in operator - JavaScript
in mycar // returns true You must specify an object on the right side of the in operator. For example, you can specify a string created with the String constructor, but you cannot specify a string literal. ...
...2 Using in with deleted or
undefined properties If you delete a property with the delete operator, the in operator returns false for that property. let mycar = {make: 'Honda', model: 'Accord', year: 1998} delete mycar.make 'make' in mycar // returns false let trees = new Array('redwood', 'bay', 'cedar', 'oak', 'maple') delete trees[3] 3 in trees // returns false If you set a property to
undefined but do not delete it, the in operator returns true for that property. let mycar = {make: 'Honda', model: 'Accord', year: 1998} mycar.make =
undefined 'make' in mycar // returns true let trees = new Array('redwood', 'bay', 'cedar', 'oak', 'maple') trees[3] =
undefined 3 in trees // returns true The in operator will return false for empty array slots. Even if accessing it directly returns u...
... property. let mycar = {make: 'Honda', model: 'Accord', year: 1998} mycar.make =
undefined 'make' in mycar // returns true let trees = new Array('redwood', 'bay', 'cedar', 'oak', 'maple') trees[3] =
undefined 3 in trees // returns true The in operator will return false for empty array slots. Even if accessing it directly returns
undefined. let empties = new Array(3) empties[2] // returns
undefined 2 in empties // returns false To avoid this, make sure a new array is always filled with non-empty values or not write to indexes past the end of array. let empties = new Array(3).fill(
undefined) 2 in empties // returns true Inherited properties The in operator returns true for properties in the prototype chain. (If you want to check for only non-inherited properties, use Object.prototype...
yield - JavaScript
nerator function). The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax [rv] = yield [expression] expression Optional Defines the value to return from the generator function via the iterator protocol. If omitted,
undefined is returned instead. rv Optional Retrieves the optional value passed to the generator's next() method to resume its execution. Description The yield keyword pauses generator function execution and the value of the expression following the yield keyword is returned to the generator's caller. It can be thought of as a generator-based version of the return keyword. yield can only be called...
...e statement immediately after the yield. throw is used to throw an exception from the generator. This halts execution of the generator entirely, and execution resumes in the caller (as is normally the case when an exception is thrown). The end of the generator function is reached. In this case, execution of the generator ends and an IteratorResult is returned to the caller in which the value is
undefined and done is true. A return statement is reached. In this case, execution of the generator ends and an IteratorResult is returned to the caller in which the value is the value specified by the return statement and done is true. If an optional value is passed to the generator's next() method, that value becomes the value returned by the generator's current yield operation. Between the generator...
...t[i] } } Once a generator function is defined, it can be used by constructing an iterator as shown. let appleStore = countAppleSales() // Generator { } console.log(appleStore.next()) // { value: 3, done: false } console.log(appleStore.next()) // { value: 7, done: false } console.log(appleStore.next()) // { value: 5, done: false } console.log(appleStore.next()) // { value:
undefined, done: true } You can also send a value with next(value) into the generator. 'step' evaluates as a return value in this syntax [rv] = yield [expression] function* counter(value) { let step; while (true) { step = yield ++value; if (step) { value += step; } } } const generatorFunc = counter(0); console.log(generatorFunc.next().value); // 1 console.log(generatorFunc.next().va...
function* - JavaScript
ue is returned, it will be set as the value property of the object returned by the generator. Much like a return statement, an error is thrown inside the generator will make the generator finished -- unless caught within the generator's body. When a generator is finished, subsequent next() calls will not execute any of that generator's code, they will just return an object of this form: {value:
undefined, done: true}. Examples Simple example function* idMaker() { var index = 0; while (true) yield index++; } var gen = idMaker(); console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 console.log(gen.next().value); // 3 // ... Example with yield* function* anotherGenerator(i) { yield i + 1; yield i + 2; yield i + 3; } functio...
...'pretzel'); // 1 pretzel gen.next('california'); // 2 california gen.next('mayonnaise'); // 3 mayonnaise Return statement in a generator function* yieldAndReturn() { yield "Y"; return "R"; yield "unreachable"; } var gen = yieldAndReturn() console.log(gen.next()); // { value: "Y", done: false } console.log(gen.next()); // { value: "R", done: true } console.log(gen.next()); // { value:
undefined, done: true } Generator as an object property const someObj = { *generator () { yield 'a'; yield 'b'; } } const gen = someObj.generator() console.log(gen.next()); // { value: 'a', done: false } console.log(gen.next()); // { value: 'b', done: false } console.log(gen.next()); // { value:
undefined, done: true } Generator as an object method class Foo { *generator () { yiel...
...t()); // { value:
undefined, done: true } Generator as an object method class Foo { *generator () { yield 1; yield 2; yield 3; } } const f = new Foo (); const gen = f.generator(); console.log(gen.next()); // { value: 1, done: false } console.log(gen.next()); // { value: 2, done: false } console.log(gen.next()); // { value: 3, done: false } console.log(gen.next()); // { value:
undefined, done: true } Generator as a computed property class Foo { *[Symbol.iterator] () { yield 1; yield 2; } } const SomeObj = { *[Symbol.iterator] () { yield 'a'; yield 'b'; } } console.log(Array.from(new Foo)); // [ 1, 2 ] console.log(Array.from(SomeObj)); // [ 'a', 'b' ] Generators are not constructable function* f() {} var obj = new f; // throws "TypeError: f is not ...
StringView - Archive of obsolete content
Code() is mainly for internal use and generally is of little utility. putUTF8CharCode() Syntax StringView.putUTF8CharCode(typedArray, charCode, index) Description Write a single codepoint at the given position into a typed array. A single UTF-8-encoded codepoint can occupy many elements (up to six). This function will split it into the needed parts and will write them. Returns
undefined. Arguments typedArray (required) A typed array containing the UTF-8 encoded elements. charCode (required) A number expressing the Unicode representation of a character (codepoint). index (required) The location to be overwritten. Examples var myStringView = new StringView("Hello world!"); // an UTF-8 stringView... StringView.putUTF8CharCode(myStringView.rawD...
...nly for internal use and generally is of little utility. putUTF16CharCode() Syntax StringView.putUTF16CharCode(typedArray, charCode, index) Description Write a single codepoint at the given position into a typed array. A single UTF-16-encoded codepoint can occupy up to two UTF-16-encoded elements. This function will split it into the needed parts and will write them. Returns
undefined. Arguments typedArray (required) A typed array containing the UTF-16 encoded elements. charCode (required) A number expressing the Unicode representation of a character (codepoint). index (required) The location to be overwritten. Examples var myStringView = new StringView("Hello world!", "UTF-16"); // an UTF-16 stringView... StringView.putUTF16CharCode(mySt...
JavaScript Object Management - Archive of obsolete content
ile of its own, so that you have this one JS file that should be included in all of your XUL files. We'll be using the placeholder <Namespace> below. This needs to be replaced with an identifier name which is unique to your add-on. If your add-on is called Sergeant Pepper, for instance, then SgtPepper would be a good namespace name. /** * <Namespace> namespace. */ if (typeof <Namespace> == "
undefined") { var <Namespace> = {}; }; Note: The naming standard that we normally follow is that the first part of the namespace corresponds to the development group (or company), and the second to the specific project. However, most extensions are small projects by individuals, so these examples follow a more practical approach of having just one namespace with the project name. Notice how the ...
...ny namespace, since namespaces are just regular JS objects. That should come in handy when you have general utility functions or properties that you want to use across all objects within the namespace. For instance, there are frequently used XPCOM services such as the Observer service that can be included as members in the namespace: /** * <Namespace> namespace. */ if (typeof <Namespace> == "
undefined") { var <Namespace> = { /** * Initializes this object. */ init : function() { this.obsService = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService); } }; <Namespace>.init(); }; JS objects can also be treated as string-indexed arrays: // equivalent. <Namespace>.Hello = {}; <Namespace>["Hello"] = {}; // equivalent. <Namespace>...
Menu - Archive of obsolete content
in Jetpack contain Menuitem objects, including both built-in Firefox menus and menus that features create. No Menuitem constructor is exposed, because Jetpack automatically boxes simple JavaScript objects into Menuitem objects. Creating menuitems To pass a new menuitem into the API, pass one of the following types: null A simple menu separator. (Note that any falsey value will suffice, including
undefined, null, and the empty string. null is recommended because it stands out.) function A menuitem that will update itself when its menu is shown. The function is invoked just before the item's menu is shown and when the items array of the item's menu is retrieved. It must return a non-function menuitem. If the item belongs to a context menu, the function is called as function(context) and otherwise fu...
... defined, the menuitem expands into a submenu. mnemonic string A character that is used as the item's shortcut key while the menu is open. It should be one of the characters that appears in the item's label. On some platforms this character is underlined in the label. type string Currently only "separator" is supported. If this property is
undefined, the item is a normal menuitem. Note that when type == "separator", any other properties (such as label) may be specified. Fancy separators may behave differently on different platforms, however. xulId string The ID of the menuitem's backing XUL element, exposed for the benefit of advanced developers. Menu bar menus jetpack.menu When you need to expose functi...
appendNotification - Archive of obsolete content
just one event type: "removed". This indicates that the notification box has been removed from its window. Example: function testNotificationBoxWithButtons() { //Create some common variables if they do not exist. // This should work from any Firefox context. // Depending on the context in which the function is being run, // this could be simplified. ...
... this could be simplified. if (typeof window === "
undefined") { //If there is no window defined, get the most recent. ...
window - Archive of obsolete content
Related Elements prefwindow, dialog, dialogheader Related Topics User Notes To change the Icon to a window's title...
... Related Elements prefwindow, dialog, dialogheader Related Topics User Notes To change the Icon to a window's title bar check this page on Window icons. ...
Object.prototype.watch() - Archive of obsolete content
uch as window. You can usually use setters and getters or proxies instead. The watch() method watches for a property to be assigned a value and runs a function when that occurs. Syntax obj.watch(prop, handler) Parameters prop The name of a property of the object on which you wish to monitor changes. handler A function to call when the specified property's value changes. Return value
undefined. Description Watches for assignment to a property named prop in this object, calling handler(prop, oldval, newval) whenever prop is set and storing the return value in that property. A watchpoint can filter (or nullify) the value assignment, by returning a modified newval (or by returning oldval). If you delete a property for which a watchpoint has been set, that watchpoint does not disappear.
...ous handler attached for that property. Examples Using watch and unwatch const o = { p: 1 }; o.watch('p', (id, oldval, newval) => { console.log('o.' + id + ' changed from ' + oldval + ' to ' + newval); return newval; }); o.p = 2; o.p = 3; delete o.p; o.p = 4; o.unwatch('p'); o.p = 5; This script displays the following: o.p changed from 1 to 2 o.p changed from 2 to 3 o.p changed from
undefined to 4 Using watch() to validate an object's properties You can use watch to test any assignment to an object's properties. This example ensures that every Person always has a valid name and an age between 0 and 200. class Person { constructor(name, age) { this.watch('age', this._isValidAssignment.bind(this)); this.watch('name', this._isValidAssignment.bind(this)); this.name = nam...
Sharp variables in JavaScript - Archive of obsolete content
a reference to initial variable. You can use this to create objects in a single line of code that would otherwise take multiple lines of code. Examples Multiple references var a = { foo:#1=[], bar:#1# }; a.foo.push("Hello"); a.bar.push("there!"); alert(a.foo[1]); // "there!" You can avoid using sharp variables by breaking the declaration up into multiple lines. var a = { foo:[], bar:
undefined }; a.bar = a.foo; a.foo.push("Hello"); a.bar.push("there!"); alert(a.foo[1]); // "there!" Cyclic references Sharp variables can be used to create a circularly linked list in one line of code. var a = #1 = { val:1, next:{val:2, next:#1#} }; a.val; // 1 a.next.val; // 2 a.next.next.val; // 1 a.next.next == a; // true Again, you can eliminate the...
...es Sharp variables can be used to create a circularly linked list in one line of code. var a = #1 = { val:1, next:{val:2, next:#1#} }; a.val; // 1 a.next.val; // 2 a.next.next.val; // 1 a.next.next == a; // true Again, you can eliminate the need for sharp variables by using two lines instead of one for the declaration. ...
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms
he function is written, the code still works. This is because of how context execution works in JavaScript. Hoisting works well with other data types and variables. The variables can be initialized and used before they are declared. Only declarations are hoisted JavaScript only hoists declarations, not initializations. If a variable is declared and initialized after using it, the value will be
undefined. For example: console.log(num); // Returns
undefined, as only declaration was hoisted, no initialization has happened at this stage var num; // Declaration num = 6; // Initialization The example below only has initialization. No hoisting happens so trying to read the variable results in ReferenceError exception. console.log(num); // Throws ReferenceError exception num = 6; // Initialization B...
...isting happens so trying to read the variable results in ReferenceError exception. console.log(num); // Throws ReferenceError exception num = 6; // Initialization Below are more examples demonstrating hoisting. // Example 1 // Only y is hoisted x = 1; // Initialize x, and if not already declared, declare it - but no hoisting as there is no var in the statement. console.log(x + " " + y); // '1
undefined' // This prints value of y as
undefined as JavaScript only hoists declarations var y = 2; // Declare and Initialize y // Example 2 // No hoisting, but since initialization also causes declaration (if not already declared), variables are available. a = 'Cran'; // Initialize a b = 'berry'; // Initialize b console.log(a + "" + b); // 'Cranberry' Technical reference var statement -- MDN funct...
NaN - MDN Web Docs Glossary: Definitions of Web-related terms
Hence this division may break the program. Now, if this computation was a small part of a much larger algorithm, it would be really painful to figure out where the error actually occurs. ...
...lue that cannot be represented, especially results of floating-point calculations. For example, NaNs can represent infinity, result of division by zero, missing value, or the square root of a negative (which is imaginary, whereas a floating-point number is real). Practically speaking, if I divide two variables in a JavaScript program, the result may be NaN, which is predefined in JavaScript as "
undefined". Hence this division may break the program. Now, if this computation was a small part of a much larger algorithm, it would be really painful to figure out where the error actually occurs. Fortunately, since the result will be NaN and I know my divisor may turn out to be 0, I can set up testing conditions that prevent any such computations in the first place or notify me of where they happen. Le...
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
There also is null, which is seemingly primitive, but indeed is a special case for every Object: and any structured type is derived from null by the Prototype Chain. Most of the time, a primitive value is represented directly at the lowest level of the language implementation. All primitives are immutable, i.e., they cannot be altered. ...
.... (Note that window.foo could still be used to access the external foo variable.) In conclusion, any changes inside our functions won't affect the original foo at all, as we are modifying copies of it That's why primitives are immutable - instead of changing them directly, we're modifying a copy, without affecting the original. Primitive wrapper objects in JavaScript Except for null and
undefined, all primitive values have object equivalents that wrap around the primitive values: String for the string primitive. Number for the number primitive. BigInt for the bigint primitive. Boolean for the boolean primitive. Symbol for the symbol primitive. The wrapper's valueOf() method returns the primitive value. Learn more General knowledge Introduction to JavaScript data types Primi...
Function return values - Learn web development
s return value is saved in the variable newString. If you look at the replace() function MDN reference page, you'll see a section called return value. It is very useful to know and understand what values are returned by functions, so we try to include this information wherever possible. Some functions don't return any value. (In these cases, our reference pages list the return value as void or
undefined.) For example, in the displayMessage() function we built in the previous article, no specific value is returned when the function is invoked. It just makes a box appear somewhere on the screen -- that's it! Generally, a return value is used where the function is an intermediate step in a calculation of some kind. You want to get to a final result, which involves some values that need to be calcu...
...you to enter a number into the text box, and display different numbers related to it in the paragraph below. Let's add some useful functions to this <script> element. Below the two existing lines of JavaScript, add the following function definitions: function squared(num) { return num * num; } function cubed(num) { return num * num * num; } function factorial(num) { if (num < 0) return
undefined; if (num == 0) return 1; let x = num - 1; while (x > 1) { num *= x; x--; } return num; } The squared() and cubed() functions are fairly obvious -- they return the square or cube of the number that was given as a parameter. The factorial() function returns the factorial of the given number. Next, we're going to include a way to print out information about the number entered in...
Making decisions in your code — conditionals - Learn web development
alue is less than or greater than another. <= and >= -- test if one value is less than or equal to, or greater than or equal to, another. Note: Review the material at the previous link if you want to refresh your memories on these. We wanted to make a special mention of testing boolean (true/false) values, and a common pattern you'll come across again and again. ...
...We wanted to make a special mention of testing boolean (true/false) values, and a common pattern you'll come across again and again. ...
CustomizableUI.jsm
because of this. aWidgetId is the widget whose instance is being destroyed, aDocument the document in which this is happening. Only fired for API-based widgets. onWidgetDrag(aWidgetId, aArea) Fired both when and after customize mode drag handling system tries to determine the width and height of widget aWidgetId when dragged to a different area. aArea will be the area the item is dragged to, or
undefined after the measurements have been done and the node has been moved back to its 'regular' area. onCustomizeStart(aWindow) Fired when opening customize mode in aWindow. onCustomizeEnd(aWindow) Fired when exiting customize mode in aWindow. onWidgetOverflow(aNode, aContainer) Fired when a widget's DOM node is overflowing its container, a toolbar, and will be displayed in the overflow panel. onW...
... the place of an element. This is intended for use from customize mode. You should generally use getPlacementOfWidget instead, which is cheaper because it does not use the DOM. Parameters aElement the DOM node whose place we need to check Return value "toolbar" if the node is in a toolbar, "panel" if it is in the menu panel, "palette" if it is in the (visible!) customization palette,
undefined otherwise. isBuiltinToolbar() Check if a toolbar is builtin or not. Parameters aToolbarId the ID of the toolbar you want to check Return value true if the toolbar is builtin, false otherwise. Properties For readability, the properties are split according to purpose: Dynamic getters Attribute Type Description areas Array Always returns an up to date Arr...
DownloadList
n a download is added to the list, its onchange event is registered by the list, thus it cannot be used to monitor the download. To receive change notifications for downloads that are added to the list, use the addView() method to register for onDownloadChanged notifications. Promise add( Download aDownload ); Parameters aDownload The Download object to add. Promise resolves to
undefined when the download has been added. remove() Removes a download from the list. If the download was already removed, this method has no effect. Promise remove( Download aDownload ); Parameters aDownload The Download object to remove. Promise resolves to
undefined when the download has been removed. addView() Adds a view that will be notified of changes to downloads. The newly adde...
...ion is called with a single Download argument, after the download is added to the end of the list. onDownloadChanged: Optional This function is called with a single Download argument, after the properties of the download change. onDownloadRemoved: Optional This function is called with a single Download argument, after the download is removed from the list. Promise resolves to
undefined when the view has been registered and all the onDownloadAdded notifications for the existing downloads have been sent. removeView() Removes a view that was previously added using addView(). Promise removeView( Object aView ); Parameters aView Optional The view object to remove. Promise resolves to
undefined when the view has been removed. At this point, the removed view will no...
DownloadSummary
ered before this object is bound to an actual list. This allows the summary to be used without requiring the initialization of the DownloadList first. Note: This method is already called internally by the Downloads.getSummary() function. Promise bindToList( DownloadList aList ); Parameters aList Underlying DownloadList whose contents should be summarized. Promise resolves to
undefined when the view on the underlying list has been registered. addView() Adds a view that will be notified of changes to the summary. The newly added view will receive an initial onSummaryChanged notification. Promise addView( Object aView ); Parameters aView The view object to add. The following methods may be defined: onSummaryChanged: Optional Called after any property ...
.... addView() Adds a view that will be notified of changes to the summary. The newly added view will receive an initial onSummaryChanged notification. Promise addView( Object aView ); Parameters aView The view object to add. The following methods may be defined: onSummaryChanged: Optional Called after any property of the summary has changed. Promise resolves to
undefined when the view has been registered and the onSummaryChanged notification has been sent. removeView() Removes a view that was previously added using addView(). Promise removeView( Object aView ); Parameters aView The view object to remove. Promise resolves to
undefined when the view has been removed. At this point, the removed view will not receive any more notifications. ...
DownloadTarget
deleted, then this value is zero. For single-file downloads, this property's value will always match the actual size of the file on disk, while the Download.totalBytes property, when available, may indicate the size of the data as encoded for transfer instead. For downloads of multiple files, such as downloading a web page and its required media to disk, the meaning of this property is
undefined. It currently indicates the size of the main file (such as the HTML document) rather than the sum of all of the files' sizes, but you must not rely upon this behavior, as it is subject to change. This is a dynamic property, which is updated when the download finishes or whenever the Download.refresh() method is called. You can use this value from the front-end to reduce file I/O that would b...
...ated by the file system. If the download is in progress or has been finalized, this method does nothing and returns a resolved Promise. Calling this method lets the Download object's properties be updated if the user moves or deletes the target file or its associated ".part" file, which contains a partially-downloaded file's contents. Promise refresh(); Parameters None. Promise resolves to
undefined when the state of the download has been updated. Promise can be rejected with Never. ...
Http.jsm
HTTP.jsm Http.jsm provides httpRequest - a wrapper for XMLHttpRequest that provides convenient and simplified API for dealing with HTTP requests. httpRequest supports the following parameters: name meaning headers an array of headers postData this can be: a string: send it as is an array of parameters: encode as form values null/
undefined: no POST data. method GET, POST or PUT (this is automatically set if postData exists). onLoad a function handle to call when the load is complete, it takes two parameters: the responseText and the XHR object. onError a function handle to call when an error occurs, it takes three parameters: the error, the responseText and the XHR object. ...
... Headers or post data are given as an array of arrays, for each inner array the first value is the key and the second is the value. For example: [["key1", "value1"], ["key2", "value2"]]. Submitting post data httpRequest allows attaching data to the post requests. The data can be specified via postData option. postData can be of 2 different types: a string or an array of parameters. When null/
undefined is given, no post data will be attached. If a string is given the data will be appended to the request as is. In case an array of parameters is given, it will be treated as an array of key-value pairs. The elements of the array will be URL-encoded and "application/x-www-form-urlencoded; charset=utf-8" will be enforced as the content type. Http.jsm only forces the content type if the post data is ...
OS.File for the main thread
nd close to append to a file. If the file does not exist, it is created. At the time of this writing, write does not support encoding option so the text to be written has to be encoded with TextEncoder. This example also shows the resolve value of open (an instance of OS.File, this is a file, so you can do any of the methods on it found here), write (a number indicating bytes written), and close (
undefined, meaning there is no resolve value). var pth = OS.Path.join(OS.Constants.Path.desktopDir, 'app.txt'); OS.File.open(pth, {write: true, append: true}).then(valOpen => { console.log('valOpen:', valOpen); var txtToAppend = 'append some text \n'; var txtEncoded = new TextEncoder().encode(txtToAppend); valOpen.write(txtEncoded).then(valWrite => { console.log('valWrite:', valWri...
...th does not represent an existing file. Performance Note: If the file is already opened, calling method stat() is much faster than calling function OS.File.stat(). OS.File.unixSymLink() Create a symoblic link file, also known as "Alias" files on Mac OS. This is similar to "Shortcut" files on Windows systems. This function is specific to UNIX baed systems such as Linux and Mac OS X. Promise<
undefined> unixSymLink( in string pathTarget, in string pathCreate ) Arguments pathTarget The complete path to the file that should be launced by the symbolic link. pathCreate The complete path to the file that should launch target. The file extension should be .link. Promise resolves to
undefined Promise can be rejected with OS.File.Error In case of any error. If the file exists alre...
Deferred
is. Note: Calling this method with a pending promise as the aValue argument, and then calling it again with another value before the promise is resolved or rejected, will have no effect the second time, as the associated promise is already resolved to the pending promise value as its resolution. void resolve( aValue ); Parameters aValue Optional If this value is not a promise, including
undefined, it becomes the fulfillment value of the associated promise. If this value is a promise, then the associated promise will be resolved to the passed promise, and follow the state as the provided promise (including any future transitions). reject() Rejects the associated promise with the specified reason. If the promise has already been resolved, either to a value, a rejection, or another promis...
...e specified reason. If the promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. Note: This function is exactly same as Promise constructor's reject argument, and can be called with any value of this. void reject( aReason ); Parameters aReason Optional The rejection reason for the associated promise. Although the reason can be
undefined, it is generally an Error object, like in exception handling. Note: This argument should not be a promise. Specifying a rejected promise would make the rejection reason equal to the rejected promise itself, and not its rejection reason. ...
L20n Javascript API
ontext instance, as well as all other locales available to the Context instance before the language negotiation. Locales are referenced by their BCP 47 language codes. ctx.registerLocales('en-US', ['ar', 'es-AR', 'es-ES', 'en-US', 'fr', 'pl']); defaultLocale is the original language of the Context instance and will be used as the last fallback locale if other locales are registered. If it is
undefined, or if registerLocales hasn't been called at all, the Context instance will create a special locale called i-default to be used as the default. availableLocales is an array of all locales available to the Context instance. This array (with defaultLocale appended to it if it is not already present) will be used to negotiate the fallback chain for the user. ctx.registerLocaleNegotiator(negotiator...
...Context instance freezes. When all resources have been fetched, parsed and compiled, the Context instance will emit a ready event. The final list of locales supported by the Context instance will be negotiated asynchronously by the negotiator registered by registerLocaleNegotiator. ctx.requestLocales('pl'); ctx.requestLocales('fr-CA', 'fr'); If requestedLocales argument list is empty or
undefined, the default locale from registerLocales will be used. ctx.requestLocales('pl'); If registerLocales hasn't been called, the special i-default locale is used, which means that the following minimal code is valid and will result in a fully operational Context instance. var ctx = L20n.getContext(); ctx.addResource('<hello "Hello, world!">'); ctx.requestLocales(); requestLocales can be call...
NSS_3.12_release_notes.html
hared Database implementation slow Bug 391294: Shared Database implementation really slow on network file systems Bug 392521: Automatic shared db update fails if user opens database R/W but never supplies a password Bug 392522: Integrity hashes must be updated when passwords are changed. ...
...inked program Bug 324740: add generation of SIA and AIA extensions to certutil Bug 339737: LIBPKIX OCSP checking calls CERT_VerifyCert Bug 358785: Merge NSS_LIBPKIX_BRANCH back to trunk Bug 365966: infinite recursive call in VFY_VerifyDigestDirect Bug 382078: pkix default http client returns error when try to get an ocsp response. ...
The JavaScript Runtime
script or function is compiled to a separate class. Compilation of JavaScript source to class files is supported. It is possible to specify the class files as well as the packages to generate into. Types and Values There are six fundamental types in JavaScript. These types are implemented with the following Java types and values: JavaScript fundamental type Java type
Undefined A singleton object defined by Context.get
UndefinedType() Null null Boolean java.lang.Boolean Number java.lang.Number, that is, any of java.lang.Byte, java.lang.Short, java.lang.Integer, java.lang.Float, or java.lang.Double. Not java.lang.Long, since a double representation of a long may lose precision. String java.lang.CharSequence (java.lang.Str...
...rg.mozilla.javascript.ConsString) Object org.mozilla.javascript.Scriptable In addition, ECMA refers to objects that implement [[Call]] as functions. These object types are represented by implementing the Function interface. Since JavaScript is a dynamically typed language, the static Java type of a JavaScript value is java.lang.Object. The behavior of the JavaScript engine is
undefined if a value of any type other than the ones described above is introduced into JavaScript. (This caveat does not apply to scripts that use LiveConnect; the Java values are wrapped and unwrapped as appropriate to conform to the above type constraints.) Property Access Properties in JavaScript objects may be accessed using either string or numeric identifiers. Conceptually, all accessors are conve...
JSAPI User Guide
n a statically typed language, like C or C++, in which all variables have types, interact with JavaScript? The JSAPI provides a data type, JS::Value (also with a deprecated jsval typedef), which can contain JavaScript values of any type. A JS::Value can be a number, a string, a boolean value, a reference to an object (like an Object, Array, Date, or Function), or one of the special values null or
undefined. For integers and boolean values, a jsval contains the value itself. In other cases, the jsval is a pointer to an object, string, or number. Warning: Like C++ pointers, and unlike JavaScript vars, a JS::Value is not automatically initialized to a safe value, and can become a dangling pointer! A dangling pointer is a pointer that used to point to a valid object, but no longer does because the ...
...jects, strings, and numbers that don't appear to be in use, and a JS::Value by itself does not protect its referent from the garbage collector. See Garbage collection below for crucial information on how to use JS::Values safely. JS::Value includes member functions to test the JavaScript data type. These are isObject(), isNumber(), isInt32(), isDouble(), isString(), isBoolean(), isNull(), and is
Undefined(). If a JS::Value contains a JSObject, double, or JSString, you can cast it to its underlying data type using the toObject(), toDouble(), and toString() member functions, respectively. This is useful in some cases where your application or a JSAPI function requires a variable or argument of a specific data type, rather than a JS::Value. Similarly, you can create a JS::Value wrapping a JSObject, ...
JSPropertyOp
it can specify getter and setter callbacks for the new property. Getters. The getter callback is called each time JavaScript code accesses the property's value using the syntax obj.prop or obj[propname]. It is also called when the property's value is accessed via JSAPI functions such as JS_GetProperty or (less obviously) JS_CallFunctionName. On entry, *vp contains the property's stored value or
undefined if the property doesn't have a stored value. The callback may modify *vp. On success, the callback returns true and the value left in *vp is returned to the script or JSAPI caller. Setters. The setter callback is called each time JavaScript code assigns to the property using any assignment operator (=, +=, etc.) or the ++ or -- operators. It is also called when the property is set via JSAPI func...
...e callback to call JSAPI functions, particularly if obj may have been visible to more than one thread. JSClass.getProperty is the default getter for new properties. See the section on getters and setters above. JSClass.getProperty is also called when a program attempts to get a property that does not exist on obj or any prototype. On entry, *vp contains the property's stored value, or
undefined if the property doesn't exist or doesn't have a stored value. The callback may modify *vp. On success, the post-callback value of *vp is returned to the caller. This value also becomes the property's new stored value, if the property exists and has a stored value. JSStrictPropertyOp JSClass.setProperty is the default setter for new properties. See the section on getters and setters abov...
JS_ConvertValue
alue converts a JavaScript value, v, to the specified type. On success, the converted value is stored in *vp. Typically users of this function set vp to point to v, so that if conversion is successful, v now contains the converted value. JS_ConvertValue calls other, type-specific conversion routines based on the type argument. Converting any value to JSTYPE_VOID always succeeds. The result is
undefined value. Converting to JSTYPE_OBJECT works exactly like JS::ToObject if v.isNullOr
Undefined() is false, otherwise the result is nullptr. Converting to JSTYPE_FUNCTION works like JS_ValueToFunction, but better: the result is a function object that has not been stripped of its lexical scope. It is safe to call the result (e.g. using JS_CallFunctionValue). Converting to JSTYPE_STRING works like JS:...
...e. It is safe to call the result (e.g. using JS_CallFunctionValue). Converting to JSTYPE_STRING works like JS::ToString. Converting to JSTYPE_NUMBER works exactly like JS::ToNumber. Converting to JSTYPE_BOOLEAN works exactly like JS::ToBoolean. On success, JS_ConvertValue stores the converted value in *vp and returns true. On error or exception, it returns false, and the value left in *vp is
undefined. See Also MXR ID Search for JS_ConvertValue JS_ConvertArguments JS_GetTypeName JS_TypeOfValue bug 1125784 ...
JS_ForwardGetPropertyTo
in a request on this JSContext. obj JS::HandleObject Object to search on for the property. id or index JS::HandleId or uint32_t Name or index of the property to look up. onBehalfOf JS::HandleObject Object to receive getter invocation. vp JS::MutableHandleValue Out parameter. ...
...perty, or
undefined if no such property is found. Description JS_ForwardGetPropertyTo is the base implementation of JS_GetProperty, JS_GetUCProperty, JS_GetPropertyById etc, where onBehalfOf is same to obj. onBehalfOf is Receiver in [[Get]] internal method of Proxy, defined in ES2015 draft spec (rev 29, 9.5.8). On success, these functions set *vp to the current value of the property, or
undefined if obj has no such property, and return true. On an error or exception, these functions return false, and the value left in *vp is
undefined. See Also MXR ID Search for JS_ForwardGetPropertyTo JS_GetProperty bug 698551 ...
JS_GetElement
ch to perform the property lookup. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject The object to search for the element. index uint32_t Index of the element to look up. vp JS::MutableHandleValue Out parameter. On success, *vp receives the current value of the element, if it exists, and
undefined otherwise. Description JS_GetElement examines a specified JS object, obj, and its prototype chain, for an element or numeric property numbered index. If the element exists, JS_GetElement sets *vp to the element's current value. If not, it sets *vp to
undefined and returns true (to indicate no error occurred). If the search fails with an error or exception, JS_GetElement returns false, and t...
...ption JS_GetElement examines a specified JS object, obj, and its prototype chain, for an element or numeric property numbered index. If the element exists, JS_GetElement sets *vp to the element's current value. If not, it sets *vp to
undefined and returns true (to indicate no error occurred). If the search fails with an error or exception, JS_GetElement returns false, and the value left in *vp is
undefined. See Also MXR ID Search for JS_GetElement JS_DefineElement JS_DeleteElement JS_GetArrayLength JS_IsArrayObject JS_LookupElement JS_NewArrayObject JS_SetArrayLength JS_SetElement ...
JS_LookupElement
ontext * The context in which to look up the property. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject The object to search. index uint32_t The numeric id of the property to look up. vp JS::MutableHandleValue Out parameter. On success, *vp receives the stored value of obj[index], or
undefined if the element does not exist. Description JS_LookupElement examines a specified JavaScript object, obj, for a numeric property numbered index. Note: In the JavaScript language, numeric properties (also called "elements") are just ordinary properties whose names are numeric strings. For example, obj[6] is always exactly the same as obj["6"]. The ECMAScript standard also specifies this be...
...exactly the same as obj["6"]. The ECMAScript standard also specifies this behavior: see ECMA 262-3 ?11.2.1, step 6. So any call to JS_LookupElement is equivalent to a call to JS_LookupProperty passing a numeric string for the name. If the property obj[index] exists, JS_LookupElement sets *vp to the property's stored value and returns true. If no such property exists, JS_LookupElement sets *vp to
undefined and returns true (to indicate that no error occurred). On error or exception, JS_LookupElement returns false, and the value left in *vp is
undefined. JS_LookupElement does not distinguish between a property with a value of
undefined and a property that does not exist. See Also JS_DefineElement JS_DeleteElement JS_GetArrayLength JS_GetElement JS_IsArrayObject JS_NewArrayObject JS_SetArr...
JS_LookupProperty
earch a specified object, obj, for a property with the given name. These functions all have similar behavior: The search starts with obj and proceeds along the prototype chain. If the property is found, *vp receives the property's stored value, or true if the property has no stored value; and the return value is true. If neither obj nor any of its prototypes have such a property, *vp receives
undefined and the return value is true (to indicate no error occurred). On error or exception (such as running out of memory during the search), the return value is false, and the value left in *vp is
undefined. There is no way to tell the difference between not finding any property and finding a property whose value is
undefined. Sorry. Use JS_GetPropertyDescriptorById instead. JS_LookupUCProperty is t...
...SRESOLVE_DECLARING Behave as though the name were being declared in a var, const, or function declaration. JSRESOLVE_CLASSNAME Search for the initial value of a standard class such as Object, Array, or Error. Do not automatically infer and enable other flags by looking at the currently executing bytecode. Notes JS_LookupProperty does not distinguish between a property with a value of
undefined and a property that does not exist. Use JS_GetPropertyAttributes to distinguish these cases. JS_LookupProperty differs from JS_GetProperty in that JS_LookupProperty does not invoke the get handler for the property. Internally, property lookups are implemented by the JSObjectOps.lookupProperty callback. See Also bug 547140 -- removed *WithFlags bug 1094176 ...
JS_ValueToNumber
caller must be in a request on this JSContext. v jsval The value to convert. dp jsdouble * Out parameter. On success, *dp receives the converted floating-point value. Description JS_ValueToNumber converts a JavaScript value to a number. It implements the ToNumber operator described in ECMA 262-3 ?9.3. If v is already a number, conversion succeeds. If v is
undefined, null, false, or true, conversion succeeds, and the result is NaN, 0, 0, or 1 respectively. If v is a string, conversion proceeds as specified in ECMA 262-3 ?9.3.1. JS_ValueToNumber always succeeds in this case, returning JS_TRUE. If the string is not a numeric string, *dp is set to NaN. Otherwise v is an object. JS_ValueToNumber carries out the following steps to convert it to a number. If at ...
... Otherwise, the resulting object's toString method, if any, is called. If that produces a primitive value, the value is converted to a number as described above and conversion succeeds. Otherwise conversion fails with a TypeError. On success, JS_ValueToNumber stores the converted value in *dp and returns JS_TRUE. On error or exception, it returns JS_FALSE, and the value left in *dp is
undefined. See Also JS_ConvertArguments JS_ConvertValue JS_GetTypeName JS_TypeOfValue JS_ValueToInt32 JS_ValueToECMAInt32 bug 884410 ...
Components.utils.unwaiveXrays
ause it sees the content window with Xray vision, but the chrome code can waive Xray protection. ...
... // "I'm an expando" // waiving is transitive isXray = Components.utils.isXrayWrapper(waived.document); // false // use unwaiveXrays to undo the waiver var unwaived = Components.utils.unwaiveXrays(waived); isXray = Components.utils.isXrayWrapper(unwaived); // true foo = unwaived.foo; //
undefined // unwaiving is transitive isXray = Components.utils.isXrayWrapper(unwaived.document); // true ...
nsICacheEntryDescriptor
stream to cache data. This will fail if the cache entry is not stream based. Use the stream transport service to asynchronously read this stream on a background thread. The returned stream may implement nsISeekableStream. nsIInputStream openInputStream( in unsigned long offset ); Parameters offset Read starting from this offset into the cached data. An offset beyond the end of the stream has
undefined consequences. Return value Returns blocking, unbuffered input stream. openOutputStream() This method opens blocking output stream to cache data. This will fail if the cache entry is not stream based. Use the stream transport service to asynchronously write to this stream on a background thread. The returned stream may implement nsISeekableStream. If opening an output stream to existing cached da...
...o asynchronously write to this stream on a background thread. The returned stream may implement nsISeekableStream. If opening an output stream to existing cached data, the data will be truncated to the specified offset. nsIOutputStream openOutputStream( in unsigned long offset ); Parameters offset Write starting from this offset into the cached data. An offset beyond the end of the stream has
undefined consequences. Return value Returns blocking, unbuffered output stream. setDataSize() This method sets the cache entry data size. This will fail if the cache entry is stream based. void setDataSize( in unsigned long size ); Parameters size The cache entry data size. setExpirationTime() This method sets the time at which the cache entry should be considered invalid (in seconds since the Epoch...
nsIHttpChannel
a NS_ERROR_FAILURE. void visitOriginalResponseHeaders( in nsIHttpHeaderVisitor aVisitor ); Parameters aVisitor An nsIHttpHeaderVisitor instance allowing to visit all original response headers. visitRequestHeaders() Call this method to visit all request headers. Warning: Calling setRequestHeader(), setReferrerWithPolicy() or setEmptyRequestHeader() while visiting request headers has
undefined behavior until Gecko 47 (Firefox 47.0 / Thunderbird 47.0 / SeaMonkey 2.44). Starting from Gecko 48 (Firefox 48.0 / Thunderbird 48.0 / SeaMonkey 2.45) they will return a NS_ERROR_FAILURE. void visitRequestHeaders( in nsIHttpHeaderVisitor aVisitor ); Parameters aVisitor The header visitor instance. visitResponseHeaders() Call this method to visit all response headers. Warning: Callin...
.../ SeaMonkey 2.44). Starting from Gecko 48 (Firefox 48.0 / Thunderbird 48.0 / SeaMonkey 2.45) they will return a NS_ERROR_FAILURE. void visitRequestHeaders( in nsIHttpHeaderVisitor aVisitor ); Parameters aVisitor The header visitor instance. visitResponseHeaders() Call this method to visit all response headers. Warning: Calling setResponseHeader() while visiting response headers has
undefined behavior until Gecko 48 (Firefox 48.0 / Thunderbird 48.0 / SeaMonkey 2.45). Starting from Gecko 49 (Firefox 49.0 / Thunderbird 49.0 / SeaMonkey 2.46) it will return a NS_ERROR_FAILURE. void visitResponseHeaders( in nsIHttpHeaderVisitor aVisitor ); Parameters aVisitor The header visitor instance. Exceptions thrown NS_ERROR_NOT_AVAILABLE If called before the response has been receiv...
nsIWebNavigation
ned long loadFlags, nsIURI referrer, nsIInputStream postData, nsIInputStream headers ); Parameters URI The URI string to load. For HTTP and FTP URLs and possibly others, characters above U+007F will be converted to UTF-8 and then URL- escaped per the rules of RFC 2396. loadFlags Flags modifying load behaviour. This parameter is a bitwise combination of the load flags defined above. (
Undefined bits are reserved for future use.) Generally you will pass LOAD_FLAGS_NONE for this parameter. referrer The referring URI. If this argument is null, then the referring URI will be inferred internally. postData If the URI corresponds to a HTTP request, then this stream is appended directly to the HTTP request headers. It may be prefixed with additional HTTP headers. This stream must contain a ...
...ameter may be null. reload() Tells the Object to reload the current page. There may be cases where the user will be asked to confirm the reload (for example, when it is determined that the request is non-idempotent). void reload( unsigned long reloadFlags ); Parameters reloadFlags Flags modifying load behaviour. This parameter is a bitwise combination of the load flags defined above. (
Undefined bits are reserved for future use.) Generally you will pass LOAD_FLAGS_NONE for this parameter. stop() Stops a load of a URI. void stop( unsigned long stopFlags ); Parameters stopFlags This parameter is one of the stop flags defined above. ...
nsIWebProgressListener
ccur if a security package is installed. void onSecurityChange( in nsIWebProgress aWebProgress, in nsIRequest aRequest, in unsigned long aState ); Parameters aWebProgress The nsIWebProgress instance that fired the notification. aRequest The nsIRequest that has new security state. aState A value composed of the Security State Flags and the Security Strength Flags listed above. Any
undefined bits are reserved for future use. onStateChange() Notification indicating the state has changed for one of the requests associated with aWebProgress. void onStateChange( in nsIWebProgress aWebProgress, in nsIRequest aRequest, in unsigned long aStateFlags, in nsresult aStatus ); Parameters aWebProgress The nsIWebProgress instance that fired the notification. aRequest The nsIReq...
...equest, in unsigned long aStateFlags, in nsresult aStatus ); Parameters aWebProgress The nsIWebProgress instance that fired the notification. aRequest The nsIRequest that has changed state. This parameter may be null. aStateFlags Flags indicating the new state. This value is a combination of one of the State Transition Flags and one or more of the State Type Flags defined above. Any
undefined bits are reserved for future use. aStatus Error status code associated with the state change. This parameter should be ignored unless aStateFlags includes the STATE_STOP bit. The status code indicates success or failure of the request associated with the state change. Note: aStatus may be a success code even for server generated errors, such as the HTTP 404 File Not Found error. In such cases, ...
Xray vision
ty of a DOM object, and then it will be filtered out by the DOM Xray: // content code // redefine Date.getFullYear() Date.prototype.getFullYear = function() {return 1000}; var date = new Date(); // chrome code // contentWindow is an Xray, and date is an expando on contentWindow // so date is filtered out gBrowser.contentWindow.date.getFullYear() // -> TypeError: gBrowser.contentWindow.date is
undefined The chrome code will only even see date if it waives Xrays, and then, because waiving is transitive, it should expect to be vulnerable to redefinition: // chrome code Components.utils.waiveXrays(gBrowser.contentWindow).date.getFullYear(); // -> 1000 However, there are some situations in which privileged code will access JavaScript objects that are not themselves DOM objects and are not proper...
...log("3) Value property defined by assignment to this:"); console.log(sandbox.me.firstName); // -> "Joe" // 4) value properties defined using defineProperty are visible: console.log("4) Value property defined by defineProperty"); console.log(sandbox.me.lastName); // -> "Smith" // 5) accessor properties are not visible console.log("5) Accessor property"); console.log(sandbox.me.middleName); // ->
undefined // 6) accessing a value property of a value-property object is fine console.log("6) Value property of a value-property object"); console.log(sandbox.me.address.street); // -> "Main Street" // 7) functions defined on the sandbox-defined object are not visible in the Xray console.log("7) Call a function defined on the object"); try { console.log(sandbox.me.fullName()); } catch (e) { console.e...
Declaring and Using Callbacks
return true; // as the return of the FunctionType was ctypes.bool we must make our javascript callback return bool otherwise js-ctypes will throw error saying unexpected type return } var myCCallback = myFuncTypeDeclaration.ptr(myJSCallback); Example 2 This callback that returns void and no arguments. When void is the return type, the javascript callback must not return, or it should return
undefined. ...
...ill throw error saying unexpected type return } var myCCallback = myFuncTypeDeclaration.ptr(myJSCallback); Example 2 This callback that returns void and no arguments. When void is the return type, the javascript callback must not return, or it should return
undefined. var myFuncTypeDeclaration = ctypes.FunctionType(ctypes.default_abi, ctypes.void_t, []); function myJSCallback() { return
undefined; // as the return of the FunctionType was ctypes.void_t we must return
undefined OR dont return at all otherwise js-ctypes will throw an error saying unexpected type } var myCCallback = myFuncTypeDeclaration.ptr(myJSCallback); Using Callbacks Since callbacks are function pointers in C, js-ctypes has special handling for function pointer types. Consider the following code: function myJSCallba...
Rich output - Firefox Developer Tools
to the clipboard Once you have output in the console window, you can save it to the clipboard by right-clicking on the output and selecting Export visible messages to clipboard: This will copy all of the output to the clipboard. Then you can paste it into a document. The output will look something like this: console.log(todoList) Array(4) [ {...}, {...}, {...}, {...} ] debugger eval code:1:9
undefined If you expand objects, such as arrays, you get slightly different content. For example, by expanding the array in the above list, I get the following: console.log(todoList) (4) [...] 0: Object { status: "Done", description: "Morning Pages", dateCreated: 1552404478137 } 1: Object { status: "In Progress", description: "Refactor styles", dateCreated: 1552404493169 } 2: Object { status: "To Do",...
... ...
Cache.match() - Web APIs
Syntax cache.match(request, {options}).then(function(response) { // Do something with the response }); Parameters request The Request for which you are attempting to find responses in the Cache. This can be a Request object or a URL. options Optional An object that sets options for the match operation. ...
...rmally only GET and HEAD are allowed.) It defaults to false. ignoreVary: A Boolean that when set to true tells the matching operation not to perform VARY header matching -- i.e. if the URL matches you will get a match regardless of whether the Response object has a VARY header. It defaults to false. Return value A Promise that resolves to the first Response that matches the request or to
undefined if no match is found. Note: Cache.match() is basically identical to Cache.matchAll(), except that rather than resolving with an array of all matching responses, it resolves with the first matching response only (that is, response[0]). Examples This example is taken from the custom offline page example (live demo). It uses a cache to supply selected data when a request fails. A catch() clause...
CacheStorage - Web APIs
e storage for Cache objects. The interface: Provides a master directory of all the named caches that can be accessed by a ServiceWorker or other type of worker or window scope (you're not limited to only using it with service workers, even though the Service Workers spec defines it). Note: Chrome and Safari only expose `CacheStorage` to the windowed context over HTTPS. window.caches will be
undefined unless an SSL certificate is configured. Maintains a mapping of string names to corresponding Cache objects. Use CacheStorage.open() to obtain a Cache instance. Use CacheStorage.match() to check if a given Request is a key in any of the Cache objects that the CacheStorage object tracks. You can access CacheStorage through the global caches property. Note: CacheStorage always rejects with ...
... '/sw-test/gallery/bountyHunters.jpg', '/sw-test/gallery/myLittleVader.jpg', '/sw-test/gallery/snowTroopers.jpg' ]); }) ); }); self.addEventListener('fetch', function(event) { event.respondWith(caches.match(event.request).then(function(response) { // caches.match() always resolves // but in case of success response will have value if (response !==
undefined) { return response; } else { return fetch(event.request).then(function (response) { // response may be used only once // we need to save clone to put one copy in cache // and serve second one let responseClone = response.clone(); caches.open('v1').then(function (cache) { cache.put(event.request, responseClone); }); ...
CustomElementRegistry.whenDefined() - Web APIs
If the custom element is already defined, the promise is resolved immediately. ...
...ontainer"> <div class="menu-placeholder">Loading...</div> <nav-menu> <menu-item>Item 1</menu-item> <menu-item>Item 2</menu-item> ... <menu-item>Item N</menu-item> </nav-menu> </nav> const container = document.getElementById('menu-container'); const placeholder = container.querySelector('.menu-placeholder'); // Fetch all the children of menu that are not yet defined. const
undefinedElements = container.querySelectorAll(':not(:defined)'); const promises = [...
undefinedElements].map( button => customElements.whenDefined(button.localName) ); // Wait for all the children to be upgraded, // then remove the placeholder. await Promise.all(promises); container.removeChild(placeholder); Specifications Specification Status Comment HTML Living StandardThe...
FetchEvent.preloadResponse - Web APIs
Example This code snippet is from the navigation preload page. The ServiceWorkerGlobalScope.onfetch event handler listens for the fetch event. When fired, pass a promise that back to the controlled page to FetchEvent.respondWith(). ...
... Example This code snippet is from the navigation preload page. The ServiceWorkerGlobalScope.onfetch event handler listens for the fetch event. When fired, pass a promise that back to the controlled page to FetchEvent.respondWith(). ...
HTMLCollection - Web APIs
HTML DOM is live; it is automatically updated when the underlying document is changed. Properties HTMLCollection.length Read only Returns the number of items in the collection. Methods HTMLCollection.item() Returns the specific node at the given zero-based index into the list. Returns null if the index is out of range. An alternative to accessing collection[i] (which instead returns
undefined when i is out-of-bounds). This is mostly useful for non-JavaScript DOM implementations. HTMLCollection.namedItem() Returns the specific node whose ID or, as a fallback, name matches the string specified by name. Matching by name is only done as a last resort, only in HTML, and only if the referenced element supports the name attribute. Returns null if no node exists by the given name. An alter...
...aScript DOM implementations. HTMLCollection.namedItem() Returns the specific node whose ID or, as a fallback, name matches the string specified by name. Matching by name is only done as a last resort, only in HTML, and only if the referenced element supports the name attribute. Returns null if no node exists by the given name. An alternative to accessing collection[name] (which instead returns
undefined when name does not exist). This is mostly useful for non-JavaScript DOM implementations. Usage in JavaScript HTMLCollection also exposes its members directly as properties by both name and index. HTML IDs may contain : and . as valid characters, which would necessitate using bracket notation for property access. Currently HTMLCollections does not recognize purely numeric IDs, which would cause...
IDBFactory.deleteDatabase() - Web APIs
The deleteDatabase() method of the IDBFactory interface requests the deletion of a database. The method returns an IDBOpenDBRequest object immediately, and performs the deletion operation asynchronously. If the database is successfully deleted, then a success event is fired on the request object returned from this method, with its result set to
undefined. If an error occurs while the database is being deleted, then an error event is fired on the request object that is returned from this method. When deleteDatabase() is called, any other open connections to this particular database will get a versionchange event. Note: This feature is available in Web Workers. Syntax For the current standard: var request = indexedDB.deleteDatabase(name); For the experimental version with options (see below):...
... value A IDBOpenDBRequest on which subsequent events related to this request are fired. Example var DBDeleteRequest = window.indexedDB.deleteDatabase("toDoList"); DBDeleteRequest.onerror = function(event) { console.log("Error deleting database."); }; DBDeleteRequest.onsuccess = function(event) { console.log("Database deleted successfully"); console.log(event.result); // should be
undefined }; Specifications Specification Status Comment Indexed Database API DraftThe definition of 'deleteDatabase()' in that specification. Recommendation Indexed Database API 2.0The definition of 'deleteDatabase()' in that specification. Recommendation Initial definition. Browser compatibility The compatibility table on this page is generated f...
IDBKeyRange.includes() - Web APIs
keyRangeValue.includes('F'); // Returns true var myResult = keyRangeValue.includes('W'); // Returns false Polyfill The includes() method was added in the second edition of the Indexed DB specification. For browsers that do not support it, the following polyfill can be used. ...
...nd edition of the Indexed DB specification. For browsers that do not support it, the following polyfill can be used. IDBKeyRange.prototype.includes = IDBKeyRange.prototype.includes || function(key) { var r = this, c; if (r.lower !==
undefined) { c = indexedDB.cmp(key, r.lower); if (r.lowerOpen && c <= 0) return false; if (!r.lowerOpen && c < 0) return false; } if (r.upper !==
undefined) { c = indexedDB.cmp(key, r.upper); if (r.upperOpen && c >= 0) return false; if (!r.upperOpen && c > 0) return false; } return true; }; Specification Specification Status Comment Indexed Database API DraftThe definition of 'includes()' in that specification. Recommendation Indexed Database API DraftThe definition of 'includes()' in that ...
IDBKeyRange - Web APIs
Note: This feature is available in Web Workers. Properties IDBKeyRange.lower Read only Lower bound of the key range. IDBKeyRange.upper Read only Upper bound of the ...
... Note: This feature is available in Web Workers. ...
LockManager.request() - Web APIs
The mode property of the options parameter may be either "exclusive" or "shared". Request an "exclusive" lock when it should only be held by one code instance at a time. This applies to code in both tabs and workers. Use this to represent mutually exclusive access to a resource. ...
... held locks with the same name will be released, and the request will be granted, preempting any queued requests for it. The default value is false. signal Optional: An AbortSignal (the signal property of an AbortController); if specified and the AbortController is aborted, the lock request is dropped if it was not already granted. callback ... Return value A Promise that resolves with
undefined when the request is granted. Examples General Example The following example shows the basic use of the request() method with an asynchronous function as the callback. Once the callback is invoked, no other running code on this orign can hold `my_resource` until the callback returns. await navigator.locks.request('my_resource', async lock => { // The lock was granted. }); Mode Example The...
performance.measure() - Web APIs
as created. startTime - set to the start mark timestamp. duration - set to a DOMHighResTimeStamp that is the duration of the measure (typically, the end mark timestamp minus the start mark timestamp). Note: This feature is available in Web Workers. Syntax performance.measure(name); performance.measure(name, startMark); performance.measure(name, startMark, endMark); performance.measure(name,
undefined, endMark); Arguments name A DOMString representing the name of the measure. startMark Optional A DOMString representing the name of the measure's starting mark. May also be the name of a PerformanceTiming property. If it is omitted, then the start time will be the navigation start time. endMark Optional A DOMString representing the name of the measure's ending mark. May also be the name...
...ested timeouts, and create a PerformanceMark for each. performance.mark(markerNameA); setTimeout(function() { performance.mark(markerNameB); setTimeout(function() { // Create a variety of measurements. performance.measure("measure a to b", markerNameA, markerNameB); performance.measure("measure a to now", markerNameA); performance.measure("measure from navigation start to b",
undefined, markerNameB); performance.measure("measure from the start of navigation to now"); // Pull out all of the measurements. console.log(performance.getEntriesByType("measure")); // Finally, clean up the entries. performance.clearMarks(); performance.clearMeasures(); }, 1000); }, 1000); Specifications Specification Status Comment User Timing Level...
Using Performance Timeline - Web APIs
performance.mark Not supported"); return; } // Create some performance entries via the mark() and measure() methods performance.mark("Begin"); do_work(50000); performance.mark("End"); do_work(50000); performance.measure("Measure1", "Begin", "End"); // Use getEntries() to iterate all entries var p = performance.getEntries(); for (var i=0; i < p.length; i++...
... toJSON() method that returns the serialization of the PerformanceEntry object. The following examples show the use of this method. ...
ReadableStream.getReader() - Web APIs
his one is released. Syntax var reader = readableStream.getReader({mode}); Parameters {mode} Optional An object containing a property mode, which takes as its value a DOMString specifying the type of reader to create. Values can be: "byob", which results in a ReadableStreamBYOBReader being created that can read readable byte streams (i.e. can handle "bring your own buffer" reading).
undefined (or not specified at all -- this is the default), which results in a ReadableStreamDefaultReader being created that can read individual chunks from a stream. Return value A ReadableStreamDefaultReader or ReadableStreamBYOBReader object instance, depending on the mode value. Exceptions RangeError The provided mode value is not "byob" or
undefined. TypeError The stream you are trying ...
...ther part of the UI. function fetchStream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always
undefined when done is true. if (done) { console.log("Stream complete"); para.textContent = value; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Received ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list2.ap...
ReadableStreamDefaultReader.read() - Web APIs
faultReader.read(); Parameters None. Return value A Promise, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: If a chunk is available, the promise will be fulfilled with an object of the form { value: theChunk, done: false }. If the stream becomes closed, the promise will be fulfilled with an object of the form { value:
undefined, done: true }. If the stream becomes errored, the promise will be rejected with the relevant error. Exceptions TypeError The source object is not a ReadableStreamDefaultReader, or the stream has no owner. Examples Example 1 - simple example This example shows the basic API usage, but doesn't try to deal with complications like stream chunks not ending on line boundaries for example. I...
...ther part of the UI. function fetchStream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always
undefined when done is true. if (done) { console.log("Stream complete"); para.textContent = result; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Received ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list2.a...
Window.prompt() - Web APIs
e user to input some text. Syntax result = window.prompt(message, default); Parameters message Optional A string of text to display to the user. Can be omitted if there is nothing to show in the prompt window. default Optional A string containing the default value displayed in the text input field. Note that in Internet Explorer 7 and 8, if you do not provide this parameter, the string "
undefined" is the default value. Return value A string containing the text entered by the user, or null. Example let sign = prompt("What's your sign?"); if (sign.toLowerCase() == "scorpio") { alert("Wow! I'm a Scorpio too!"); } // there are many ways to use the prompt feature sign = window.prompt(); // open the blank prompt window sign = prompt(); // open the blank prompt window sign = wind...
...pport 12Firefox Full support 1IE Full support 4Notes Full support 4Notes Notes This function has no effect in the Modern UI/Metro version of Internet Explorer for Windows 8. It does not display a prompt to the user, and always returns
undefined. It is not clear whether this is a bug or intended behavior. Desktop versions of IE do implement this function.Opera Full support 3Notes Full support 3Notes Notes Starting with Opera 33, this method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modals.Safari ...
Window.scrollX - Web APIs
operty is an alias for the scrollX property: window.pageXOffset == window.scrollX; // always true For cross-browser compatibility, use window.pageXOffset instead of window.scrollX. Additionally, older versions of Internet Explorer (< 9) do not support either property and must be worked around by checking other non-standard properties. ...
... instead of window.scrollX. Additionally, older versions of Internet Explorer (< 9) do not support either property and must be worked around by checking other non-standard properties. A fully compatible example: var x = (window.pageXOffset !==
undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft; var y = (window.pageYOffset !==
undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop; Specification Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'window.scrollX' in that specification. Working Draft ...
WindowOrWorkerGlobalScope.setInterval() - Web APIs
} : vCallback, nDelay); }; window.setInterval.isPolyfill = true; } Another possibility is to use an anonymous function to call your callback, although this solution is a bit more expensive. Example: var intervalID = setInterval(function() { myFunc('one', 'two', 'three'); }, 1000); Another possibility is to use function's bind. Example: var intervalID = setInterval(function(arg1) {}.bind(
undefined, 10), 1000); Inactive tabs Requires Gecko 5.0(Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2) Starting in Gecko 5.0 (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2), intervals are clamped to fire no more often than once per second in inactive tabs. The "this" problem When you pass a method to setInterval() or any other function, it is invoked with the wrong this value. This problem is...
...roblem, in fact, is the same for both timers): myArray = ['zero', 'one', 'two']; myArray.myMethod = function (sProperty) { alert(arguments.length > 0 ? ...
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
our callback, but this solution is a bit more expensive. Example: var intervalID = setTimeout(function() { myFunc('one', 'two', 'three'); }, 1000); The above example can also be written with the help of an arrow function: var intervalID = setTimeout(() => { myFunc('one', 'two', 'three'); }, 1000); Yet another possibility is to use function's bind. Example: setTimeout(function(arg1){}.bind(
undefined, 10), 1000); The "this" problem When you pass a method to setTimeout() (or any other function, for that matter), it will be invoked with a this value that may differ from your expectation. This issue is explained in detail in the JavaScript reference. Explanation Code executed by setTimeout() is called from an execution context separate from the function from which setTimeout was called. The...
...(); // prints "zero,one,two" myArray.myMethod(1); // prints "one" The above works because when myMethod is called, its this is set to myArray by the call, so within the function, this[sProperty] is equivalent to myArray[sProperty]. However, in the following: setTimeout(myArray.myMethod, 1.0*1000); // prints "[object Window]" after 1 second setTimeout(myArray.myMethod, 1.5*1000, '1'); // prints "
undefined" after 1.5 seconds The myArray.myMethod function is passed to setTimeout, then when it's called, its this is not set so it defaults to the window object. There's also no option to pass a thisArg to setTimeout as there is in Array methods like forEach, reduce, etc. and as shown below, using call to set this doesn't work either. setTimeout.call(myArray, myArray.myMethod, 2.0*1000); // error: "NS_...
WorkerGlobalScope.self - Web APIs
cope, or ServiceWorkerGlobalScope. Syntax var selfRef = self; Value A global scope object (differs depending on the type of worker you are dealing with, as indicated above). ...
...rviceWorkerGlobalScope. Syntax var selfRef = self; Value A global scope object (differs depending on the type of worker you are dealing with, as indicated above). ...
ARIA: row role - Accessibility
like a plain cell, the rowheader role establishes a relationship between it and all cells in the corresponding row. States and properties aria-expanded state The aria-expanded attribute, which defines the state of the row, can take one of three values, or be omitted: aria-expanded="true: Row is currently expanded. aria-expanded="false": Row is currently collapsed. aria-expended="
undefined" or the attribute is missing: The row is neither expandable nor collapsible. If the element with the aria-expanded attribute controls the expansion of another grouping container that is not 'owned by' the element, the author should reference the container by using the aria-controls attribute. aria-selected state Only relevant if the row is in an interactive container, such as a grid or tr...
...he container by using the aria-controls attribute. aria-selected state Only relevant if the row is in an interactive container, such as a grid or treegrid, but not relevant if the row is in a table. The aria-selected attribute can take one of three values, or be omitted: aria-selected="true: Row is currently selected aria-selected="false": Row is not currently selected. aria-selected="
undefined" or the attribute is missing: The row is not selectable. aria-colindex attribute The aria-colindex attribute is only needed if columns are hidden from the DOM. It is generally placed on row children, rather than on the row itself. If the columns displayed are contiguous, then it can be placed on the row. The attribute takes as its value an integer between 1 and the total number of c...
max-width - CSS: Cascading Style Sheets
refox for AndroidOpera for AndroidSafari on iOSSamsung Internetmax-widthChrome Full support 1Edge Full support 12Firefox Full support 1Notes Full support 1Notes Notes CSS 2.1 leaves the behavior of max-width with table
undefined. Firefox supports applying max-width to table elements.IE Full support 7Opera Full support 4Notes Full support 4Notes Notes CSS 2.1 leaves the behavior of max-width with table
undefined. Opera supports applying max-width to table elements.Safari F...
...Full support 1WebView Android Full support 4.4Chrome Android Full support 18Firefox Android Full support 4Notes Full support 4Notes Notes CSS 2.1 leaves the behavior of max-width with table
undefined. Firefox supports applying max-width to table elements.Opera Android Full support 14Safari iOS Full support 1Samsung Internet Android Full support 1.0fit-content ExperimentalChrome Full support 46 Full s...
min-width - CSS: Cascading Style Sheets
refox for AndroidOpera for AndroidSafari on iOSSamsung Internetmin-widthChrome Full support 1Edge Full support 12Firefox Full support 1Notes Full support 1Notes Notes CSS 2.1 leaves the behavior of min-width with table
undefined. Firefox supports applying min-width to table elements.IE Full support 7Opera Full support 4Notes Full support 4Notes Notes CSS 2.1 leaves the behavior of min-width with table
undefined. Opera supports applying min-width to table elements.Safari F...
...Full support 1WebView Android Full support 4.4Chrome Android Full support 18Firefox Android Full support 4Notes Full support 4Notes Notes CSS 2.1 leaves the behavior of min-width with table
undefined. Firefox supports applying min-width to table elements.Opera Android Full support 14Safari iOS Full support 1Samsung Internet Android Full support 1.0autoChrome Full support 21Notes Full support ...
Standard metadata names - HTML: Hypertext Markup Language
r. initial-scale A positive number between 0.0 and 10.0 Defines the ratio between the device width (device-width in portrait mode or device-height in landscape mode) and the viewport size. maximum-scale A positive number between 0.0 and 10.0 Defines the maximum amount to zoom in. It must be greater or equal to the minimum-scale or the behaviour is
undefined. Browser settings can ignore this rule and iOS10+ ignores it by default. minimum-scale A positive number between 0.0 and 10.0 Defines the minimum zoom level. It must be smaller or equal to the maximum-scale or the behaviour is
undefined. Browser settings can ignore this rule and iOS10+ ignores it by default. user-scalable yes or no If set to no, t...
... needs to access the page in order to read these rules. To prevent bandwidth consumption, use a robots.txt file. If you want to remove a page, noindex will work, but only after the robot visits the page again. Ensure that the robots.txt file is not preventing revisits. Some values are mutually exclusive, like index and noindex, or follow and nofollow. In these cases the robot's behaviour is
undefined and may vary between them. Some crawler robots, like Google, Yahoo and Bing, support the same values for the HTTP header X-Robots-Tag; this allows non-HTML documents like images to use these rules. Specifications Specification HTML Living StandardThe definition of 'standard metadata names' in that specification. CSS Color Adjustment Module Level 1The d...
Working with objects - JavaScript
Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it. So, for example, you could access the properties of the myCar object as follows: myCar['mak...
... = 'Mustang'; myCar.year = 1969; The above example could also be written using an object initializer, which is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}): var myCar = { make: 'Ford', model: 'Mustang', year: 1969 }; Unassigned properties of an object are
undefined (and not null). myCar.color; //
undefined Properties of JavaScript objects can also be accessed or set using a bracket notation (for more details see property accessors). Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it. So, for example, you could access the properties of the myCar object as follows: myCar['make'] = 'Ford'; myCar['model'] = 'Mustang'; m...
Public class fields - JavaScript
elds are declared using the static keyword. They are added to the class constructor at the time of class evaluation using Object.defineProperty(). They are accessed again from the class constructor. class ClassWithStaticField { static staticField = 'static field' } console.log(ClassWithStaticField.staticField) // expected output: "static field" Fields without initializers are initialized to
undefined. class ClassWithStaticField { static staticField } console.assert(ClassWithStaticField.hasOwnProperty('staticField')) console.log(ClassWithStaticField.staticField) // expected output: "
undefined" Public static fields are not reinitialized on subclasses, but can be accessed via the prototype chain. class ClassWithStaticField { static baseStaticField = 'base field' } class SubClassWithStat...
... added with Object.defineProperty() either at construction time in the base class (before the constructor body runs), or just after super() returns in a subclass. class ClassWithInstanceField { instanceField = 'instance field' } const instance = new ClassWithInstanceField() console.log(instance.instanceField) // expected output: "instance field" Fields without initializers are initialized to
undefined. class ClassWithInstanceField { instanceField } const instance = new ClassWithInstanceField() console.assert(instance.hasOwnProperty('instanceField')) console.log(instance.instanceField) // expected output: "
undefined" Like properties, field names may be computed. const PREFIX = 'prefix' class ClassWithComputedFieldName { [`${PREFIX}Field`] = 'prefixed field' } const instance = new Cl...
Warning: JavaScript 1.6's for-each-in loops are deprecated - JavaScript
10 // 20 // 30 } Alternative standard syntax This is now possible with for...of (ES2015) loops as well. ...
...20 // 30 } Iterating over a null-able array for each...in does nothing if the specified value is null or
undefined, but for...of will throw an exception in these cases. Deprecated syntax function func(array) { for each (var x in array) { console.log(x); } } func([10, 20]); // 10 // 20 func(null); // prints nothing func(
undefined); // prints nothing Alternative standard syntax To rewrite for each...in statements so that values can be null or
undefined with for...of as well, you need to guard around for...of. function func(array) { if (array) { for (var x of array) { console.log(x); } } } func([10, 20]); // 10 // 20 func(null); // prints nothing func(unde...
getter - JavaScript
another get or with a data entry for the same property ({ get x() { }, get x() { } } and { x: ..., get x() { } } are forbidden). Examples Defining a getter on new objects in object initializers This will create a pseudo-property latest for object obj, which will return the last array item in log. const obj = { log: ['example','test'], get latest() { if (this.log.length === 0) return
undefined; return this.log[this.log.length - 1]; } } console.log(obj.latest); // "test" Note that attempting to assign a value to latest will not change it. Deleting a getter using the delete operator If you want to remove the getter, you can just delete it: delete obj.latest; Defining a getter on existing objects using defineProperty To append a getter to an existing object later at any time...
...ce between the two when used on classes. When using get the property will be defined on the instance's prototype, while using Object.defineProperty() the property will be defined on the instance it is applied to. class Example { get hello() { return 'world'; } } const obj = new Example(); console.log(obj.hello); // "world" console.log(Object.getOwnPropertyDescriptor(obj, 'hello')); //
undefined console.log( Object.getOwnPropertyDescriptor( Object.getPrototypeOf(obj), 'hello' ) ); // { configurable: true, enumerable: false, get: function get hello() { return 'world'; }, set:
undefined } Specifications Specification ECMAScript (ECMA-262)The definition of 'Method definitions' in that specification. ...
Array() constructor - JavaScript
case only applies to JavaScript arrays created with the Array constructor, not array literals created with the bracket syntax. arrayLength If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual
undefined values). If the argument is any other number, a RangeError exception is thrown. Examples Array literal notation Arrays can be created using the literal notation: let fruits = ['Apple', 'Banana']; console.log(fruits.length); // 2 console.log(fruits[0]); // "Apple" Array constructor with a single parameter Arrays can be created using a constructor with a single number parameter. An arr...
... ['Apple', 'Banana']; console.log(fruits.length); // 2 console.log(fruits[0]); // "Apple" Array constructor with a single parameter Arrays can be created using a constructor with a single number parameter. An array with its length property set to that number and the array elements are empty slots. let fruits = new Array(2); console.log(fruits.length); // 2 console.log(fruits[0]); //
undefined Array constructor with multiple parameters If more than one argument is passed to the constructor, a new Array with the given elements is created. let fruits = new Array('Apple', 'Banana'); console.log(fruits.length); // 2 console.log(fruits[0]); // "Apple" Specifications Specification ECMAScript (ECMA-262)The definition of 'Array constructor' in that specification. ...
Array.prototype.reduce() - JavaScript
Let O be ? ToObject(this value). var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")). var len = o.length >>> 0; // Steps 3, 4, 5, 6, 7 var k = 0; var value; if (arguments.length >= 2) { ...
...y ' + 'with no initial value' ); } value = o[k++]; } // 8. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). // b. Let kPresent be ? HasProperty(O, Pk). // c. If kPresent is true, then // i. Let kValue be ? Get(O, Pk). // ii. Let accumulator be ? Call( // callbackfn,
undefined, // << accumulator, kValue, k, O >>). if (k in o) { value = callback(value, o[k], k, o); } // d. Increase k by 1. k++; } // 9. Return accumulator. return value; } }); } Caution: If you need to support truly obsolete JavaScript engines that do not support Object.defineProperty(), it is best not to polyfill Arra...
Array.prototype.findIndex() - JavaScript
ge case alert: Unlike other array methods such as Array.some(), callback is run even for indexes with unassigned values. callback is invoked with three arguments: The value of the element The index of the element The Array object being traversed If a thisArg parameter is passed to findIndex(), it will be used as the this inside each invocation of the callback. If it is not provided, then
undefined is used. The range of elements processed by findIndex() is set before the first invocation of callback. callback will not process the elements appended to the array after the call to findIndex() begins. If an existing, unvisited element of the array is changed by callback, its value passed to the callback will be the value at the time findIndex() visits the element's index. Elements that are de...
...ot defined'); } var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")). var len = o.length >>> 0; // 3. If IsCallable(predicate) is false, throw a TypeError exception. if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } // 4. If thisArg was supplied, let T be thisArg; else let T be
undefined. var thisArg = arguments[1]; // 5. Let k be 0. var k = 0; // 6. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). // b. Let kValue be ? Get(O, Pk). // c. Let testResult be ToBoolean(? Call(predicate, T, << kValue, k, O >>)). // d. If testResult is true, return k. var kValue = o[k]; if (predicate.c...
Array.prototype.forEach() - JavaScript
x [, array]])[, thisArg]) Parameters callback Function to execute on each element. It accepts between one and three arguments: currentValue The current element being processed in the array. index Optional The index currentValue in the array. array Optional The array forEach() was called upon. thisArg Optional Value to use as this when executing callback. Return value
undefined. Description forEach() calls a provided callback function once for each element in an array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized. (For sparse arrays, see example below.) callback is invoked with three arguments: the value of the element the index of the element the Array object being traversed If a thisArg parameter is pr...
...allback will be the value at the time forEach() visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. using shift()) during the iteration, later elements will be skipped. (See this example, below.) forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value
undefined and is not chainable. The typical use case is to execute side effects at the end of a chain. forEach() does not mutate the array on which it is called. (However, callback may do so) There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool. Early termination may be accomplished with: A simple for...
Array.isArray() - JavaScript
Return value true if the value is an Array; otherwise, false. Description If the value is an Array, true is returned; otherwise, false is. See the article "Determining with absolute accuracy whether or not a JavaScript object is an array" for more details. ...
... var iframe = document.createElement('iframe'); document.body.appendChild(iframe); xArray = w...
Array.of() - JavaScript
a new Array instance from a variable number of arguments, regardless of number or type of the arguments. The difference between Array.of() and the Array constructor is in the handling of integer arguments: Array.of(7) creates an array with a single element, 7, whereas Array(7) creates an empty array with a length property of 7 (Note: this implies an array of 7 empty slots, not slots with actual
undefined values). Array.of(7); // [7] Array.of(1, 2, 3); // [1, 2, 3] Array(7); // array of 7 empty slots Array(1, 2, 3); // [1, 2, 3] Syntax Array.of(element0[, element1[, ...[, elementN]]]) Parameters elementN Elements used to create the array. Return value A new Array instance. Description This function is part of the ECMAScript 2015 standard. For more information, see...
...ode before any other code will create Array.of() if it's not natively available. if (!Array.of) { Array.of = function() { return Array.prototype.slice.call(arguments); // Or let vals = []; for(let prop in arguments){ vals.push(arguments[prop]); } return vals; } } Examples Using Array.of Array.of(1); // [1] Array.of(1, 2, 3); // [1, 2, 3] Array.of(
undefined); // [
undefined] Specifications Specification ECMAScript (ECMA-262)The definition of 'Array.of' in that specification. ...
Array.prototype.pop() - JavaScript
last element from an array and returns that element. This method changes the length of the array. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax arrName.pop() Return value The removed element from the array;
undefined if the array is empty. Description The pop method removes the last element from an array and returns that value to the caller. pop is intentionally generic; this method can be called or applied to objects resembling arrays. Objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner. If ...
... method removes the last element from an array and returns that value to the caller. pop is intentionally generic; this method can be called or applied to objects resembling arrays. Objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner. If you call pop() on an empty array, it returns
undefined. Array.prototype.shift() has similar behavior to pop, but applied to the first element in an array. Examples Removing the last element of an array The following code creates the myFish array containing four elements, then removes its last element. var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; var popped = myFish.pop(); console.log(myFish); // ['angel', 'clown', 'mandarin' ] con...
Array.prototype.shift() - JavaScript
element from an array and returns that removed element. This method changes the length of the array. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax arr.shift() Return value The removed element from the array;
undefined if the array is empty. Description The shift method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value. If the length property is 0,
undefined is returned. shift is intentionally generic; this method can be called or applied to objects resembling arrays. Objects which do not contain a length property reflecting the last in...
...mandarin', 'surgeon'] console.log('Removed this element:', shifted); // Removed this element: angel Using shift() method in while loop The shift() method is often used in condition inside while loop. In the following example every iteration will remove the next element from an array, until it is empty: var names = ["Andrew", "Edward", "Paul", "Chris" ,"John"]; while( (i = names.shift()) !==
undefined ) { console.log(i); } // Andrew, Edward, Paul, Chris, John Specifications Specification ECMAScript (ECMA-262)The definition of 'Array.prototype.shift' in that specification. ...
Array.prototype.some() - JavaScript
oked only for indexes of the array with assigned values. It is not invoked for indexes which have been deleted or which have never been assigned values. callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed. If a thisArg parameter is provided to some(), it will be used as the callback's this value. Otherwise, the value
undefined will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. some() does not mutate the array on which it is called. The range of elements processed by some() is set before the first invocation of callback. Elements appended to the array after the call to some() begins will not be visited...
...or have their original values and that fun.call evaluates to the original value of Function.prototype.call(). ...
Array.prototype.toLocaleString() - JavaScript
// host environment's current locale (this is // derived in an implementation-defined way). // NOTE: In this case, we will use a comma var separator = ','; // 4. If len is zero, return the empty String. if (len === 0) { return ''; } // 5. Let firstElement be ? Get(A, "0"). var firstElement = a[0]; // 6. If firstElement is
undefined or null, then // a.Let R be the empty String. // 7. Else, // a. Let R be ? // ToString(? // Invoke( // firstElement, // "toLocaleString", // << locales, options >> // ) // ) var r = firstElement == null ? '' : firstElement.toLocaleString(locales, options); // 8. Let k be 1. ...
...'' : firstElement.toLocaleString(locales, options); // 8. Let k be 1. var k = 1; // 9. Repeat, while k < len while (k < len) { // a. Let S be a String value produced by // concatenating R and separator. var s = r + separator; // b. Let nextElement be ? Get(A, ToString(k)). var nextElement = a[k]; // c. If nextElement is
undefined or null, then // i. Let R be the empty String. // d. Else, // i. Let R be ? // ToString(? // Invoke( // nextElement, // "toLocaleString", // << locales, options >> // ) // ) r = nextElement == null ? '' : nextElement.toLocaleString(locales, options); ...
Error.prototype.stack - JavaScript
diately before the at (@) sign. While an object (or array, etc.) would appear in the converted form "[object Object]", and as such could not be evaluated back into the actual objects, scalar values could be retrieved (though it may be -- it is still possible in Firefox 14 -- easier to use arguments.callee.caller.arguments, as could the function name be retrieved by arguments.callee.caller.name). "
undefined" is listed as "(void 0)". Note that if string arguments were passed in with values such as "@", "(", ")" (or if in file names), you could not easily rely on these for breaking the line into its component parts. Thus, in Firefox 14 and later this is less of an issue. Different browsers set this value at different times. For example, Firefox sets it when creating an Error object, while PhantomJS s...
...eem to match the PhantomJS implementation. Examples Using the stack property The following HTML markup demonstrates the use of stack property. ...
Function.prototype.apply() - JavaScript
ory. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax func.apply(thisArg, [ argsArray]) Parameters thisArg The value of this provided for the call to func. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and
undefined will be replaced with the global object, and primitive values will be boxed. This argument is required. argsArray Optional An array-like object, specifying the arguments with which func should be called, or null or
undefined if no arguments should be provided to the function. Starting with ECMAScript 5 these arguments can be a generic array-like object instead of an array. See below for b...
...ay. See below for browser compatibility information. Return value The result of calling the function with the specified this value and arguments. Description Note: While the syntax of this function is almost identical to that of call(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments. Note: When the first argument is
undefined or null a similar outcome can be achieved using the array spread syntax. You can assign a different this object when calling an existing function. this refers to the current object (the calling object). With apply, you can write a method once, and then inherit it in another object, without having to rewrite the method for the new object. apply is very similar to call(), except for the type of ...
Function.prototype.call() - JavaScript
to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax func.call([thisArg[, arg1, arg2, ...argN]]) Parameters thisArg Optional The value to use as this when calling func. Caution: In certain cases, thisArg may not be the actual value seen by the method. If the method is a function in non-strict mode, null and
undefined will be replaced with the global object, and primitive values will be converted to objects. arg1, arg2, ...argN Optional Arguments for the function. Return value The result of calling the function with the specified this value and arguments. Description The call() allows for a function/method belonging to one object to be assigned and called for a different object. call() provides a n...
...out specifying the first argument In the example below, we invoke the display function without passing the first argument. If the first argument is not passed, the value of this is bound to the global object. var sData = 'Wisen'; function display() { console.log('sData value is %s ', this.sData); } display.call(); // sData value is Wisen Caution: In strict mode, the value of this will be
undefined. See below. 'use strict'; var sData = 'Wisen'; function display() { console.log('sData value is %s ', this.sData); } display.call(); // Cannot read the property of 'sData' of
undefined Specifications Specification ECMAScript (ECMA-262)The definition of 'Function.prototype.call' in that specification. ...
Generator.prototype.next() - JavaScript
xamples Using next() The following example shows a simple generator and the object that the next method returns: function* gen() { yield 1; yield 2; yield 3; } const g = gen(); // "Generator { }" g.next(); // "Object { value: 1, done: false }" g.next(); // "Object { value: 2, done: false }" g.next(); // "Object { value: 3, done: false }" g.next(); // "Object { value:
undefined, done: true }" Using next() with a list function* getPage(pageSize = 1, list) { let output = []; let index = 0; while (index < list.length) { output = []; for (let i = index; i < index + pageSize; i++) { if (list[i]) { output.push(list[i]); } } yield output; index += pageSize; } } list = [1, 2, 3, 4, 5, 6, 7, 8] var page = getPage(3, list); ...
... Note that the first call does not log anything, because the generator was not yielding anything initially. function* gen() { while (true) { let value = yield null; console.log(value); } } const g = gen(); g.next(1); // "{ value: null, done: false }" g.next(2); // 2 // "{ value: null, done:...
Generator.prototype.return() - JavaScript
value) Parameters value The value to return. Return value The value that is given as an argument. Examples Using return() The following example shows a simple generator and the return method. function* gen() { yield 1; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.return('foo'); // { value: "foo", done: true } g.next(); // { value:
undefined, done: true } If return(value) is called on a generator that is already in "completed" state, the generator will remain in "completed" state. If no argument is provided, the value property of returned object is the same as if .next(). If an argument is provided, it will be set to the value of the value property of the returned object. function* gen() { yield 1; yield 2; yield 3; } cons...
...argument is provided, the value property of returned object is the same as if .next(). If an argument is provided, it will be set to the value of the value property of the returned object. function* gen() { yield 1; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.next(); // { value: 2, done: false } g.next(); // { value: 3, done: false } g.next(); // { value:
undefined, done: true } g.return(); // { value:
undefined, done: true } g.return(1); // { value: 1, done: true } Specifications Specification ECMAScript (ECMA-262)The definition of 'Generator.prototype.return' in that specification. ...
Intl.DateTimeFormat() constructor - JavaScript
tored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax new Intl.DateTimeFormat([locales[, options]]) Parameters locales Optional A string with a BCP 47 language tag, or an array of such strings. To use the browser's default locale, omit this argument or pass
undefined. Unicode extension are supported (for example "en-US-u-ca-buddhist"). For the general form and interpretation of the locales argument, see the Intl page. The following Unicode extension keys are allowed: nu Numbering system. Possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mym...
..."2-digit". minute The representation of the minute. Possible values are "numeric", "2-digit". second The representation of the second. Possible values are "numeric", "2-digit". timeZoneName The representation of the time zone name. Possible values are: "long" (e.g., British Summer Time) "short" (e.g., GMT+1) The default value for each date-time component property is
undefined, but if all component properties are
undefined, then year, month, and day are assumed to be "numeric". Examples Using DateTimeFormat In basic use without specifying a locale, DateTimeFormat uses the default locale and default options. var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); // toLocaleString without arguments depends on the implementation, // the default locale, and the defa...
Intl - JavaScript
best-supported locale determined by evaluating each of them in order and comparing against the locales supported by the implementation) by passing an array (or array-like object, with a length property and corresponding indexed elements) whose elements are either Intl.Locale objects or values that convert to Unicode BCP 47 locale identifier strings. If the locales argument is not provided or is
undefined, the runtime's default locale is used. A Unicode BCP 47 locale identifier consists of a language code, (optionally) a script code, (optionally) a region (or country) code, (optionally) one or more variant codes, and (optionally) one or more extension sequences, with all present components separated by hyphens. Locale identifiers are case-insensitive ASCII. However, it's conventional t...
...bset of the keys defined for the Unicode extension, and the supported values often depend on the language tag. For example, the "co" key (collation) is only supported by Collator, and its "phonebk" value is only supported for German. options argument The options argument must be an object with properties that vary between constructors and functions. If the options argument is not provided or is
undefined, default values are used for all properties. One property is supported by all language sensitive constructors and functions: The localeMatcher property, whose value must be a string "lookup" or "best fit" and which selects one of the locale matching algorithms described above. Examples Formatting dates and numbers You can use Intl to format dates and numbers in a form that's conventional for ...
JSON.parse() - JavaScript
ely walk the resulting structure so // that modifications can be made. var k; var v; var value = holder[key]; if (value && typeof value === "object") { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !==
undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequenc...
...fore being returned. Specifically, the computed value and all its properties (beginning with the most nested properties and proceeding to the original value itself) are individually run through the reviver. Then it is called, with the object containing the property being processed as this, and with the property name as a string, and the property value as arguments. If the reviver function returns
undefined (or returns no value, for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the reviver only transforms some values and not others, be certain to return all untransformed values as-is, otherwise, they will be deleted from the resulting object. JSON.parse('{"p": 5}', (key, value) => ...
JSON - JavaScript
avaScript string literals is a SyntaxError. Consider this example where JSON.parse() parses the string as JSON and eval executes the string as JavaScript: let code = '"\u2028\u2029"' JSON.parse(code) // evaluates to "\u2028\u2029" in all engines eval(code) // throws a SyntaxError in old engines Other differences include allowing only double-quoted strings and having no provisions for
undefined or comments. For those who wish to use a more human-friendly configuration format based on JSON, there is JSON5, used by the Babel compiler, and the more commonly used YAML. Full JSON syntax The full JSON syntax is as follows: JSON = null or true or false or JSONNumber or JSONString or JSONObject or JSONArray JSONNumber = - PositiveNumber or PositiveNumber Positi...
... between JavaScript and JSON, cause a SyntaxError to be thrown. The reviver option allows for interpreting what the replacer has used to stand in for other datatypes. JSON.stringify(value[, replacer[, space]]) Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner. By default, all instances of
undefined are replaced with null, and other unsupported native data types are censored. The replacer option allows for specifying other behavior. Examples Example JSON { "browsers": { "firefox": { "name": "Firefox", "pref_url": "about:config", "releases": { "1": { "release_date": "2004-11-09", "status": "retired", "engine": "Gecko", ...
Object() constructor - JavaScript
The Object constructor creates an object wrapper for the given value. If the value is null or
undefined, it will create and return an empty object. Otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value. When called in a non-constructor context, Object behaves identically to new Object(). Syntax new Object() new Object(value) Parameters value Any value. ...
...ject of a Type that corresponds to the given value. If the value is an object already, it will return the value. When called in a non-constructor context, Object behaves identically to new Object(). Syntax new Object() new Object(value) Parameters value Any value. Examples Creating a new Object let o = new Object() o.foo = 42 console.log(o) // Object { foo: 42 } Using Object given
undefined and null types The following examples store an empty Object object in o: let o = new Object() let o = new Object(
undefined) let o = new Object(null) Specifications Specification ECMAScript (ECMA-262)The definition of 'Object constructor' in that specification. ...
Object.prototype.constructor - JavaScript
uous line of code. Take the following case: the object has the create() method to create itself. function Parent() { /* ... */ } function CreatedConstructor() { Parent.call(this) } CreatedConstructor.prototype = Object.create(Parent.prototype) CreatedConstructor.prototype.create = function create() { return new this.constructor() } new CreatedConstructor().create().create() // TypeError
undefined is not a function since constructor === Parent In the example above the exception will be shown since the constructor links to Parent. To avoid this, just assign the necessary constructor you are going to use. function Parent() { /* ... */ } function CreatedConstructor() { /* ... */ } CreatedConstructor.prototype = Object.create(Parent.prototype) CreatedConstructor.prototype.constructor = Cre...
...Child = Object.assign(ParentWithStatic) // Notice that we assign it before we create(...) a prot...
Object.prototype.hasOwnProperty() - JavaScript
wnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check for a property in the object's prototype chain. If an Object is an Array, hasOwnProperty method can check whether an index exists. Note hasOwnProperty returns true even if the value of the property is null or
undefined. ...
...irect property of that object; unlike the in operator, this method does not check for a property in the object's prototype chain. If an Object is an Array, hasOwnProperty method can check whether an index exists. Note hasOwnProperty returns true even if the value of the property is null or
undefined. o = new Object(); o.propOne = null; o.hasOwnProperty('propOne'); // returns true o.propTwo =
undefined; o.hasOwnProperty('propTwo'); // returns true Examples Using hasOwnProperty to test for a property's existence The following example determines whether the o object contains a property named prop: o = new Object(); o.hasOwnProperty('prop'); // returns false o.prop = 'exists'; o.hasOwnProperty('prop'); // returns true Direct vs. inherited properties The following example differentiat...
Object.prototype.toString() - JavaScript
y default, the toString() method is inherited by every object descended from Object. If this method is not overridden in a custom object, toString() returns "[object type]", where type is the object type. The following code illustrates this: const o = new Object(); o.toString(); // returns [object Object] Note: Starting in JavaScript 1.8.5, toString() called on null returns [object Null], and
undefined returns [object
Undefined], as defined in the 5th Edition of ECMAScript and subsequent Errata. See Using toString() to detect object class. Parameters For Numbers and BigInts toString() takes an optional parameter radix the value of radix must be minimum 2 and maximum 36. By using radix you can also convert base 10 numbers (like 1,2,3,4,5,.........) to another base numbers, in example belo...
...h every object, you need to call Function.prototype.call() or Function.prototype.apply() on it, passing the object you want to inspect as the first parameter (called thisArg). const toString = Object.prototype.toString; toString.call(new Date); // [object Date] toString.call(new String); // [object String] toString.call(Math); // [object Math] // Since JavaScript 1.8.5 toString.call(
undefined); // [object
Undefined] toString.call(null); // [object Null] Using toString() in this way is unreliable; objects can change the behavior of Object.prototype.toString() by defining a Symbol.toStringTag property, leading to unexpected results. For example: const myDate = new Date(); Object.prototype.toString.call(myDate); // [object Date] myDate[Symbol.toStringTag] = 'myDate'; Obj...
handler.getOwnPropertyDescriptor() - JavaScript
yntax const p = new Proxy(target, { getOwnPropertyDescriptor: function(target, prop) { } }); Parameters The following parameters are passed to the getOwnPropertyDescriptor() method. this is bound to the handler. target The target object. prop The name of the property whose description should be retrieved. Return value The getOwnPropertyDescriptor() method must return an object or
undefined. Description The handler.getOwnPropertyDescriptor() method is a trap for Object.getOwnPropertyDescriptor(). Interceptions This trap can intercept these operations: Object.getOwnPropertyDescriptor() Reflect.getOwnPropertyDescriptor() Invariants If the following invariants are violated, the proxy will throw a TypeError: getOwnPropertyDescriptor() must return an object or
undefined. A...
... ...
ReferenceError() constructor - JavaScript
eferenced. Syntax new ReferenceError([message[, fileName[, lineNumber]]]) Parameters message Optional Optional. Human-readable description of the error. fileName Optional Optional. The name of the file containing the code that caused the exception. lineNumber Optional Optional. The line number of the code that caused the exception. ...
...e description of the error. fileName Optional Optional. The name of the file containing the code that caused the exception. lineNumber Optional Optional. The line number of the code that caused the exception. ...
ReferenceError - JavaScript
Name Path to file that raised this error. Inherited from Error. ReferenceError.prototype.lineNumber Line number in file that raised this error. Inherited from Error. ReferenceError.prototype.columnNumber Column number in line that raised this error. Inherited from Error. ReferenceError.prototype.stack Stack trace. Inherited from Error. ...
...ed this error. Inherited from Error. ReferenceError.prototype.columnNumber Column number in line that raised this error. Inherited from Error. ReferenceError.prototype.stack Stack trace. Inherited from Error. ...
Reflect.apply() - JavaScript
called. Return value The result of calling the given target function with the specified this value and arguments. Exceptions A TypeError, if the target is not callable. Description In ES5, you typically use the Function.prototype.apply() method to call a function with a given this value and arguments provided as an array (or an array-like object). ...
...et is not callable. Description In ES5, you typically use the Function.prototype.apply() method to call a function with a given this value and arguments provided as an array (or an array-like object). Function.prototype.apply.call(Math.floor,
undefined, [1.75]); With Reflect.apply() this becomes less verbose and easier to understand. Examples Using Reflect.apply() Reflect.apply(Math.floor,
undefined, [1.75]); // 1; Reflect.apply(String.fromCharCode,
undefined, [104, 101, 108, 108, 111]) // "hello" Reflect.apply(RegExp.prototype.exec, /ab/, ['confabulation']).index // 4 Reflect.apply(''.charAt, 'ponies', [3]) // "i" Specifications Specification ECMAScript (ECMA-262)The definition of 'Reflect.apply' in that specification. ...
Reflect.construct() - JavaScript
strate below: function func1(a, b, c, d) { console.log(arguments[3]); } function func2(d, e, f, g) { consol.log(arguments[3]); } let obj1 = Reflect.construct(func1, ['I', 'Love', 'my', 'India']) obj1 However, while the end result is the same, there is one important difference in the process. When using Object.create() and Function.prototype.apply(), the new.target operator will point to
undefined within the function used as the constructor, since the new keyword is not being used to create the object. When invoking Reflect.construct(), on the other hand, the new.target operator will point to the newTarget parameter if supplied, or target if not. function OneClass() { console.log('OneClass') console.log(new.target) } function OtherClass() { console.log('OtherClass') conso...
...) { console.log('OtherClass') console.log(new.target) } let obj1 = Reflect.construct(OneClass, args) // Output: // OneClass // function OneClass { ... } let obj2 = Reflect.construct(OneClass, args, OtherClass) // Output: // OneClass // function OtherClass { ... } let obj3 = Object.create(OtherClass.prototype); OneClass.apply(obj3, args) // Output: // OneClass //
undefined Examples Using Reflect.construct() let d = Reflect.construct(Date, [1776, 6, 4]) d instanceof Date // true d.getFullYear() // 1776 Specifications Specification ECMAScript (ECMA-262)The definition of 'Reflect.construct' in that specification. ...
String.prototype.split() - JavaScript
rator)[0] is returned If limit is 0, [] is returned. Return value An Array of strings, split at each point where the separator occurs in the given string. Description When found, separator is removed from the string, and the substrings are returned in an array. If separator is a regular expression with capturing parentheses, then each time separator matches, the results (including any
undefined results) of the capturing parentheses are spliced into the output array. If the separator is an array, then that Array is coerced to a String and used as a separator. Examples Using split() When the string is empty, split() returns an array containing one empty string, rather than an empty array. If the string and separator are both empty strings, an empty array is returned. const myString ...
...tring, space) splitString(tempestString) splitString(monthString, comma) This example produces the following output: The original string is: "Oh brave new world that has such people in it." The separator is: " " The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it. The original string is: "Oh brave new world that has such people in it." The separator is: "
undefined" The array has 1 elements: Oh brave new world that has such people in it. The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec" The separator is: "," The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec Removing spaces from a string In the following example, split() looks for zero or more spaces, followed by a semicolon, followed...
Symbol.keyFor() - JavaScript
is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Symbol.keyFor(sym); Parameters sym Symbol, required. The symbol to find a key for. Return value A string representing the key for the given symbol if one is found on the global registry; otherwise,
undefined. ...
...ax Symbol.keyFor(sym); Parameters sym Symbol, required. The symbol to find a key for. Return value A string representing the key for the given symbol if one is found on the global registry; otherwise,
undefined. Examples Using keyFor var globalSym = Symbol.for('foo'); // create a new global symbol Symbol.keyFor(globalSym); // "foo" var localSym = Symbol(); Symbol.keyFor(localSym); //
undefined // well-known symbols are not symbols registered // in the global symbol registry Symbol.keyFor(Symbol.iterator) //
undefined Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.keyFor' in that specification. ...
Symbol.toStringTag - JavaScript
and more Built-in toStringTag symbols Object.prototype.toString.call(new Map()); // "[object Map]" Object.prototype.toString.call(function* () {}); // "[object GeneratorFunction]" Object.prototype.toString.call(Promise.resolve()); // "[object Promise]" // ... and more Custom classes default t...
...and more Built-in toStringTag symbols Object.prototype.toString.call(new Map()); // "[object Map]" Object.prototype.toString.call(function* () {}); // "[object GeneratorFunction]" Object.prototype.toString.call(Promise.resolve()); // "[object Promise]" // ... and more Custom classes default to object tag When creat...
TypedArray - JavaScript
rt index to an end index with a static value. See also Array.prototype.fill(). TypedArray.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). TypedArray.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function, or
undefined if not found. See also Array.prototype.find(). TypedArray.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). TypedArray.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). TypedArray.prototype.includes() Det...
... can still use named properties, just like with all objects. // Setting and getting using standard array syntax var int16 = new Int16Array(2); int16[0] = 42; console.log(int16[0]); // 42 // Indexed properties on prototypes are not consulted (Fx 25) Int8Array.prototype[20] = 'foo'; (new Int8Array(32))[20]; // 0 // even when out of bound Int8Array.prototype[20] = 'foo'; (new Int8Array(8))[20]; //
undefined // or with negative integers Int8Array.prototype[-1] = 'foo'; (new Int8Array(8))[-1]; //
undefined // Named properties are allowed, though (Fx 30) Int8Array.prototype.foo = 'bar'; (new Int8Array(32)).foo; // "bar" Specifications Specification ECMAScript (ECMA-262)The definition of 'TypedArray Objects' in that specification. ...
WeakRef.prototype.deref() - JavaScript
Notes See the Notes on WeakRefs section of the WeakRef page for some important notes. Examples Using deref See the Examples section of the WeakRef page for the complete example. ...
... Notes See the Notes on WeakRefs section of the WeakRef page for some important notes. Examples Using deref See the Examples section of the WeakRef page for the complete example. ...
isNaN() - JavaScript
lse. Description The necessity of an isNaN function Unlike all other possible values in JavaScript, it is not possible to rely on the equality operators (== and ===) to determine whether a value is NaN or not, because both NaN == NaN and NaN === NaN evaluate to false. Hence, the necessity of an isNaN function. Origin of NaN values NaN values are generated when arithmetic operations result in
undefined or unrepresentable values. Such values do not necessarily represent overflow conditions. A NaN also results from attempted coercion to numeric values of non-numeric values for which no primitive numeric value is available. For example, dividing zero by zero results in a NaN -- but dividing other numbers by zero does not. Confusing special-case behavior Since the very earliest versions of the i...
...xpression (x != x) is a more reliable way to test whether variable x is NaN or not, as the result is not subject to the false positives that make isNaN unreliable. ...
parseInt() - JavaScript
parseInt should not be used as a substitute for Math.floor(). parseInt understands exactly two signs: + for positive, and - for negative (since ECMAScript 1). It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string. If radix is
undefined, 0, or unspecified, JavaScript assumes the following: If the input string begins with "0x" or "0X" (a zero, followed by lowercase or uppercase X), radix is assumed to be 16 and the rest of the string is parsed as a hexidecimal number. If the input string begins with "0" (a zero), radix is assumed to be 8 (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAS...
... not an octal digit. The ECMAScript 5 specification of the function parseInt no longer allows implementations to treat Strings beginning with a 0 character as octal values. ECMAScript 5 states: The parseInt function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix. Leading whitespace in string is ignored. If radix is
undefined or 0, it is assumed to be 10 except when the number begins with the character pairs 0x or 0X, in which case a radix of 16 is assumed. This differs from ECMAScript 3, which merely discouraged (but allowed) octal interpretation. Many implementations have not adopted this behavior as of 2013. And, because older browsers must be supported, always specify a radix. A stricter parse function It is ...
Iteration protocols - JavaScript
as the value true if the iterator has completed its sequence. In this case, value optionally specifies the return value of the iterator. value Any JavaScript value returned by the iterator. Can be omitted when done is true. The next() method must always return an object with appropriate properties including done and value. If a non-object value gets returned (such as false or
undefined), a TypeError ("iterator.next() returned a non-object value") will be thrown. Note: It is not possible to know reflectively whether a particular object implements the iterator protocol. However, it is easy to create an object that satisfies both the iterator and iterable protocols (as shown in the example below). Doing so allows an iterator to be consumed by the various syntaxes expe...
...e.log(typeof someString[Symbol.iterator]); // "function" String's default iterator returns the string's code points one by one: let iterator = someString[Symbol.iterator](); console.log(iterator + ''); // "[object String Iterator]" console.log(iterator.next()); // { value: "h", done: false } console.log(iterator.next()); // { value: "i", done: false } console.log(iterator.next()); // { value:
undefined, done: true } Some built-in constructs--such as the spread syntax--use the same iteration protocol under the hood: console.log([...someString]); // ["h", "i"] You can redefine the iteration behavior by supplying our own @@iterator: // need to construct a String object explicitly to avoid auto-boxing let someString = new String('hi'); someString[Symbol.iterator] = function () { return { ...
Destructuring assignment - JavaScript
e.log(red); // "one" console.log(yellow); // "two" console.log(green); // "three" Assignment separate from declaration A variable can be assigned its value via destructuring separate from the variable's declaration. let a, b; [a, b] = [1, 2]; console.log(a); // 1 console.log(b); // 2 Default values A variable can be assigned a default, in the case that the value unpacked from the array is
undefined. let a, b; [a=5, b=7] = [1]; console.log(a); // 1 console.log(b); // 7 Swapping variables Two variables values can be swapped in one destructuring expression. Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick). let a = 1; let b = 3; [a, b] = [b, a]; console.log(a); // 3 console.log(b); // 1 const arr =...
...ble with a different name than the object property. const o = {p: 42, q: true}; const {p: foo, q: bar} = o; console.log(foo); // 42 console.log(bar); // true Here, for example, const {p: foo} = o takes from the object o the property named p and assigns it to a local variable named foo. Default values A variable can be assigned a default, in the case that the value unpacked from the object is
undefined. const {a = 10, b = 5} = {a: 3}; console.log(a); // 3 console.log(b); // 5 Assigning to new variables names and providing default values A property can be both 1) unpacked from an object and assigned to a variable with a different name and 2) assigned a default value in case the unpacked value is
undefined. const {a: aa = 10, b: bb = 5} = {a: 3}; console.log(aa); // 3 console.log(bb); // 5 ...
Less than (<) - JavaScript
ughly summarised below: First, objects are converted to primitives using Symbol.ToPrimitive. If both values are strings, they are compared as strings, based on the values of the Unicode code points they contain. Otherwise JavaScript attempts to convert non-numeric types to numeric values: Boolean values true and false are converted to 1 and 0 respectively. null is converted to 0.
undefined is converted to NaN. Strings are converted based on the values they contain, and are converted as NaN if they do not contain numeric values. If either value is NaN, the operator returns false. Otherwise the values are compared as numeric values. Examples String to string comparison console.log("a" < "b"); // true console.log("a" < "a"); // false console.log("a" < "3");...
...ole.log(5 < "hello"); // false console.log("5" < 3n); // false console.log("3" < 5n); // true Number to Number comparison console.log(5 < 3); // false console.log(3 < 3); // false console.log(3 < 5); // true Number to BigInt comparison console.log(5n < 3); // false console.log(3 < 5n); // true Comparing Boolean, null,
undefined, NaN console.log(true < false); // false console.log(false < true); // true console.log(0 < true); // true console.log(true < 1); // false console.log(null < 0); // false console.log(null < 1); // true console.log(
undefined < 3); // false console.log(3 <
undefined); // false console.log(3 < NaN); // false console.log(NaN < 3); /...
Logical OR (||) - JavaScript
ve-examples and send us a pull request. Syntax expr1 || expr2 Description If expr1 can be converted to true, returns expr1; else, returns expr2. If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called falsy. Examples of expressions that can be converted to false are: null; NaN; 0; empty string ("" or '' or ``);
undefined. Even though the || operator can be used with operands that are not Boolean values, it can still be considered a boolean operator since its return value can always be converted to a boolean primitive. To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator or the Boolean constructor. Short-circuit evaluation The logic...
...t' // f || t returns "Cat" o7 = 'Cat' || false // t || f returns "Cat" o8 = '' || false // f || f returns false o9 = false || '' // f || f returns "" o10 = false || varObject // f || object returns varObject Note: If you use this operator to provide a default value to some variable, be aware that any falsy value will not be used. If you only need to filter out null or
undefined, consider using the nullish coalescing operator. Conversion rules for booleans Converting AND to OR The following operation involving booleans: bCondition1 && bCondition2 is always equal to: !(!bCondition1 || !bCondition2) Converting OR to AND The following operation involving booleans: bCondition1 || bCondition2 is always equal to: !(!bCondition1 && !bCondition2) Removing nested par...
Strict equality (===) - JavaScript
s://github.com/mdn/interactive-examples and send us a pull request. Syntax x === y Description The strict equality operators (=== and !==) use the Strict Equality Comparison Algorithm to compare two operands. If the operands are of different types, return false. If both operands are objects, return true only if they refer to the same object. If both operands are null or both operands are
undefined, return true. If either operand is NaN, return false. Otherwise, compare the two operand's values: Numbers must have the same numeric values. +0 and -0 are considered to be the same value. Strings must have the same characters in the same order. Booleans must be both true or both false. The most notable difference between this operator and the equality (==) operator is that i...
... ...
Function expression - JavaScript
ymous functions. A function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about functions for more information. Function expression hoisting Function expressions in JavaScript are not hoisted, unlike function declarations. You can't use function expressions before you create them: console.log(notHoisted) //
undefined // even though the variable name is hoisted, the definition isn't. so it's
undefined. notHoisted(); // TypeError: notHoisted is not a function var notHoisted = function() { console.log('bar'); }; Named function expression If you want to refer to the current function inside the function body, you need to create a named function expression. This name is then local only to the function body ...
...me (implicit name). If function name is present, it will be the function name (explicit name). This also applies to arrow functions (arrows don't have a name so you can only give the variable an implicit name). var foo = function() {} foo.name // "foo" var foo2 = foo foo2.name // "foo" var bar = function baz() {} bar.name // "baz" console.log(foo === foo2); // true console.log(typeof baz); //
undefined console.log(bar === baz); // false (errors because baz ==
undefined) Examples Creating an unnamed function The following example defines an unnamed function and assigns it to x. The function returns the square of its argument: var x = function(y) { return y * y; }; Using a function as a callback More commonly it is used as a callback: button.addEventListener('click', function(event) {...
new.target - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
... the identifier target. Normally, the left-hand side of the dot is the object on which property access is performed, but here, new is not an object. The new.target pseudo-property is available in all functions. In class constructors, it refers to the constructed class. In ordinary functions, it refers to the function itself, assuming it was invoked via the new operator; otherwise new.target is
undefined. In arrow functions, new.target is inherited from the surrounding scope. Examples new.target in function calls In normal function calls (as opposed to constructor function calls), new.target is
undefined. This lets you detect whether a function was called with new as a constructor. function Foo() { if (!new.target) { throw 'Foo() must be called with new' } console.log('Foo instantiated w...
yield* - JavaScript
function* g3() { yield* [1, 2]; yield* '34'; yield* Array.from(arguments); } const iterator = g3(5, 6); console.log(iterator.next()); // {value: 1, done: false} console.log(iterator.next()); // {value: 2, done: false} console.log(...
... function* g4() { yield* [1, 2, 3]; return 'foo'; } function* g5() { const g4ReturnValue = yield* g4(); console.log(g4ReturnValue) // 'foo' return g4ReturnValue; } const iterator = g5(); console.log(iterator.next()); // {value: 1, done: false} console.log(iterat...
async function - JavaScript
rst await expression (if there is one), is run synchronously. In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously. For example: async function foo() { await 1 } ...is equivalent to: function foo() { return Promise.resolve(1).then(() =>
undefined) } Code after each await expression can be thought of as existing in a .then callback. In this way a promise chain is progressively constructed with each reentrant step through the function. The return value forms the final link in the chain. In the following example, we successively await two promises. Progress moves through function foo in three stages. The first line of the body of funct...
...d await expression is evaluated. Again, progress through foo is suspended and control is yielded. Some time later, when the second promise has either been fulfilled or rejected, control re-enters foo. The result of the second promise resolution is returned from the second await expression. Here 2 is assigned to result2. Control moves to the return expression (if any). The default return value of
undefined is returned as the resolution value of the current promise. async function foo() { const result1 = await new Promise((resolve) => setTimeout(() => resolve('1'))) const result2 = await new Promise((resolve) => setTimeout(() => resolve('2'))) } foo() Note how the promise chain is not built-up in one go. Instead, the promise chain is constructed in stages as control is successively yielded ...
return - JavaScript
ution and specifies a value to be returned to the function caller. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax return [[expression]]; expression The expression whose value is to be returned. If omitted,
undefined is returned instead. Description When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x, where x is a number. function square(x) { return x * x; } var demo = square(3); // demo will equal 9 If the value is omitted...
...s returned instead. Description When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x, where x is a number. function square(x) { return x * x; } var demo = square(3); // demo will equal 9 If the value is omitted,
undefined is returned instead. The following return statements all break the function execution: return; return true; return false; return x; return x + y / 3; Automatic Semicolon Insertion The return statement is affected by automatic semicolon insertion (ASI). No line terminator is allowed between the return keyword and the expression. return a + b; is transformed by ASI into: return; a + b; T...
Template literals (Template strings) - JavaScript
dding of languages (for example DSLs, or LaTeX), where other escapes sequences are common. The ECMAScript proposal Template Literal Revision (Stage 4, to be integrated in the ECMAScript 2018 standard) removes the syntax restriction of ECMAScript escape sequences from tagged templates. However, illegal escape sequences must still be represented in the "cooked" representation. ...
...e 4, to be integrated in the ECMAScript 2018 standard) removes the syntax restriction of ECMAScript escape sequences from tagged templates. However, illegal escape sequences must still be represented in the "cooked" representation. They will show up as
undefined element in the "cooked" array: function latex(str) { return { "cooked": str[0], "raw": str.raw[0] } } latex`\unicode` // { cooked:
undefined, raw: "\\unicode" } Note that the escape sequence restriction is only dropped from tagged templates--not from untagged template literals: let bad = `bad escape sequence: \unicode`; Specifications Specification ECMAScript (ECMA-262)The definition of 'Template Literals' in that specification. ECMAScript (ECMA-262)The definition of 'Tagged templates Literals' in th...
Autoplay guide for media and Web Audio APIs - Web media technologies
solved once the media successfully begins to play, and is rejected when playback fails to begin (such as if autoplay is denied). When autoplay fails, you likely will want to offer a way for the user to manually tell the browser to ask the user to grant permission to play media. You might use code like this to accomplish the job: let startPlayPromise = videoElem.play(); if (startPlayPromise !==
undefined) { startPlayPromise.then(() => { // Start whatever you need to do only after playback // has begun. }).catch(error => { if (error.name === "NotAllowedError") { showPlayButton(videoElem); } else { // Handle a load or playback error } }); } The first thing we do with the result of play() is make sure it's not
undefined. We check for this because in earlier ve...
... If the promise returned by play() is resolved without error, the then() clause is run and can begin whatever needs to be done when autoplay has begun. ...
Classes and Inheritance - Archive of obsolete content
he keyword this for the duration of the call. Moreover, if the constructor does not return a value, the result of the call defaults to the value of this. Constructors are just ordinary functions, however, so it is perfectly legal to perform ordinary function calls on them. In fact, some people (including the Add-on SDK team) prefer to use constructors this way. However, since the value of this is
undefined for ordinary function calls, we need to add some boilerplate code to convert them to constructor calls: function Shape(x, y) { if (!this) return new Shape(x, y); this.x = x; this.y = y; } Prototypes Every object has an implicit property, known as its prototype. When JavaScript looks for a property, it first looks for it in the object itself. If it cannot find the property ...
Modules - Archive of obsolete content
hat property/function. If the script being loaded is less privileged than the loading script, the access is prevented, as the following example shows: // index.js: let a = loadScript("www.foo.com/a.js", { Components: Components }); // index.js has chrome privileges Components.utils; // => [object nsXPCComponents_Utils] // a.js: // a.js has content privileges imports.Components.utils; // =>
undefined Modules in the Add-on SDK The module system used by the SDK is based on what we learned so far: it follows the CommonJS specification, which attempts to define a standardized module API. A CommonJS module defines three global variables: require, which is a function that behaves like loadScript in our examples, exports, which behaves like the exports object, and module, which is an object repres...
simple-storage - Archive of obsolete content
Quotas The simple storage available to your add-on is limited. Currently this limit is about five megabytes (5,242,880 bytes). You can choose to be notified when you go over quota, and you should respond by reducing the amount of data in storage. If the...
io/text-streams - Archive of obsolete content
ompletes, the backing stream's buffer is flushed, and both the stream and the backing stream are closed, also on the background thread. If the stream is already closed, an exception is thrown immediately. Parameters str : string The string to write. callback : callback callback, if given, must be a function. It's called as callback(error) when the write completes. error is an Error object or
undefined if there was no error. Inside callback, this is the TextWriter object. Properties closed True if the stream is closed. ...
places/bookmarks - Archive of obsolete content
. Each query object can take several properties, which are queried against the bookmarks database. Each property is AND'd together, meaning that bookmarks must match each property within a query object. Multiple query objects are then OR'd together. options : object Optional options: Name Type count number The number of bookmark items to return. If left
undefined, no limit is set. sort string A string specifying how the results should be sorted. Possible options are 'title', 'date', 'url', 'visitCount', 'dateAdded' and 'lastModified'. descending boolean A boolean specifying whether the results should be in descending order. By default, results are in ascending order. Properties MENU This is a co...
places/history - Archive of obsolete content
es. Each query object can take several properties, which are queried against the history database. Each property is AND'd together, meaning that bookmarks must match each property within a query object. Multiple query objects are then OR'd together. options : object Optional options: Name Type count number The number of bookmark items to return. If left
undefined, no limit is set. sort string A string specifying how the results should be sorted. Possible options are 'title', 'date', 'url', 'visitCount', 'keyword', 'dateAdded' and 'lastModified'. descending boolean A boolean specifying whether the results should be in descending order. By default, results are in ascending order. PlacesEmitter The ...
preferences/service - Archive of obsolete content
er,boolean Preference value. Example: var name = "extensions.checkCompatibility.nightly"; require("sdk/preferences/service").set(name, false); get(name, defaultValue) Gets the application preference name. Parameters name : string defaultValue : string,number,boolean Preference value. Returns string,number,boolean : Preference value, returns defaultValue if no preference is set, returns
undefined if defaultValue is not provided. Example: var name = "extensions.checkCompatibility.nightly"; var nightlyCompatChk = require("sdk/preferences/service").get(name); has(name) Parameters name : string Preference name. Returns boolean : Returns whether or not the application preference name exists. defaultValue Example: var name = "extensions.checkCompatibility.nightly"; if (require("sdk/p...
system/environment - Archive of obsolete content
ariable by setting the property: env.FOO = 'foo'; env.PATH += ':/my/path/' You can unset an environment variable by deleting the property: delete env.FOO; Limitations There is no way to enumerate existing environment variables, also env won't have any enumerable properties: console.log(Object.keys(env)); // [] Environment variable will be unset, show up as non-existing if it's set to null,
undefined or ''. env.FOO = null; console.log('FOO' in env); // false env.BAR = ''; console.log(env.BAR); //
undefined ...
system/unload - Archive of obsolete content
ethod. Default is unload. when(callback) Registers a function to be called when the module is unloaded. Parameters callback : function A function that will be called when the module is unloaded. It is called with a single argument, one of the following strings describing the reason for unload: "uninstall", "disable", "shutdown", "upgrade", or "downgrade". If a reason could not be determined,
undefined will be passed instead. Note that if an add-on is unloaded with reason "disable", it will not be notified about "uninstall" while it is disabled. See bug 571049. ...
ui/button/action - Archive of obsolete content
ect, null Include this parameter only if you are setting state. It is an object containing all the properties you wish to set. For example: button.state("tab", { "label" : "tab-specific label", "icon": "./tab-specific-icon.ico" }); To reset state, pass null: button.state("tab", null); Returns state : if you have passed the second state argument to make this function a setter, it returns
undefined. Otherwise, it functions as a getter and returns the button's state for the specified object. This logs the state for the button associated with the currently active tab: console.log(button.state("tab")); This object represents a snapshot of the state at the time state() is called. It is not kept up to date with changes made to the button: button.label = "foo"; var state = button.state(button)...
ui/button/toggle - Archive of obsolete content
ect, null Include this parameter only if you are setting state. It is an object containing all the properties you wish to set. For example: button.state("tab", { "label" : "tab-specific label", "icon": "./tab-specific-icon.ico" }); To reset state, pass null: button.state("tab", null); Returns state : if you have passed the second state argument to make this function a setter, it returns
undefined. Otherwise, it functions as a getter and returns the button's state for the specified object. This logs the state for the button associated with the currently active tab: console.log(button.state("tab")); This object represents a snapshot of the state at the time state() is called. It is not kept up to date with changes made to the button: button.label = "foo"; var state = button.state(button)...
util/array - Archive of obsolete content
ator : iterator The Iterator object over which to iterate and place results into an array. Returns array : The iterator's results in an array. find(iterator) Iterates over given array and applies given predicate function until predicate(element) is true. If such element is found it's retured back otherwise third optional fallback argument is returned back. If fallback is not provided returns
undefined. let { find } = require('sdk/util/array'); let isOdd = (x) => x % 2; find([2, 4, 5, 7, 8, 9], isOdd); // => 5 find([2, 4, 6, 8], isOdd); // => undefiend find([2, 4, 6, 8], isOdd, null); // => null fromIterator(i) // ['otoro', 'unagi', 'keon'] Parameters iterator : iterator The Iterator object over which to iterate and place results into an array. Returns array : The iterator's...
util/object - Archive of obsolete content
all arguments into the first argument. If two or more argument objects have properties with the same name, the property is overwritten with precedence from right to left, implying that properties of the object on the left are overwritten by a same named property of an object on the right. Properties are merged with descriptors onto the source object. Any argument given with "falsy" values (null,
undefined) in case of objects are skipped. let { merge } = require("sdk/util/object"); var a = { jetpacks: "are yes", foo: 10 } var b = merge(a, { foo: 5, bar: 6 }, { foo: 50, location: "SF" }); b === a // true b.jetpacks // "are yes" b.foo // 50 b.bar // 6 b.location // "SF" // Merge also translates property descriptors var c = { "type": "addon" }; var d = {}; Object.defineProperty(d, "nam...
Canvas code snippets - Archive of obsolete content
method] = function() { this.ctx[method].apply(this.ctx, arguments); return this; }; } for (let m of getterMethods) { let method = m; Canvas2DContext.prototype[method] = function() { return this.ctx[method].apply(this.ctx, arguments); }; } for (let p of props) { let prop = p; Canvas2DContext.prototype[prop] = function(value) { if (value ===
undefined) return this.ctx[prop]; this.ctx[prop] = value; return this; }; } }; var canvas = document.getElementById('canvas'); // Use context to get access to underlying context var ctx = Canvas2DContext(canvas) .strokeStyle('rgb(30, 110, 210)') .transform(10, 3, 4, 5, 1, 0) .strokeRect(2, 10, 15, 20) .context; // Use property name as a function (but without arguments) ...
Finding window handles - Archive of obsolete content
GdkWindow.ptr(ctypes.UInt64(GDKWindowPtrString)); var rez_gst = gdk_x11_get_server_time(browserWindow_madeIntoGdkWinPtr); console.info('rez_gst:', rez_gst, uneval(rez_gst)); // return is a number of ms since the computer (XServer) was on var rez_gwf = gdk_window_focus(browserWindow_madeIntoGdkWinPtr, rez_gst); console.info('rez_gwf:', rez_gwf, uneval(rez_gwf)); // return is void so this will be
undefined gdk.close(); GTK+ Components.utils.import('resource://gre/modules/Services.jsm'); var browserWindow = Services.wm.getMostRecentWindow('navigator:browser'); if (!browserWindow) { throw new Error('No browser window found'); } var baseWindow = browserWindow.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) ...
LookupNamespaceURI - Archive of obsolete content
function is not necessary for Gecko-based browsers (though the function will quickly return the standard value for Mozilla browsers) when used to reflect on static documents. However, due to bug 312019, this method does not work with dynamically assigned namespaces (e.g., those set with Node.prefix). ...
Preferences - Archive of obsolete content
nsISupportsString Used to handle Unicode strings in preferences. Use this when the preference value may contain non-ASCII characters (for example, a user's name). nsIPrefLocalizedString Almost the same as nsISupportsString, but it is handled differently in getComplexValue() when there's no user value for the given preference; see below for details. nsILocalFile and nsIRelativeFilePref S...
Windows - Archive of obsolete content
llowing code generate an error as describe in the following warning box var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var newWindow = wm.getMostRecentWindow("navigator:browser"); var b = newWindow.gBrowser; The code generate a TypeError from firefox console. In particular the Components.classes is
undefined and The Components object is deprecated. It will soon be removed. Draggable windows To make a window draggable by clicking on the window's contents, you can use the mousedown and mousemove events. The following code does not care which element is clicked on, simply responding to all mousedown events equally. You could improve this code by checking the event.target element and only setting the...
The Essentials of an Extension - Archive of obsolete content
function will be called once the user clicks on the menu item in the Hello World menu. All event handlers define a special object named event, which is usually good to pass as an argument to the function. Event handlers are explained in greater depth further ahead. Now let's look at the JavaScript file and see what's going on when the event is fired. /** * XULSchoolChrome namespace. */ if ("
undefined" == typeof(XULSchoolChrome)) { var XULSchoolChrome = {}; }; The XULSchoolChrome namespace is defined. All objects and variables we define in this JavaScript are global, meaning that scripts in Firefox and other extensions can see them and interact with them. This also means that if we define an object called MenuHandler or some other generic name, it's likely going to conflict with an existi...
Session store API - Archive of obsolete content
code similar to the following: var ss = Components.classes["@mozilla.org/browser/sessionstore;1"] .getService(Components.interfaces.nsISessionStore); var currentTab = gBrowser.selectedTab; var retrievedData = ss.getTabValue(currentTab, "key-name-here"); After this code executes, the variable retrievedData contains the value saved for the key "key-name-here". retrievedData is
undefined if there is no value saved for that key name. Deleting a value associated with a tab To delete a value from a tab, you can use code similar to the following: var ss = Components.classes["@mozilla.org/browser/sessionstore;1"] .getService(Components.interfaces.nsISessionStore); var currentTab = gBrowser.selectedTab; ss.deleteTabValue(currentTab, "key-name-here"); Remarks Th...
Using the Stylesheet Service - Archive of obsolete content
null); if(sss.sheetRegistered(u, sss.USER_SHEET)) sss.unregisterSheet(u, sss.USER_SHEET); Registering stylesheets on startup via the category manager Stylesheets may also be registered on startup via the agent-style-sheets and user-style-sheets categories. The category names are ignored, and the values are the URIs from which to load the stylesheets. The order the sheets are applied in is
undefined. Usage notes Stylesheets added using this service get applied to both chrome and content documents. Remember to declare the correct namespace if you want to apply stylesheets to XUL documents. Registered style sheets are not remembered across restarts. loadAndRegisterSheet fails if CSS contains #id. '#' must be percent-encoded, details see bug 659650. Historical information nsIStyleSheet...
Index - Archive of obsolete content
emoved from Browsers. You can use the more general Proxy object instead. 2007 ArrayBuffer.transfer() ArrayBuffer, Experimental, JavaScript, Method, Reference, TypedArrays The static ArrayBuffer.transfer() method returns a new ArrayBuffer whose contents have been taken from the oldBuffer's data and then is either truncated or zero-extended by newByteLength. If newByteLength is
undefined, the byteLength of the oldBuffer is used. This operation leaves oldBuffer in a detached state. 2008 Date.prototype.toLocaleFormat() Date, JavaScript, Method, Non-standard, Prototype, Reference The non-standard toLocaleFormat() method converts a date to a string using the specified formatting. Intl.DateTimeFormat is an alternative to format dates in a standards-compliant way. ...
MMgc - Archive of obsolete content
to allocate arrays and other objects of variable size that contain GC pointers or are otherwise desirable to have in managed memory. These flags may be passed to Alloc to control the allocation type. /** * flags to be passed as second argument to alloc */ enum AllocFlags { kZero=1, kContainsPointers=2, kFinalize=4, kRCObject=8 }; kZero zeros out the memory. Otherwise, the memory contains
undefined values. kContainsPointers indicates to the GC that the memory will contain pointers to other GC objects, and thus needs to be scanned by the GC's mark phase. If you know for certain that the objects will not contain GC pointers, leave this flag off; it will make the mark phase faster by excluding your object. kFinalize and kRCObject are used internally by the GC; you should not need to set them i...
JavaScript crypto - Archive of obsolete content
ue=""> <p>Password: <input type=password name="password" value=""> <p><input type=submit Name="Send" value="Submit"> </form> <script> /* the following values could be filled in by the server CGI */ var authenticator = "server_magic"; var keyTransportCert = null; var crmfObject = null; var form = document.forms[0]; function validate() { // generate keys for nsm. ...
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
nings are logged. You can access it in Mozilla by going to Tools -> Web Development -> JavaScript Console or in Firefox (the standalone browser product from Mozilla) at Tools -> JavaScript Console. Figure 1. JavaScript console The JavaScript console can show the full log list or just errors, warnings, and messages. The error message in Figure 1 says that at aol.com, line 95 tries to access an
undefined variable called is_ns70. Clicking on the link will open Mozilla's internal view source window with the offending line highlighted. The console also allows you to evaluate JavaScript. To evaluate the entered JavaScript syntax, type in 1+1 into the input field and press Evaluate, as Figure 2 shows. Figure 2. JavaScript console evaluating Mozilla's JavaScript engine has built-in support for deb...
Scripting - Archive of obsolete content
ndle is allowed to hold a JavaScript file named webapp.js (called the webapp script). This file will be loaded into the Prism chrome window very much like a Firefox extension is loaded into the browser chrome window. It can contain the following functions: startup When the app starts, before the user interface is displayed. Since the web application has not yet loaded, the window object is still
undefined. preload Just before the user interface is displayed. Returning false causes the application to terminate. load After the main application windows has finished loading. The window object has been initialized and can be used. error If there is an error loading the main app page (e.g. the server is not accessible). shutdown Just before the application terminates. Prism exposes desktop integration ...
File object - Archive of obsolete content
in the file. Currently "ascii" (ASCII), "binary" (UTF-8) or "unicode" (UCS-2). (XXX Note -- ASCII might imply ASCIIZ) File.mode A string describing the mode used to open the file. File.creationTime A Date object representing the time when the file was created. File.lastModified A Date object representing the time when the file was last modified. File.size The length of the file in bytes;
undefined(?) for directories and pipelines. File.hasRandomAccess True if random access is supported for this file. Binary (UTF-8) files and pipelines (including File.intput) do not support random access. File.hasAutoFlush Force a flush on each line break? (readonly) File.position The file position. Writing to the property moves the file pointer. File.isNative True if the file is backed by a native ...
Cmdline tests - Archive of obsolete content
e: Use case 1: test the interactive cmdline debugger Test contents: start avmshell -d test.abc, set breakpoint on a line, show local variable value, quit from cmdutils import * def run(): r=RunTestLib() r.run_test( 'debugger locals', '%s -d testdata/debug.abc'%r.avmrd, input='break 53\ncontinue\nnext\ninfo locals\nnext\ninfo locals\nquit\n', expectedout=['local1 =
undefined','local2 = 10','local2 = 15'] ) Use case 2: test -memstats returns memory logs to stdout Test contents: start avmshell -memstats test.abc, assert stdout contains 'gross stats', 'sweep m reclaimed n pages.' from cmdutils import * def run(): r=RunTestLib() r.run_test(name='memstats', command="%s -memstats testdata/memstats.abc" % r.avm, expectedout=[ ...
Venkman Introduction - Archive of obsolete content
you are inspecting. If you would like to inspect the object's prototype and parent chains, check the "Include ECMA Properties" menu item in the view's context menu. If a property shows up in a bold red font, an exception occurred when Venkman tried to read the value. The exception object will appear as the value of the property. Icon Data Type Icon Data Type Void (
undefined) value Null value Boolean value String value Integer value Double value Object value Function value Figure 9. Type Icons The column picker for this view (the box on the top right) can be used to display Type and Flags columns. The Type column contains a textual description of the type of the object. Flags lists one or mo...
Using Breakpoints in Venkman - Archive of obsolete content
useful to try out additional code, on the fly. Stop regardless of result causes Venkman to stop execution after executing the breakpoint script, allowing you to inspect program state. Stop if result is true effectively makes this a conditional breakpoint. If the breakpoint script returns a true value (it doesn't have to strictly be a boolean true, any non-null, non-empty string, non-zero, non-
undefined, and non-false value will do), execution will continue normally. If, on the other hand, the script returns a false value, Venkman will stop execution at that point. Early return from caller with result will cause the function that the breakpoint is set in to return the value of the breakpoint script as its result, immediatley after the breakpoint script completes. The Pass exceptions to calle...
Elements - Archive of obsolete content
ox 3: If you have two fields, one named A and one named B, and field A sets .B, the value of .B will depend on whether or not .A has already been accessed. If a proto is inserted into the proto chain after binding instantiation, doing so may affect field values (this wasn't the case in prior versions of Firefox). At binding attachment time, <field name="parentNode">this.parentNode</field> is
undefined instead of the value of parentNode. A field no longer changes the value of a property set on the object itself (rather than a proto) before binding attachment. property <!ENTITY % property-content "(getter?,setter?)"> <!ELEMENT property %property-content;> <!ATTLIST property id ID #IMPLIED name CDATA #REQUIRED readonly ...
listbox.currentIndex - Archive of obsolete content
<< XUL Reference currentIndex Type: integer Set to the index of the currently focused item in the list. If no item is focused, the value will be -1. (or, on some platforms, typeof(listboxcurrentIndex) will be
undefined) In a single selection list, the current index will always be the same as the selected index. In a multiple selection list, the currently focused row may be modified by the user without changing the selection by pressing the Control key and pressing the cursor keys to navigate. ...
Manifest Files - Archive of obsolete content
ght directory and is well-formed. Open the contents.rdf file in Mozilla to see if it parses as well-formed XML. If not, you will see an error on a yellow background. If you are using a debug build of Mozilla, some info will be printed to the terminal when starting up indicating what chrome applications are being checked. Check if your application is listed. The error message "XML Parsing Error:
undefined entity" in your XUL file can be caused by an error in the manifest or in the jar file referenced by the manifest. For example, in <!DOCTYPE window SYSTEM "chrome://fireclipse/locale/fireclipse.dtd"> the dtd file must exist and its directory must be correctly addressed in the "locale" manifest or XML parsing will fail. For more information about manifest files, see Chrome Registration. In the nex...
Tree Box Objects - Archive of obsolete content
coordinate corresponds to a location where the image is. Of course, in many cases you may not care what part of the cell the coordinate is on and just want the row and column. To go in reverse and get the coordinates of a specific cell, use the getCoordsForCellItem() function. It takes seven arguments, as described below. var x = {}, y = {}, width = {}, height = {}; if (typeof tree.columns != "
undefined") column = tree.columns[column]; tree.boxObject.getCoordsForCellItem( row, column, part, x, y, width, height ); The row, column, and part arguments are similar to those returned from the getCellAt() function. Again, the column should be either a string or a column object depending on which version you are using. The cell part type may be used to get the coordinates of either the text, the entir...
listbox - Archive of obsolete content
do not access or affect the contents displayed to the user. Properties accessibleType Type: integer A value indicating the type of accessibility object for the element. currentIndex Type: integer Set to the index of the currently focused item in the list. If no item is focused, the value will be -1. (or, on some platforms, typeof(listboxcurrentIndex) will be
undefined) In a single selection list, the current index will always be the same as the selected index. In a multiple selection list, the currently focused row may be modified by the user without changing the selection by pressing the Control key and pressing the cursor keys to navigate. currentItem Type: listitem element Returns the currently focused item in the list box, which is only useful in a m...
preference - Archive of obsolete content
and sets the value of the user preference specified in name. In pref dialogs with instantApply == true (default on Mac OS X) this value is kept in sync with the actual value stored in the preferences (see valueFromPreferences). When instantApply is off (default on Windows), this gets and sets the current value of the preference in the currently open dialog. There's a special case of value ===
undefined, indicating that the preference does not have a user-set value (hasUserValue == false). In this case the actual value to be displayed in the UI is obtained from the defaultValue property. valueFromPreferences Gets and sets the value stored in the user preference, specified in name. (This always accesses the nsIPrefBranch APIs regardless of the instantApply mode in effect). Methods ...
richlistbox - Archive of obsolete content
o not access or affect the contents displayed to the user. Properties accessibleType Type: integer A value indicating the type of accessibility object for the element. currentIndex Type: integer Set to the index of the currently focused item in the list. If no item is focused, the value will be -1. (or, on some platforms, typeof(listboxcurrentIndex) will be
undefined) In a single selection list, the current index will always be the same as the selected index. In a multiple selection list, the currently focused row may be modified by the user without changing the selection by pressing the Control key and pressing the cursor keys to navigate. currentItem Type: listitem element Returns the currently focused item in the list box, which is only useful in a ...
NPClass - Archive of obsolete content
NPObject that is being created. deallocate Called by NPN_ReleaseObject() when an object's reference count reaches zero. If this field is NULL, free() is called isntead. invalidate Called on live objects that belong to a plugin instance that is being destroyed. This call is always followed by a call to the deallocate function, or free(). Any attempt to use an invalidated object will result in
undefined behavior. hasMethod Called by NPN_HasMethod() to determine whether or not a specified method exists on a given NPObject. Returns true if the method exists, otherwise returns false. invoke Called by NPN_Invoke() to invoke a specific method on a given NPObject. Returns true if invocation succeeded or false if an error occurred. invokeDefault Called by NPN_InvokeDefault() to invoke the default...
NPEvent - Archive of obsolete content
ues: 0 nullEvent 1 mouseDown 2 mouseUp 3 keyDown 4 keyUp 5 autoKey 6 updateEvt 7 diskEvt 8 activateEvt 15 osEvt 23 kHighLevelEvent getFocusEvent 0, 1 (true, false) loseFocusEvent adjustCursorEvent 0, 1 (true, false) For information about these events, see the Mac OS developer documentation. message LongInt. Additional information about the event. Type of information depends on the event type.
Undefined for null, mouseUp, and mouseDown events. when LongInt. Ticks since start-up. where Point. Cursor location. modifiers Integer. Flags. XEvent NPEvent on Unix/X11 NPEvent is defined as an XEvent data structure, which is a union of a number of different X11 event structures. type The type member is an int representing an event type, and indicating which structure is relevant. The event type may ...
NPN_IntFromIdentifier - Archive of obsolete content
corresponding to the given integer identifier. Syntax #include <npruntime.h> int32_t NPN_IntFromIdentifier(NPIdentifier identifier); Parameters The function has the following parameter: <tt>identifier</tt> The integer identifier whose corresponding integer value should be returned. Returns An integer corresponding to the specified <tt>identifier</tt>. Note: The behavior of this function is
undefined if <tt>identifier</tt> isn't an integer identifier. ...
NPN_ReleaseVariantValue - Archive of obsolete content
The variant whose value is to be released. Returns Nothing. Description NPN_ReleaseVariantValue() releases the value in the given variant. This must always be called on result variants and such in this API, i.e. any NPVariant whose value comes from a call that passes back an NPVariant must be released using this function. Access to the value in an NPVariant that has been released will result in
undefined behavior. NPN_ReleaseVariantValue() will call NPN_ReleaseObject() on NPVariants of type NPVARIANTTYPE_OBJECT, and NPN_MemFree() on NPVariants of type NPVARIANTTYPE_STRING. ...
Browser Feature Detection - Archive of obsolete content
alse}, {name: 'voiceFamily', 'supported': false}, {name: 'volume', 'supported': false}, {name: 'widows', 'supported': false}, {name: 'zIndex', 'supported': false} ] }; function supports(object, featureSet) { var i; var features = _FEATURES[featureSet]; var level = 0; if (!features) return level; for (i = 0; i < features.length; i++) if (typeof(object[features[i].name]) != '
undefined') { features[i].supported = true; ++level; } return Math.floor( (100 * level) / features.length ); } function generateReport(object, featureSet, description) { var i; var features = _FEATURES[featureSet]; document.write('<p><b>' + featureSet + ' support for properties/methods in ' + description + ', percentage of names defined = ' + supports(object, featureSet) + '%<\/b><\/p>');...
-ms-scroll-limit-x-max - Archive of obsolete content
operty is equal to Element.scrollWidth. <length> The maximum value for the scrollLeft property. Formal syntax auto | <length> Specifications Not part of any specification. Remarks This property has no effect on non-scrollable elements. The specified behavior of the -ms-scroll-limit-x-max property is only applicable at a mscontentzoomfactor of 1; the behavior of this property is
undefined at other zoom factors. This property requires Windows 8 or later. ...
-ms-scroll-limit-x-min - Archive of obsolete content
lues <length> The minimum value for the scrollLeft property. If the value is negative, then 0 is used. Formal syntax <length> Specifications Not part of any specification. Remarks This property has no effect on non-scrollable elements. The specified behavior of the -ms-scroll-limit-x-min property is only applicable at a mscontentzoomfactor of 1; the behavior of this property is
undefined at other zoom factors. This property requires Windows 8 or later. ...
-ms-scroll-limit-y-max - Archive of obsolete content
operty is equal to Element.scrollHeight. <length> The maximum value for the scrollTop property. Formal syntax auto | <length> Specifications Not part of any specification. Remarks This property has no effect on non-scrollable elements. The specified behavior of the -ms-scroll-limit-y-max property is only applicable at a mscontentzoomfactor of 1; the behavior of this property is
undefined at other zoom factors. This property requires Windows 8 or later. ...
-ms-scroll-limit-y-min - Archive of obsolete content
alues <length> The minimum value for the scrollTop property. If the value is negative, then 0 is used. Formal syntax <length> Specifications Not part of any specification. Remarks This property has no effect on non-scrollable elements. The specified behavior of the -ms-scroll-limit-y-min property is only applicable at a mscontentzoomfactor of 1; the behavior of this property is
undefined at other zoom factors. This property requires Windows 8 or later. ...
-ms-scroll-limit - Archive of obsolete content
y-max property. Formal syntax <'-ms-scroll-limit-x-min'> <'-ms-scroll-limit-y-min'> <'-ms-scroll-limit-x-max'> <'-ms-scroll-limit-y-max'> Specifications Not part of any specification. Remarks This property has no effect on non-scrollable elements. The specified behavior of the -ms-scroll-limit property is only applicable at a mscontentzoomfactor of 1; the behavior of this property is
undefined at other zoom factors. This property requires Windows 8 or later. ...
E4X for templating - Archive of obsolete content
createBundle('chrome://myeExt/locale/myExt.properties'); if (args){ args = Array.prototype.slice.call(arguments, 1); return STRS.formatStringFromName(msg,args,args.length); } return STRS.GetStringFromName(msg); } For example, <toolbarbutton label={$S('myToolbar.label')}/> Conditionals function _if (cond, h, _else) { if (cond && cond !=
undefined) { // We need
undefined condition for E4X return h(cond); } else if (_else) { return _else(cond); } return ''; // Empty string allows conditions in attribute as well as element content } For example: {_if(elems.length(), function () <description>{elems[0]}</description>, function _else () <label>No data</label> )} Note that the simple XMLList() constru...
Processing XML with E4X - Archive of obsolete content
sible to use generators and iterators, giving more options for traversing E4X. In a manner akin to DOM tree walkers, we can define our own walkers for E4X. While the following is already achievable by iterating an E4X object with for each...in, it demonstrates how a more customized one could be created. ...
ArrayBuffer.transfer() - Archive of obsolete content
This operation leaves oldBuffer in a detached state. Syntax ArrayBuffer.transfer(oldBuffer [, newByteLength]); Parameters oldBuffer An ArrayBuffer object from which to transfer. newByteLength The byte length of the new ArrayBuffer object. Return value A new ArrayBuffer object. ...
Enumerator.atEnd - Archive of obsolete content
soft extension and is only supported in Internet Explorer. The Enumerator.atEnd method returns a Boolean value indicating if the enumerator is at the end of the collection. Syntax myEnum.atEnd() Remarks The required myEnum reference is any Enumerator object. The atEnd method returns true if the current item is the last one in the collection, the collection is empty, or the current item is
undefined. Otherwise, it returns false. Example In following code, the atEnd method is used to determine if the end of a list of drives has been reached: function ShowDrives() { var s = ""; var bytesPerGB = 1024 * 1024 * 1024; var fso = new ActiveXObject("Scripting.FileSystemObject"); var e = new Enumerator(fso.Drives); e.moveFirst(); while (e.atEnd() == false) { va...
Enumerator.item - Archive of obsolete content
Non-standard. Do not use! This object is a Microsoft extension and is only supported in Internet Explorer. The Enumerator.item method returns the current item in the collection. Syntax enumObj.item() Remarks The required enumObj reference is any Enumerator object. The item method returns the current item. If the collection is empty or the current item is
undefined, it returns
undefined. Example function ShowDrives() { var s = ""; var bytesPerGB = 1024 * 1024 * 1024; var fso = new ActiveXObject("Scripting.FileSystemObject"); var e = new Enumerator(fso.Drives); e.moveFirst(); while (e.atEnd() == false) { var drv = e.item(); s += drv.Path + " - "; if (drv.IsReady) { var freeGB = drv.FreeSpace / bytesPerGB; ...
Enumerator.moveFirst - Archive of obsolete content
Non-standard. Do not use! This object is a Microsoft extension and is only supported in Internet Explorer. The Enumerator.moveFirst method resets the current item in the collection to the first item. Syntax enumObj.moveFirst( ) Remarks The required enumObj reference is any Enumerator object. If there are no items in the collection, the current item is set to
undefined. Example In following example, the moveFirst method is used to evaluate members of the Drivescollection from the beginning of the list: function ShowDrives() { var s = ""; var bytesPerGB = 1024 * 1024 * 1024; var fso = new ActiveXObject("Scripting.FileSystemObject"); var e = new Enumerator(fso.Drives); e.moveFirst(); while (e.atEnd() == false) { var drv = e.item(); s += drv.Pat...
Enumerator.moveNext - Archive of obsolete content
Non-standard. Do not use! This object is a Microsoft extension and is only supported in Internet Explorer. The Enumerator.moveNext method moves the current item to the next item in the collection. Syntax enumObj.moveNext( ) Remarks The required enumObj reference is any Enumerator object. If the enumerator is at the end of the collection or the collection is empty, the current item is set to
undefined. Example In following example, the moveNext method is used to move to the next drive in the Drives collection: function ShowDrives() { var s = ""; var bytesPerGB = 1024 * 1024 * 1024; var fso = new ActiveXObject("Scripting.FileSystemObject"); var e = new Enumerator(fso.Drives); e.moveFirst(); while (e.atEnd() == false) { var drv = e.item(); s += d...
Error.description - Archive of obsolete content
operty provides backward compatibility; the message property complies with the ECMA standard. Example The following example illustrates the use of the description property. try { // Cause an error: x = y } catch(e) { // Prints "[object Error]": document.write(e) document.write (" "); // Prints 5009: document.write((e.number & 0xFFFF)) document.write (" "); // Prints "'y' is
undefined": document.write(e.description); document.write (" "); // Prints "'y' is
undefined": document.write(e.message) } Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards, Internet Explorer 11 standards. Also supported in S...
Error.number - Archive of obsolete content
ocument.write ("Error Code: "); document.write (e.number & 0xFFFF) document.write ("<br />"); document.write ("Facility Code: ") document.write(e.number>>16 & 0x1FFF) document.write ("<br />"); document.write ("Error Message: ") document.write (e.message) } Example The output of this code is as follows. Error Code: 5009 Facility Code: 10 Error Message: 'y' is
undefined Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards, Internet Explorer 11 standards. Also supported in Store apps (Windows 8 and Windows Phone 8.1). Applies To: Error Object See Also description Property (Error) message Pro...
VBArray.ubound - Archive of obsolete content
orer. The VBArray.ubound method returns the highest index value used in the specified dimension of the VBArray. Syntax safeArray.ubound(dimension) Parameters safeArray A VBArray object. dimension Optional The dimension of the VBArray for which the higher bound index is wanted. If omitted, ubound behaves as if a 1 was passed. Remarks If the VBArray is empty, the ubound method returns
undefined. If dim is greater than the number of dimensions in the VBArray, or is negative, the method generates a "Subscript out of range" error. Example The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is JavaScript code that determines the number of dimensions in the safe array and the upper bound of each dimension. Both...
New in JavaScript 1.2 - Archive of obsolete content
igned scripts Changed functionality in JavaScript 1.2 You can now nest functions within functions. Number now converts a specified object to a number. Number now produces NaN rather than an error if x is a string that does not contain a well-formed numeric literal. String now converts a specified object to a string. Array.prototype.sort() now works on all platforms. It no longer converts
undefined elements to null and sorts them to the high end of the array. String.prototype.split() It can take a regular expression argument, as well as a fixed string, by which to split the object string. It can take a limit count so that it won't include trailing empty elements in the resulting array. String.prototype.substring(): no longer swaps index numbers when the first index is greate...
New in JavaScript 1.3 - Archive of obsolete content
4.5 executes JavaScript language versions up to 1.3. Note that Communicator and Navigator 4.0-4.05 and earlier ignored scripts with the language attribute set to "JavaScript1.3" and higher. <SCRIPT LANGUAGE="JavaScript1.2"> <!-- JavaScript for Navigator 4.0. --> <SCRIPT LANGUAGE="JavaScript1.3"> <!-- JavaScript for Navigator 4.5. ...
New in JavaScript 1.8.5 - Archive of obsolete content
API Offers support for creating Object and Function proxies that enable meta-programming in JavaScript. Changed functionality in JavaScript 1.8.5 ISO 8601 support in Date: The Date object's parse() method now supports simple ISO 8601 format date strings. Global objects made read only: The NaN, Infinity, and
undefined global objects have been made read only, per the ECMAScript 5 specification. obj.__parent__ and obj.__count__ become obsolete. Some information about why: SpiderMonkey change du jour: the special __parent__ property has been removed bug 551529 & bug 552560. Trailing commas no longer accepted in JSON.parse(). ...
Object.prototype.__noSuchMethod__ - Archive of obsolete content
g a function at that object's __noSuchMethod__ member. The function takes two arguments, the first is the name of the method attempted and the second is an array of the arguments that were passed in the method call. The second argument is an actual array (that is, it inherits through the Array.prototype chain) and not the array-like arguments object. If this method cannot be called, either as if
undefined by default, if deleted, or if manually set to a non-function, the JavaScript engine will revert to throwing TypeErrors. Examples Simple test of __noSuchMethod__ var o = { __noSuchMethod__: function(id, args) { console.log(id, '(' + args.join(', ') + ')'); } }; o.foo(1, 2, 3); o.bar(4, 5); o.baz(); // Output // foo (1, 2, 3) // bar (4, 5) // baz () ...
Object.prototype.unwatch() - Archive of obsolete content
In addition, using watchpoints has a serious negative impact on performance, which is especially true when used on global objects, such as window. You can usually use setters and getters or proxies instead. The unwatch() method removes a watchpoint set with the watch() method. Syntax obj.unwatch(prop) Parameters prop The name of a property of the object to stop watching. Return value
undefined. Description The JavaScript debugger has functionality similar to that provided by this method, as well as other debugging options. For information on the debugger, see Venkman. By default, this method is inherited by every object descended from Object. Note: The reason for unwatch() to take the property name prop as its only parameter is due to the "single handler allowing" behavior of the ...
Archived JavaScript Reference - Archive of obsolete content
bserve() method was used to remove observers set by Array.observe(), but has been deprecated and removed from Browsers. You can use the more general Proxy object instead.ArrayBuffer.transfer()The static ArrayBuffer.transfer() method returns a new ArrayBuffer whose contents have been taken from the oldBuffer's data and then is either truncated or zero-extended by newByteLength. If newByteLength is
undefined, the byteLength of the oldBuffer is used. This operation leaves oldBuffer in a detached state.Date.prototype.toLocaleFormat()The non-standard toLocaleFormat() method converts a date to a string using the specified formatting. Intl.DateTimeFormat is an alternative to format dates in a standards-compliant way. See also the newer version of Date.prototype.toLocaleDateString().ECMAScript 2016 to ES.N...
MDN Web Docs Glossary: Definitions of Web-related terms
Three js Time to first byte Time to interactive TLD TOFU Transmission Control Protocol (TCP) Transport Layer Security (TLS) Tree shaking Trident Truthy TTL TURN Type Type coercion Type conversion U UDP (User Datagram Protocol) UI
undefined Unicode URI URL URN Usenet User agent UTF-8 UX V Validator Value Variable Vendor Prefix Viewport Visual Viewport VoIP W W3C WAI WCAG Web performance Web server Web standards ...
Introducing asynchronous JavaScript - Learn web development
code block. You just can't guarantee that the async function will return before the browser has processed the sync block. To see this in action, try taking a local copy of our example, and changing the fourth console.log() call to the following: console.log ('All done! ' + image.src + 'displayed.'); You should now get an error in your console instead of the third message: TypeError: image is
undefined; can't access its "src" property This is because at the time the browser tries to run the third console.log() statement, the fetch() block has not finished running so the image variable has not been given a value. Note: For security reasons, you can't fetch() files from your local filesystem (or run other such operations locally); to run the above example locally you'll have to run the example...
Graceful asynchronous programming with Promises - Learn web development
that may occur with any of the promises passed in the array to .all(). If any of the promises reject, the .catch() block will let you know which one had a problem. The .all() block (see below) will still fulfill, but it won't display the resources that had problems. Remember that, once you handle the promise with a .catch() block, the resulting promise is considered resolved but with a value of
undefined; that's why in this case the .all() block will always get fulfilled. If you wanted the .all() to reject, you'd have to chain the .catch() block on to the end of the .all() instead. The code inside the function body is async and promise-based, therefore in effect, the entire function acts like a promise -- convenient. Next, we call our function three times to begin the process of ...
Looping code - Learn web development
loop will stop, and the browser will move on to the next bit of code below the loop. Note: We have made the condition i < cats.length, not i <= cats.length, because computers count from 0, not 1 -- we are starting i at 0, and going up to i = 4 (the index of the last array item). cats.length returns 5, as there are 5 items in the array, but we don't want to get up to i = 5, as that would return
undefined for the last item (there is no array item with an index of 5). So, therefore, we want to go up to 1 less than cats.length (i <), not the same as cats.length (i <=). Note: A common mistake with conditions is making them use "equal to" (===) rather than say "less than or equal to" (<=). If we wanted to run our loop up to i = 5, the exit condition would need to be i <= cats.length. If we set it t...
A first splash into JavaScript - Learn web development
ing: guessField.value = 'Hello'; The value property represents the current value entered into the text field. You'll see that by entering this command, we've changed the text in the text field! Now try typing guesses into the console and pressing return. The console shows you that the variable contains a <p> element. Now try entering the following line: guesses.value The browser returns
undefined, because paragraphs don't have the value property. To change the text inside a paragraph, you need the textContent property instead. Try this: guesses.textContent = 'Where is my paragraph?'; Now for some fun stuff. Try entering the below lines, one by one: guesses.style.backgroundColor = 'yellow'; guesses.style.fontSize = '200%'; guesses.style.padding = '10px'; guesses.style.boxShadow = '...
Storing the information you need — Variables - Learn web development
work correctly for single lines, but probably won't when you are writing multiple lines of code together. Try to get into the habit of including it. You can test whether these values now exist in the execution environment by typing just the variable's name, e.g. myName; myAge; They currently have no value; they are empty containers. When you enter the variable names, you should get a value of
undefined returned. If they don't exist, you'll get an error message -- try typing in scoobyDoo; Note: Don't confuse a variable that exists but has no defined value with a variable that doesn't exist at all -- they are very different things. In the box analogy you saw above, not existing would mean there's no box (variable) for a value to go in. No value defined would mean that there IS a box, but it ha...
What is JavaScript? - Learn web development
e() code block (lines 5-8) is run. The updateName() code block (these types of reusable code blocks are called "functions") asks the user for a new name, and then inserts that name into the paragraph to update the display. If you swapped the order of the first two lines of code, it would no longer work -- instead, you'd get an error returned in the browser developer console -- TypeError: para is
undefined. This means that the para object does not exist yet, so we can't add an event listener to it. Note: This is a very common error -- you need to be careful that the objects referenced in your code exist before you try to do stuff to them. Interpreted versus compiled code You might hear the terms interpreted and compiled in the context of programming. In interpreted languages, the code is run f...
Object prototypes - Learn web development
otype.fullName = 'Bob Smith'; This isn't very flexible, as the person might not be called that. It'd be much better to build the fullName out of name.first and name.last: Person.prototype.fullName = this.name.first + ' ' + this.name.last; However, this doesn't work. That's because this will be referencing the global scope in this case, not the function scope. Calling this property would return
undefined. This worked fine on the method we defined earlier in the prototype because it is sitting inside a function scope, which will be transferred successfully to the object instance scope. So you might define constant properties on the prototype (i.e. ones that never need to change), but generally it works better to define properties inside the constructor. In fact, a fairly common pattern for more o...
Dynamic behavior in Svelte: working with variables and props - Learn web development
pt by taking valid syntax and giving it a new purpose. In this case Svelte is using the export keyword to mark a variable declaration as a property or prop, which means it becomes accessible to consumers of the component. You can also specify a default initial value for a prop. This will be used if the component's consumer doesn't specify the prop on the component -- or if its initial value is
undefined -- when instantiating the component. So with export let todos = [], we are telling Svelte that our Todos.svelte component will accept a todos attribute, which when omitted will be initialized to an empty array. Have a look at the app, and you'll see the "Nothing to do here!" message. This is because we are currently not passing any value into it from App.svelte, so it's using the default...
Focus management with Vue refs - Learn web development
is.isEditing = false; this.focusOnEditButton(); }, editCancelled() { this.isEditing = false; this.focusOnEditButton(); }, Try editing and then saving/cancelling a to-do item via your keyboard. You'll notice that focus isn't being set, so we still have a problem to solve. If you open your console, you'll see an error raised along the lines of "can't access property "focus", editButtonRef is
undefined". This seems weird. Your button ref was defined when you activated the "Edit" Button, but now it's not. What is going on? Well, remember that when we change isEditing to true, we no longer render the section of the component featuring the "Edit" Button. This means there's no element to bind the ref to, so it becomes
undefined. You might now be thinking "hey, don't we set isEditing=false before ...
Implementing feature detection - Learn web development
eded. First, remove the contents of the second <link> element's href attribute. We will fill this in dynamically later on. Next, add a <script></script> element at the bottom of your body (just before the closing </body> tag). Give it the following contents: const conditional = document.querySelector('.conditional'); const testElem = document.createElement('div'); if (testElem.style.flex !==
undefined && testElem.style.flexFlow !==
undefined) { conditional.setAttribute('href', 'flex-layout.css'); } else { conditional.setAttribute('href', 'float-layout.css'); } Here we are grabbing a reference to the second <link> element, and creating a <div> element as part of our test. In our conditional statement, we test that the flex and flex-flow properties exist in the browser. Note how the Java...
Accessibility API cross-reference
a group box (titledbox in mozilla) GROUPING PANEL PANEL group <fieldset>, <div> A heading for a section of the page. In ARIA, the heading level is expressed with the aria-level attribute. heading <h1> ... <h6> <H1> ... <H6>. ...
The Firefox codebase: CSS Guidelines
bars. If you'd like a different shade of a themed area and no CSS variable is adequate, using colors with alpha transparency is usually a good idea, as it will preserve the original theme author's color hue. Variables For clarity, CSS variables that are only used when a theme is enabled have the --lwt- prefix. Layout & performance Layout Mixing XUL flexbox and HTML flexbox can lead to
undefined behaviour. CSS selectors When targetting the root element of a page, using :root is the most performant way of doing so. Reflows and style flushes See Performance best practices for Firefox front-end engineers for more information about this. Misc Text aliasing When convenient, avoid setting the opacity property on text as it will cause text to be aliased differently. HDPI support It's r...
Listening to events on all tabs
The nsIWebProgress instance that fired the notification. aRequest The nsIRequest that has changed state. This parameter may be null. Need more information on what NULL means. aStateFlags Flags indicating the new state. This value is a combination of one of the State Transition Flags and one or more of the State Type Flags defined in the nsIWebProgressListener documentation. Any
undefined bits are reserved for future use. aStatus Error status code associated with the state change; this indicates whether or not the request was successful. This parameter should be ignored unless aStateFlags includes the STATE_STOP bit. NOTE: aStatus may be a success code even for server generated errors, such as the HTTP 404 File Not Found error. In such cases, the request itself should b...
Displaying Places information using views
queries An array of nsINavHistoryQuery objects. options An nsINavHistoryQueryOptions object. selectItems() Selects the first node in the tree that matches each given item ID. It will open any parent nodes that it needs to in order to show the selected items. void selectItems( array aIDs, array aOpenContainers ); Parameters aIDs An array of item IDs. aOpenContainers If true or
undefined, folders that are closed are also searched. They are not searched otherwise. Optional. selectNode() Causes a particular node to be selected in the tree, resulting in all containers above the node in the hierarchy to be opened so that the node is visible. void selectNode( nsINavHistoryNode node ); Parameters node The nsINavHistoryResultNode to select. selectPlaceURI() Causes a parti...
Error codes returned by Mozilla APIs
NS_ERROR_DOM_FILE_NOT_FOUND_ERR (0x80650000) File was not found. NS_ERROR_DOM_FILE_NOT_READABLE_ERR (0x80650001) File could not be read. Network Errors The following errors can occur when creating...
mozbrowsermetachange
h the following properties: name A DOMString representing the <meta> name attribute value. This can be viewmode, theme-color, theme-group, or application-name. content A DOMString representing the <meta> content attribute value, i.e. the content of the meta tag. type A DOMString representing the type of meta change that this event object represents. This can be added, changed, removed, or
undefined. lang Optional A DOMString representing the <meta> name attribute value, if included. If not included, the value returned is
undefined. Example var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowsermetachange", function(event) { console.log("A meta tag has been " + event.details.type + ". Its name is " + event.details.name + ", and its content is " + event.
IPDL Tutorial
ly because they are common, and because the base IPC library knows how to serialize and deserialize these types. See ipc/ipdl/ipdl/builtin.py for the most up-to-date list of automatically imported types. Actors may be passed as parameters. The C++ signature will accept a PProtocolParent* on one side and convert it to a PProtocolChild* on the other. Maybe types If you want to pass a potentially
undefined argument, you can add ? postfix after the type name. Then you can pass a mozilla::Maybe object instead of a concrete value. protocol PMaybe { child: async Maybe(nsCString? maybe); }; Custom primitive types When you need to send data of a type other than one built into IPDL, you can add a using declaration in an IPDL specification. A custom serializer and deserializer must be provided by yo...
AddonType
in the list the type will appear. Built-in Values: Value Category 2000 Locale 4000 Extension 5000 Theme 6000 Plugin viewType integer The type of UI to use to display this type of add-on in the UI. If
undefined the type will not appear in the UI. flags integer Additional behavior flags for the type. ...
Dict.jsm
om the dictionary. Return value true if an entry was found and removed; false if no match was found. get() Returns the value corresponding to the specified key. Object get( String aKey, [optional] Object aDefault ); Parameters aKey The key whose value should be returned. aDefault Optional The value to return if the specified key isn't found. If you don't specify a default value,
undefined is returned for keys that aren't found. Return value The value of the specified key, or
undefined if no matching key was found. has() Determines whether or not the specified key exists in the dictionary. boolean has( String aKey ); Parameters aKey The key for which to determine existence in the dictionary. Return value true if the specified key is in the dictionary, otherwise fal...
Downloads.jsm
ontaining the path of the target file. Alternatively, may be an nsIFile or a DownloadTarget object. aOptions Optional An optional object used to control the behavior of this function. You may pass an object with a subset of the following fields: isPrivate: Optional Indicates whether the download originated from a private window. If omitted, the download is public. Promise resolves to
undefined when the download has finished successfully and you can access the target file. Promise can be rejected with DownloadError if the download failed. getList() Retrieves the specified type of DownloadList object. There is one download list for each type, and this method always retrieves a reference to the same download list when called with the same argument. Calling this function may cause the...
JavaScript OS.Constants
r read and write. O_RSYNC O_SHLOCK Atomically obtain a shared lock. O_SYMLINK Allow opening of symbolic links. O_SYNC (Linux only) Open for purely synchronous access. O_TRUNC Truncate the file. O_WRONLY Open the file for write only. OS.Constants.Win Constants for interacting with the Windows API. OS.Constants.Win is
undefined on non-Windows platforms. Useful mostly in conjunction with js-ctypes. (tbd) ...
Task.jsm
r // one second, in this imaginary example). We can easily loop while // calling asynchronous functions, and wait multiple times. for (let i = 0; i < 3; i++) { result += yield getPromiseResolvedOnTimeoutWithValue(50, "!"); } return "Resolution result for the task: " + result; }).then(function (result) { // result == "Resolution result for the task: Value!!!" // The result is
undefined if no special Task.Result exception was thrown. }, function (exception) { // Failure! We can inspect or report the exception. }); Exception handling Components.utils.import("resource://gre/modules/osfile.jsm") Components.utils.import("resource://gre/modules/Task.jsm") Task.spawn(function* () { let currentDir = yield OS.File.getCurrentDirectory(); let path = OS.Path.join(currentDir, "...
Extras
MathML Extras This is a technology demonstration of some of the extras in Mozilla but not defined in the MathML spec, and not prevented by the spec either. They are not portable and are meant to showcase a few interesting upshots from building natively upon the browser environment. Other renderers are expected to ignore attributes that they don't understand while the behavior of
undefined elements is well,
undefined. The title attribute as a tooltip (from XHTML) HTML Content <p>Mouse over either log to see a tooltip showing the title <math display="block"> <mrow> <mrow> <msub title="Base-a log"> <mi>log</mi> <mi>a</mi> </msub> <mo>⁡</mo> <mi>x</mi> </mrow> <mo>=</mo> <mfrac> <mrow> <mi title="Natural log">ln</mi> <mo>⁡</mo> <mi>x</mi> </mrow> <mrow> <mi tit...
MathML3Testsuite
ed with passed, failed, not-tested or some parts pass, giving the status of trunk builds with the appropriate fonts installed. When the markup is intentionally errorous, the correct behavior is not defined by the recommendation and hence the tests are considered passed if there is no fatal error (crash, etc). This exception also holds for obsolete features (such as macro, mode etc) or for other
undefined behaviors (attribute href for example). Note that in general, comparing with the "Sample Rendering" is not enough to conclude on the success/failure of the test. So please do not edit these pages if you are not able to explain Gecko's rendering. However, any report is welcome on the Tracking bug for the MathML testsuite. Characters Blocks Symbols Variants EntityNames NumericRefs UTF8 General ...
Localization Use Cases
ShortName }} ulegla awarii", neutral: "{{ brandShortName }} uleglo awarii" }> This will give us, depending on the current branding, the following messages: Firefox OS ulegl awarii Boot2Gecko uleglo awarii Isolation Let's look at how the Settings app formats sizes. ...
AsyncTestUtils extended framework
asynchronous operation is complete, something needs to call async_driver(). Returning false tells the asynchronous driver that it should yield control up to the top-level. Calling async_driver() lets it know to start up again. A function should yield true or return true when the asynchronous driver should continue executing without stopping. A function that does not return anything (or returns
undefined) and is not a generator is treated like a function that returned true. Most of the things you will want to do already have helper functions that take care of all of this, so all you need to do is pass their return values through. For example, you would do "yield async_move_messages(...);" and be done with it. Helpers for the Asynchronous Function Contract It can be annoying to have to write i...
PR_Lock
be locked. Description When PR_Lock returns, the calling thread is "in the monitor," also called "holding the monitor's lock." Any thread that attempts to acquire the same lock blocks until the holder of the lock exits the monitor. Acquiring the lock is not an interruptible operation, nor is there any timeout mechanism. PR_Lock is not reentrant. Calling it twice on the same thread results in
undefined behavior. See Also PR_Unlock ...
PR_Unlock
Syntax #include <prlock.h> PRStatus PR_Unlock(PRLock *lock); Parameter PR_Unlock has one parameter: lock A pointer to a lock object to be released. ...
Threads
g Types and Constants PRThread PRThreadType PRThreadScope PRThreadState PRThreadPriority PRThreadPrivateDTOR Threading Functions Most of the functions described here accept a pointer to the thread as an argument. NSPR does not check for the validity of the thread. It is the caller's responsibility to ensure that the thread is valid. The effects of these functions on invalid threads are
undefined. Creating, Joining, and Identifying Threads Controlling Thread Priorities Interrupting and Yielding Setting Global Thread Concurrency Getting a Thread's Scope Creating, Joining, and Identifying Threads PR_CreateThread creates a new thread. PR_JoinThread blocks the calling thread until a specified thread terminates. PR_GetCurrentThread returns the current thread object for the curren...
Index
anism-list is a colon-delimited list of mechanism names. Enclose this list in quotation marks if it contains spaces. The module becomes a default provider for the listed mechanisms when those mechanisms are enabled. If more than one module claims to be a particular mechanism's default provider, that mechanism's default provider is
undefined. modutil supports several mechanisms: RSA, DSA, RC2, RC4, RC5, AES, DES, DH, SHA1, SHA256, SHA512, SSL, TLS, MD5, MD2, RANDOM (for random number generation), and FRIENDLY (meaning certificates are publicly readable). -newpwfile new-password-file Specify a text file containing a token's new or replacement password so that a pa...
NSS 3.28.3 release notes
as been reverted to the original state in bug 1334108. SECKEYECPublicKey had been extended with a new attribute, named "encoding". If an application passed type SECKEYECPublicKey to NSS (as part of SECKEYPublicKey), the NSS library read the uninitialized attribute. With this NSS release SECKEYECPublicKey.encoding is deprecated. NSS no longer reads the attribute, and will always set it to ECPoint_
Undefined. See bug 1340103. Compatibility NSS 3.28.3 shared libraries are backward compatible with most older NSS 3.x shared libraries, but depending on your application, may be incompatible, if you application has been compiled against header files of versions 3.28, 3.28.1, or 3.28.2. A program linked with most older NSS 3.x shared libraries (excluding the exceptions mentioned above), will work with NS...
NSS 3.29.1 release notes
as been reverted to the original state in bug 1334108. SECKEYECPublicKey had been extended with a new attribute, named "encoding". If an application passed type SECKEYECPublicKey to NSS (as part of SECKEYPublicKey), the NSS library read the uninitialized attribute. With this NSS release SECKEYECPublicKey.encoding is deprecated. NSS no longer reads the attribute, and will always set it to ECPoint_
Undefined. See bug 1340103. Note that NSS 3.28.3 from the older NSS 3.28.x branch has also been released with the identical fixes. Compatibility NSS 3.29.1 shared libraries are backward compatible with most older NSS 3.x shared libraries, but depending on your application, may be incompatible, if you application has been compiled against header files of versions 3.28, 3.28.1, 3.28.2 NSS 3.29.1. A progr...
NSS 3.37 release notes
X platform was available (bug 1346735), which performed seeding exclusively based on /dev/urandom. This alternative implementation is selected at build time by defining the SEED_ONLY_DEV_URANDOM symbol. (The classic implementation for RNG seeding on the Linux/Unix platform, which may use additional sources for the default seeding, is still available and will be used if SEED_ONLY_DEV_URANDOM is
undefined.) With NSS 3.37, this alternative implementation for Linux/Unix can be selected in "make" builds by defining the environment variable NSS_SEED_ONLY_DEV_URANDOM. With NSS 3.37, this alternative implementation for Linux has been enhanced to use the glibc function getentropy(), instead of reading from /dev/urandom directly, if the build and runtime Linux platform supports it. The CA certifi...
NSS 3.46 release notes
cryptographic primitives (CVE-2019-17006) Bug 1542077 - mp_set_ulong and mp_set_int should return errors on bad values Bug 1572791 - Read out-of-bounds in DER_DecodeTimeChoice_Util from SSLExp_DelegateCredential Bug 1560593 - Cleanup.sh script does not set error exit code for tests that "Failed with core" Bug 1566601 - Add Wycheproof test vectors for AES-KW Bug 1571316 - curve25519_32.c:280:
undefined reference to `PR_Assert' when building NSS 3.45 on armhf-linux Bug 1516593 - Client to generate new random during renegotiation Bug 1563258 - fips.sh fails due to non-existent "resp" directories Bug 1561598 - Remove -Wmaybe-uninitialized warning in pqg.c Bug 1560806 - Increase softoken password max size to 500 characters Bug 1568776 - Output paths relative to repository in NSS coverity Bug ...
NSS 3.54 release notes
or "O=Government Root Certification Authority; C=TW" root. Bug 1645199 - Remove AddTrust root certificates. Bug 1641718 - Remove "LuxTrust Global Root 2" root certificate. Bug 1639987 - Remove "Staat der Nederlanden Root CA - G2" root certificate. Bug 1618402 - Remove Symantec root certificates and disable email trust bit. Bug 1640516 - NSS 3.54 should depend on NSPR 4.26. Bug 1642146 - Fix
undefined reference to `PORT_ZAlloc_stub' in seed.c. Bug 1642153 - Fix infinite recursion building NSS. Bug 1642638 - Fix fuzzing assertion crash. Bug 1642871 - Enable SSL_SendSessionTicket after resumption. Bug 1643123 - Support SSL_ExportEarlyKeyingMaterial with External PSKs. Bug 1643557 - Fix numerous compile warnings in NSS. Bug 1644774 - SSL gtests to use ClearServerCache when resetting self-en...
nss tech note1
lates. The syntax of these templates is identical for both decoders, except where noted. A "NULL Template" is a template that is all zeros, having a zero kind.+ The term "NULL-terminated array", as used throughout this document, means an array of templates, the last of which is a NULL template. void* dest is a pointer to the target area. This is where the decoder stores its output. The type is
undefined as it is completely dependent on the content of the decoder templates.+ This typically points to a struct that is described (or partially described) by the templates. PRArenaPool* arena is a pointer to an NSPR arena pool. This is the arena pool from which the decoder will allocate memory as needed. Decoder templates : The SEC_ASN1Template structure tells the decoder what to do with the input...
PKCS #11 Module Specs
CS #11 functions and is only used for loading additional modules. trustOrder - integer value specifying the order in which the trust information for certificates specified by tokens on this PKCS #11 library should be rolled up. '0' means that tokens on this library should not supply trust information (default). The relative order of two pkcs#11 libraries which have the same trustOrder value is
undefined. cipherOrder - integer value specifiying the order in which tokens are searched when looking for a token to do a generic operation (DES/Hashing, etc). ciphers - comma separated list of ciphers this token will enable that isn't already enabled by the library (currently only FORTEZZA is defined) (case-insensitive). slotParams - space separated list of name/value pairs where the name is a slotID ...
Build instructions
dows, in both DEBUG and optimized builds, when using MSVC, tells NSS to put symbols in a .pdb file. Required to build with MSVC 8 (2005 Express). Default is not to put debug symbols into optimized builds, and for MSVC, is to put symbols into the .exe or .dll file. NSDISTMODE: If set to 'copy', mozilla/dist/<OBJ_STUFF>/bin/* real files instead of symbolic links. These variables should be either
undefined, or set to "1". Results are
undefined for variables set to "0". For Windows, install the MozillaBuild environment and Microsoft Visual Studio 2010. (The free edition works, and other versions like Visual Studio 2008 and Visual Studio 2012 may also work.) Use start-shell-msvc2010.bat from MozillaBuild to get a bash shell with the PATH already configured, and execute these instructions from within...
NSS tools : modutil
cular module will be flagged as a default provider. The mechanism-list is a colon-delimited list of mechanism names. Enclose this list in quotation marks if it contains spaces. The module becomes a default provider for the listed mechanisms when those mechanisms are enabled. If more than one module claims to be a particular mechanism's default provider, that mechanism's default provider is
undefined. modutil supports several mechanisms: RSA, DSA, RC2, RC4, RC5, AES, DES, DH, SHA1, SHA256, SHA512, SSL, TLS, MD5, MD2, RANDOM (for random number generation), and FRIENDLY (meaning certificates are publicly readable). -newpwfile new-password-file Specify a text file containing a token's new or replacement password so that a password can be entered automatically with the -changepw option. ...
NSS Tools modutil
a particular module will be flagged as a default provider. The mechanism-list is a colon-delimited list of mechanism names. Enclose this list in quotation marks if it contains spaces. The module becomes a default provider for the listed mechanisms when those mechanisms are enabled. If more than one module claims to be a particular mechanism's default provider, that mechanism's default provider is
undefined. The following mechanisms are currently available: RSA, DSA, RC2, RC4, RC5, DES, DH, FORTEZZA, SHA1, MD5, MD2, RANDOM (for random number generation), and FRIENDLY (meaning certificates are publicly readable). -installdir root-installation-directory Specify the root installation directory relative to which files will be installed by the -jar JAR-file option. This directory should be one below wh...
NSS tools : modutil
anism-list is a colon-delimited list of mechanism names. Enclose this list in quotation marks if it contains spaces. The module becomes a default provider for the listed mechanisms when those mechanisms are enabled. If more than one module claims to be a particular mechanism's default provider, that mechanism's default provider is
undefined. modutil supports several mechanisms: RSA, DSA, RC2, RC4, RC5, AES, DES, DH, SHA1, SHA256, SHA512, SSL, TLS, MD5, MD2, RANDOM (for random number generation), and FRIENDLY (meaning certificates are publicly readable). -newpwfile new-password-file Specify a text file containing a token's new or replacement password so that a pa...
Rhino scopes and contexts
tion that varies across scopes in the instance scope yet still share functions that manipulate that information reside in the shared scope. The DynamicScopes example illustrates all the points discussed above. More on Scopes The key things to determine in setting up scopes for your application are What scope should global variables be created in when your script executes an assignment to an
undefined variable, and What variables should your script have access to when it references a variable? The answer to 1 determines which scope should be the ultimate parent scope: Rhino follows the parent chain up to the top and places the variable there. After you've constructed your parent scope chain, the answer to question 2 may indicate that there are additional scopes that need to be searched that...
How to embed the JavaScript engine
button, and copy the code from the window that appears. Compile the helloworld application and link to the SpiderMonkey library. Run the helloworld executable at the command line: ./helloworld How to call C functions from JavaScript Say the C function is named doit and it would like at least two actual parameters when called (if the caller supplies fewer, the JS engine should ensure that
undefined is passed for the missing ones): #define DOIT_MINARGS 2 // [SpiderMonkey 24] Use JSBool instead of bool. static bool doit(JSContext *cx, unsigned argc, jsval *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); /* * Look in argv for argc actual parameters, set *rval to return a * value to the caller. * * ex. Add two arguments as integer. * args.rval().setInt32(args[0].toInt32...
SpiderMonkey Internals
C++ double (noting that JavaScript NaN must be represented as one canonical NaN format). Other values are encoded as a value and a type tag: On x86, ARM, and similar 32-bit platforms, we use what we call "nunboxing", in which non-double values are a 32-bit type tag and a 32-bit payload, which is normally either a pointer or a signed 32-bit integer. There are a few special values: NullValue(),
UndefinedValue(), TrueValue() and FalseValue(). On x64 and similar 64-bit platforms, pointers are longer than 32 bits, so we can't use the nunboxing format. Instead, we use "punboxing", which has 17 bits of tag and 47 bits of payload. Only JIT code really depends on the layout--everything else in the engine interacts with values through functions like val.isDouble(). Most parts of the JIT also avoid dep...
Introduction to the JavaScript shell
gratification, which is handy for experimenting or testing new features. You can also pass in, on the command line, a JavaScript program file to run, in which case the program is run automatically. After following the build documentation and installing the built shell using make install, you can run the shell in interactive mode using the command: js [ If you get " symbol lookup error: ./js:
undefined symbol: PR_SetCurrentThreadName" e.g. from a Bash console when using a pre-compiled binary, try <path to your Firefox's run-mozilla.sh>/run-mozilla.sh ./js -- that worked for me] If you'd like to run the JavaScript code in the file foo.js, you can use this command: js foo.js To run foo.js then drop into the interactive shell, do this: js -f foo.js -i Reference Note: Because the JavaSc...
INT_TO_JSVAL
onvert to a jsval. Description INT_TO_JSVAL converts a C integer, i, to a jsval. Before SpiderMonkey 1.8.5, not all integers can be stored in a jsval; use INT_FITS_IN_JSVAL to test. Starting in SpiderMonkey 1.8.5, jsval can store a full 32-bit integer, so this check isn't needed any longer for 32-bit integers.") }} If i does not fit into a jsval (see INT_FITS_IN_JSVAL), the behavior is
undefined. To convert any number to a jsval, regardless of whether it fits in an int jsval, use JS_NewNumberValue instead. To convert an integer jsval to a C integer, use JS::ToInt32. See Also MXR ID Search for INT_TO_JSVAL JS::ToInt32 JS::Int32Value bug 1177892 -- removed ...
JS::CallArgs
If false, it reports an error message on the context. Methods inherited from JS::CallArgsBase Method Description unsigned length() const Returns the number of arguments.. JS::MutableHandleValue operator[](unsigned i) const Returns the i-th zero-indexed argument. JS::HandleValue get(unsigned i) const Returns the i-th zero-indexed argument, or
undefined if there's no such argument. bool hasDefined(unsigned i) const Returns true if the i-th zero-indexed argument is present and is not
undefined. Methods inherited from JS::detail::CallReceiverBase Method Description JSObject &callee() const Returns the function being called, as an object. Must not be called after rval() has been used! JS::HandleV...
JS::Compile
in characters. file is the filehandle containing the text of the script. filename is the name of the file (or URL) containing the script. This information is included in error messages if an error occurs during compilation.. On success, JS::Compile stores an object representing the newly compiled script into script, and returns true. Otherwise, it returns false and the value left in script is
undefined. See Also The JSAPI User Guide contains example code using compiled scripts. MXR ID Search for JS::Compile JS::Evaluate JS::CompileOffThread JS::CompileFunction JS_DecompileScript bug 771705 bug 1143793 -- removed obj parameter ...
JS::CompileFunction
of argument names should match the number of arguments specified in nargs. chars, bytes, or srcBuf is a string containing the source code of the function. length is the length of the source code in characters. On success, JS::CompileFunction stores an function object representing the newly compiled function into fun and and returns true. Otherwise, it returns false and the value left in fun is
undefined. See Also The JSAPI User Guide contains example code using compiled scripts. MXR ID Search for JS::CompileFunction JS::Evaluate JS::Compile JS::CompileOffThread JS_ExecuteScript JS_DecompileScript bug 771705 ...
JS::CreateError
message JS::HandleString The value of Error.prototype.message. rval JS::MutableHandleValue Out parameter. Receives the created error object. Description JS::CreateError creates an Error object with specified properties. If successful, JS::CreateError stores the created error object to *rval and returns true, otherwise returns false and the value of *rval is
undefined. See Also MXR ID Search for JS::CreateError JSExnType JSErrorReport bug 984048 bug 1038238 -- change stack parameter from JS::HandleString to JS::HandleObject ...
JS::Evaluate
e the script is just an expression, the result value is simply the value of that expression. More generally, the result value is the value of the last-executed expression statement in the script that isn't in a function. If a script compiles and executes successfully, JS::Evaluate stores the result in *rval, if non-null, and returns true. Otherwise it returns false and the value left in *rval is
undefined. See Also MXR ID Search for JS::Evaluate JS::Compile JS_ExecuteScript bug 771705 bug 1097987 -- remove obj parameter ...
JS::NullHandleValue
This article covers features introduced in SpiderMonkey 24 The JS::Value that represents the JavaScript value null. Syntax const JS::HandleValue JS::NullHandleValue; Description JS::NullHandleValue is a JS::HandleValue constant that represents the JavaScript value null. See Also MXR ID Search for JS::NullHandleValue JS::
UndefinedHandleValue JS::TrueHandleValue JS::FalseHandleValue bug 865969 ...
JS::OrdinaryToPrimitive
hould not call this -- use JS::ToNumber, JS::ToBoolean, or JS::ToString instead. This should only be called from custom convert hooks. It implements the default conversion behavior shared by most objects in JS, so it's useful as a fallback. On success, JS::OrdinaryToPrimitive stores the converted value in *vp and returns true. On error or exception, it returns false, and the value left in *vp is
undefined. See Also MXR ID Search for JS::OrdinaryToPrimitive JS::ToNumber JS::ToBoolean JS::ToString bug 1103152 ...
JS::PersistentRooted
RootedValue itself can be a global variable. // JS::PersistentRootedValue persistentVal; static bool SetPersistent(JSContext* cx, unsigned argc, JS::Value* vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); // Set persistent value. persistentVal.ref() = args.get(0); // or // *persistentVal = args.get(0); // [SpiderMonkey 38] // persistentVal = args.get(0); args.rval().set
Undefined(); return true; } static bool GetPersistent(JSContext* cx, unsigned argc, JS::Value* vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); // Get persistent value. JS::RootedValue val(cx, persistentVal.ref()); // or // JS::RootedValue val(cx, *persistentVal); // [SpiderMonkey 38] // JS::RootedValue val(cx, persistentVal); args.rval().set(val); return true; } static const...
JS::ToInt32
out int32_t * Out parameter. On success, *out receives the converted floating-point value. Description JS::ToInt32 converts a JavaScript value to a signed 32bit integer. It implements the ToInt32 operator described in ECMA 262-3 ?9.5. On success, JS::ToInt32 stores the converted value in *out and returns true. On error or exception, it returns false, and the value left in *out is
undefined. See Also MXR ID Search for JS::ToInt32 bug 739541 ...
JS::ToInt64
t. v JS::HandleValue The value to convert. out int64_t * Out parameter. On success, *out receives the converted floating-point value. Description JS::ToInt64 converts a JavaScript value to a signed 64bit integer. On success, JS::ToInt64 stores the converted value in *out and returns true. On error or exception, it returns false, and the value left in *out is
undefined. See Also MXR ID Search for JS::ToInt64 bug 742188 ...
JS::ToNumber
ert. out double * Out parameter. On success, *out receives the converted floating-point value. Description JS::ToNumber converts a JavaScript value to a number. It implements the ToNumber operator described in ECMA 262-3 ?9.3. On success, JS::ToNumber stores the converted value in *out and returns true. On error or exception, it returns false, and the value left in *out is
undefined. See Also MXR ID Search for JS::ToNumber bug 739541 ...
JS::ToPrimitive
pass any other type. vp JS::MutableHandleObject Out parameter. On success, *vp receives the converted value. Description JS::ToPrimitive converts a JavaScript object, obj, to a primitive value using ECMAScript 6 ToPrimitive. On success, JS::ToPrimitive stores the converted value in *vp and returns true. On error or exception, it returns false, and the value left in *vp is
undefined. See Also MXR ID Search for JS::ToPrimitive JS::GetFirstArgumentAsTypeHint JS_DefaultValue -- old name of this function bug 1054756 - added ...
JS::ToUint16
t uint16_t * Out parameter. On success, *out receives the converted floating-point value. Description JS::ToInt16 converts a JavaScript value to an unsigned 16bit integer. It implements the ToInt16 operator described in ECMA 262-3 ?9.7. On success, JS::ToInt16 stores the converted value in *out and returns true. On error or exception, it returns false, and the value left in *out is
undefined. See Also MXR ID Search for JS::ToUint16 bug 779601 ...
JS::ToUint32
int32_t * Out parameter. On success, *out receives the converted floating-point value. Description JS::ToUint32 converts a JavaScript value to an unsigned 32bit integer. It implements the ToUint32 operator described in ECMA 262-3 ?9.5. On success, JS::ToUint32 stores the converted value in *out and returns true. On error or exception, it returns false, and the value left in *out is
undefined. See Also MXR ID Search for JS::ToUint32 bug 739541 ...
JS::ToUint64
v JS::HandleValue The value to convert. out uint64_t * Out parameter. On success, *out receives the converted floating-point value. Description JS::ToInt64 converts a JavaScript value to an unsigned 64bit integer. On success, JS::ToInt64 stores the converted value in *out and returns true. On error or exception, it returns false, and the value left in *out is
undefined. See Also MXR ID Search for JS::ToUint64 bug 742188 ...
JSNewResolveOp
id], not id. JSRESOLVE_ASSIGNING Obsolete since JSAPI 31 The property appears on the left-hand side of an assignment. JSRESOLVE_DETECTING Obsolete since JSAPI 20 The property is being used in code like "if (o.p)...", or a similar idiom where the apparent purpose of the property access is to detect whether the property exists. (This flag has been replaced with the JSCLASS_EMULATES_
UNDEFINED mechanism.) JSRESOLVE_DECLARING Obsolete since JSAPI 15 The property is being declared in a var, const, or function declaration. JSRESOLVE_CLASSNAME Obsolete since JavaScript 1.8.8 class name used when constructing. JSRESOLVE_WITH Obsolete since JavaScript 1.8.8 The lookup is occurring for a name evaluated inside a with statement. See Also JSClass bug 547140 - remove...
JSType
JSTYPE_OBJECT JavaScript objects. JSTYPE_FUNCTION Functions. JSTYPE_STRING Strings. JSTYPE_NUMBER Numbers. ...
JSVAL_IS_OBJECT
ers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determine whether a given jsval is an object or null. Syntax JSBool JSVAL_IS_OBJECT(jsval v); Description JSVAL_IS_OBJECT(v) returns true if v is either an object or JSVAL_NULL. This indicates that it is safe to call JSVAL_TO_OBJECT(v) to convert v to type JSObject *. If v is a string, number, boolean, or
undefined, the result is false. This function is obsolete and has been removed. Instead use !JSVAL_IS_PRIMITIVE(v) to detect objects and JSVAL_IS_NULL(v) to detect null. See Also bug 952650 ...
JSVAL_IS_PRIMITIVE
Obsolete since JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determine if a given jsval is of a primitive type. Syntax JSVAL_IS_PRIMITIVE(v) Description JSVAL_IS_PRIMITIVE(v) is true if v is
undefined, null, a boolean, a number, or a string. Otherwise it is false, and v is an object. See Also bug 952650 ...
JSVAL_IS_VOID
Obsolete since JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determines if a given jsval is the JavaScript value
undefined. Syntax JSVAL_IS_VOID(v) Description JSVAL_IS_VOID(v) is true if v is JSVAL_VOID, which represents the JavaScript value
undefined. Example The following code snippet illustrates how a JavaScript variable, MyItem, is conditionally tested in an if statement to see if it is void. if (JSVAL_IS_VOID(MyItem)) { ... } See Also bug 952650 ...
JSVAL_TO_BOOLEAN
at any time. Try to avoid using it. Cast a boolean JavaScript value to a C integer, either 0 or 1, without any type checking or error handling. Syntax JSBool JSVAL_TO_BOOLEAN(jsval v); Description JSVAL_TO_BOOLEAN casts the value v to a C integer, either 0 or 1. As a precondition, JSVAL_IS_BOOLEAN(v) must be true. That is, v must be either JSVAL_TRUE or JSVAL_FALSE. Otherwise the behavior is
undefined. The result is JS_TRUE or JS_FALSE respectively. These are constants of type JSBool, which is an integer type, the SpiderMonkey version of bool. JS_FALSE is 0; JS_TRUE is 1. To convert any value to a boolean, use JS_ValueToBoolean instead. That function has well-defined behavior even when the argument is an object, number, or something else. To convert a JSBool to jsval, use BOOLEAN_TO_JSVAL. See...
JSVAL_TO_DOUBLE
o avoid using it. Casts a given jsval to a jsdouble without any type checking or error handling. Syntax jsdouble JSVAL_TO_DOUBLE(jsval v); Description JSVAL_TO_DOUBLE casts a specified JS value, v, to a C floating-point number of type jsdouble. As a precondition, JSVAL_IS_DOUBLE(v) must be true. This function is not type-safe: if v is an integer, string, null, or anything else, the behavior is
undefined. To convert any value to a number, use JS_ValueToNumber instead. See Also bug 952650 ...
JSVAL_TO_GCTHING
. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Cast a jsval to a raw pointer of type void *. Syntax JSVAL_TO_GCTHING(v) Description JSVAL_TO_GCTHING casts a jsval, v, to a raw pointer. The type of the result is void *. v must be either JSVAL_NULL or a reference to a GC thing. Otherwise the resulting pointer is
undefined. JSVAL_IS_GCTHING may be used to check this. This macro is exposed in jsapi.h because other JSAPI macros make use of it. Applications should not call it directly in most cases. When possible, it is better to use a more specific macro, such as JSVAL_TO_OBJECT or JSVAL_TO_STRING. Another possible alternative is to avoid casting altogether by using an API that operates on jsvals rather than raw poin...
JSVAL_TO_OBJECT
ime. Try to avoid using it. Cast a jsval to a JSObject * without a type check. Syntax JSObject * JSVAL_TO_OBJECT(jsval v); Description JSVAL_TO_OBJECT casts the argument, v, to type JSObject *. As a precondition, JSVAL_IS_OBJECT(v) must be true. That is, v must be either a reference to an object or JSVAL_NULL. This function is not type-safe: if v is not an object or JSVAL_NULL, the behavior is
undefined. To convert a value to an object, use the JS_ValueToObject function, which has well-defined behavior even when the argument is not an object or null. See Also bug 952650 ...
JSVAL_TO_STRING
rk in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Cast a jsval to type JSString * without a type check. Syntax JSString * JSVAL_TO_STRING(jsval v); Description JSVAL_TO_STRING casts the argument, v, to type JSString *. As a precondition, JSVAL_IS_STRING(v) must be true. This function is not type-safe: if v is not a string, the behavior is
undefined. To coerce any value to a string, use the JS_ValueToString function instead. (The difference is that the latter will convert an object, array, number, or other value to a string in a type-safe way, creating a new string if needed.) To convert the return type of this macro (JSString *) to a char pointer, use JS_GetStringBytes. See Also bug 952650 ...
JSVAL_VOID
Obsolete since JSAPI 42This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. The jsval that represents the JavaScript value
undefined. Syntax JSVAL_VOID Description JSVAL_VOID is a jsval constant that represents the JavaScript value
undefined. See Also MXR ID Search for JSVAL_VOID JSVAL_NULL JSVAL_TRUE JSVAL_FALSE JSVAL_ZERO JSVAL_ONE bug 1177825 -- removed ...
JS_AlreadyHasOwnProperty
UCProperty only) The length of name, in characters; or the special value (size_t) -1 to indicate that name is null-terminated. index uint32_t (in JS_AlreadyHasOwnElement only) The index of the element to search for. foundp bool * Out parameter. *foundp receives true if the property is found or false if it is not found. If an error occurs, the value left in *foundp is
undefined. Description These functions attempt to determine whether a property already exists on a specific JSObject without modifying the object. By design, this search may not find a property that other property lookup functions, such as JS_LookupProperty, would find. For native objects--objects whose properties are stored in the default data structure provided by SpiderMonkey--these functions simp...
JS_CallFunction
ction. Obsolete since JSAPI 30. In argc, indicate the number of arguments passed to the function. In argv, pass a pointer to the actual argument values to use. rval is a pointer to a variable that will hold the function's return value, if any, on successful function execution. If the called function executes successfully, JS_CallFunction returns true. Otherwise it returns false, and rval is
undefined. Calling JS_CallFunction is safe only if the fun argument could be passed to JS_GetFunctionObject safely: that is, it is a function implemented by a JSNative or JSFastNative or the result of a call to JS_CompileFunction, JS_CompileUCFunction, JS_CompileFunctionForPrincipals, or JS_CompileUCFunctionForPrincipals. Passing any other JSFunction pointer can lead to a crash or worse. See also MXR ...
JS_ClearScope
properties, except the special __proto__ and __parent__ properties, in a single operation. Properties belonging to objects on obj's prototype chain are not affected. To remove a single property from an object, use JS_DeleteProperty. To remove a single array object element, use JS_DeleteElement. See Also JS_DeleteProperty JS_DeleteElement JS_ClearNonGlobalObject JS_SetAllNonReservedSlotsTo
Undefined bug 749371 ...
JS_DefaultValue
See Also MXR ID Search for JS_DefaultValue JS::ToPrimitive bug 1054756 - renamed to JS::ToPrimitive ...
JS_DefineProperties
opertySpec structures. Each array element defines a single property: its name, attributes, getter, and setter. The name field of the last array element must be NULL. JS_DefineProperties creates one property for each element in the array before the element with a null name field. Each property is defined as though by calling JS_DefineProperties. The initial stored value of each property created is
undefined. On success, JS_DefineProperties returns true, indicating it has created all properties listed in the array. Otherwise it returns false. See Also MXR ID Search for JS_DefineProperties JS_DefineConstDoubles JS_DefineElement JS_DefineFunction JS_DefineFunctions JS_DefineObject JS_DefineProperty JS_InitClass bug 855582 ...
JS_DeleteElement2
n JS_DeleteElement2 removes a specified element or numeric property, index, from an object, obj. If an object references an element belonging to a prototype, the element reference is removed from the object, but the prototype's element is not deleted. If deletion is successful, JS_DeleteElement2 stores true to *succeeded and returns true. Otherwise it returns false and the value of *succeeded is
undefined. Notes Per the ECMA standard, JS_DeleteElement2 removes read-only properties from objects as long as they are not also permanent. For JavaScript 1.2 and earlier, if deletion fails because the property is permanent, JS_DeleteElement2 reports the error and returns false. For JavaScript 1.3, the attempt is silently ignored. In both these cases, *succeeded will receive the stored value of the pr...
JS_DoubleIsInt32
e to compare ip int32_t * A pointer to int32_t value to compare Description JS_DoubleIsInt32 returns true if d i sequal to *ip. (comment from mozilla::NumberEqualsInt32) Casting a floating-point value that doesn't truncate to int32_t, to int32_t, induces
undefined behavior. We should definitely fix this (bug 744965), but as apparently it "works" in practice, it's not a pressing concern now. See Also MXR ID Search for JS_DoubleIsInt32 JS_DoubleToInt32 JS_DoubleToUint32 bug 631132 bug 744965 ...
JS_EvaluateScript
, the result value is simply the value of that expression. More generally, the result value is the value of the last-executed expression statement in the script that isn't in a function. If a script compiles and executes successfully, JS_EvaluateScript or JS_EvaluateUCScript stores the result in *rval, if non-null, and returns JS_TRUE. Otherwise it returns JS_FALSE and the value left in *rval is
undefined. See Also MXR ID Search for JS_EvaluateScript MXR ID Search for JS_EvaluateUCScript JS_CompileFile JS_CompileScript JS_DecompileScript JS_DestroyScript JS_EvaluateScriptForPrincipals bug 1100579 ...
JS_EvaluateScriptForPrincipals
neno is used to report the line number of the script or file where an error occurred during compilation. If the script compiles and executes successfully, *rval receives the value from the last-executed expression statement processed in the script, and JS_EvaluateScriptForPrincipals or JS_EvaluateUCScriptForPrincipals returns JS_TRUE. Otherwise it returns JS_FALSE, and the value left in *rval is
undefined. See Also JS::Evaluate JS_CompileFile JS_CompileScriptForPrincipals JS_EvaluateScript bug 980180 ...
JS_ExecuteRegExp
se stores null to *rval. If test is true, JS_ExecuteRegExp and JS_NewRegExpObjectNoStatics store the boolean value true to *rval if matches, otherwise stores null to *rval. ...
JS_ExecuteScriptPart
of a previously compiled script, script. The part parameter must be either JSEXEC_PROLOG to execute the script prolog or JSEXEC_MAIN to execute the main section of the script. If the script executes successfully, JS_ExecuteScriptPart stores the value of the last-executed expression statement in the script in *rval and returns JS_TRUE. Otherwise it returns JS_FALSE, and the value left in *rval is
undefined. To execute both parts of a script, use JS_ExecuteScript instead. See Also MXR ID Search for JS_ExecuteScriptPart JS_ExecuteScript bug 555104 ...
JS_GetArrayLength
alling JS_GetProperty and converts it to a 32-bit unsigned integer. If obj is an array (see JS_IsArrayObject), this is guaranteed to succeed, because the .length property of an array is always a number and can't be deleted or redefined. On success, JS_GetArrayLength stores the length in *lengthp and returns true. On failure, it reports an error and returns false, and the value left in *lengthp is
undefined. See Also MXR ID Search for JS_GetArrayLength JS_GetElement JS_SetArrayLength ...
JS_GetClassObject
SProtoKey The key of the prototype. objp JS::MutableHandle<JSObject*> Out parameter. If successful, receive the class constructor. Description JS_GetClassObject gets the builtin class costructor for the specified prototype key. If successful, JS_GetClassObject stores the class constructor to *objp and returns true, otherwise returns false and the value of *objp is
undefined. See Also MXR ID Search for JS_GetClassObject JS_GetClassPrototype JSProtoKey ...
JS_GetClassPrototype
key of the prototype. objp JS::MutableHandle<JSObject*> Out parameter. If successful, receive the class prototype object. Description JS_GetClassPrototype gets the builtin class costructor for the specified prototype key. If successful, JS_GetClassPrototype stores the class prototype object to *objp and returns true, otherwise returns false and the value of *objp is
undefined. See Also MXR ID Search for JS_GetClassPrototype JS_GetClassObject JSProtoKey ...
JS_GetPendingException
r must be in a request on this JSContext. vp JS::MutableHandleValue Out parameter. On success, *vp receives the current pending exception. Description If an exception has been thrown in the context cx, and it has not yet been caught or cleared, JS_GetPendingException stores the exception object in *vp and returns true. Otherwise, it returns false, and the value left in *vp is
undefined. See examples in the JSAPI Phrasebook. See Also MXR ID Search for JS_GetPendingException JS_IsExceptionPending JS_ClearPendingException JS_ReportPendingException JS_SetPendingException ...
JS_GetPropertyDefault
must be in a request on this JSContext. obj JS::HandleObject Object to search on for the property. name or id const char * or JS::HandleId Name of the property to look up. def JS::HandleValue Default value if the property is not found. vp JS::MutableHandleValue Out parameter. On success, *vp receives the current value of the property, or
undefined if no such property is found. Description JS_GetPropertyDefault examines a specified JS object obj and its prototype chain for a property with the specified name. On success, these functions set *vp to the current value of the property, or def if obj has no such property, and return true. On an error or exception, these functions return false, and the value left in *vp is
undefined. See Als...
JS_GetReservedSlot
when non-JavaScript values must be stored; the garbage collector ignores such values when it sees them. (Note that private values must not be exposed directly to JavaScript. It's only legal to store and retrieve data from private values. They cannot be returned from functions, set as properties on objects, embedded in JavaScript arrays, and so on.) New objects' reserved slots are initialized to
undefined. See Also MXR ID Search for JS_GetReservedSlot MXR ID Search for JS_SetReservedSlot bug 1184564 -- Changed jsval to JS::Value ...
JS_GetStringChars
only) A context. str JSString * The string to obtain characters from. Description JS_GetStringChars Obsolete since JavaScript 1.8.5 returns a pointer to the first element of an array of jschars. Warnings: The array is not necessarily null-terminated. To get the length of the string, use JS_GetStringLength. The program must not modify the array. If it does, the behavior is
undefined. The content of a JS string is not guaranteed to be valid UTF-16. It may contain surrogate code units that aren't properly paired. It may also contain zeroes. The array returned by this function remains valid as long as str is valid. (Eventually, str becomes unreachable, the garbage collector collects it, and the array is freed by the system.) JS_GetStringCharsZ is the same except that it alway...
JS_GetTypeName
time information. type JSType One of JSTYPE_VOID, JSTYPE_OBJECT, JSTYPE_FUNCTION, JSTYPE_STRING, JSTYPE_NUMBER, or JSTYPE_BOOLEAN. Description JS_GetTypeName returns a pointer to a string literal description of a specified JS data type, type. ...
JS_HasArrayLength
length of the array. Description JS_HasArrayLength determines if an object, obj, has a length property. If the property exists, JS_HasArrayLength stores the current value of the property in *lengthp. On success, JS_HasArrayLength returns JS_TRUE, and *lengthp receives the current value of the length property. On failure, JS_HasArrayLength returns JS_FALSE, and the value left in *lengthp is
undefined. This function differs from JS_GetArrayLength in the treatment of errors and unusual cases, like when an object's length is negative or not a number. This function may return JS_FALSE without having reported any error or exception. See Also JS_DefineElement JS_DeleteElement JS_GetArrayLength JS_GetElement JS_IsArrayObject JS_LookupElement JS_NewArrayObject JS_SetArrayLength JS...
JS_HasElement
Description JS_HasElement examines a specified JS object, obj, and its prototype chain, for an element or numeric property numbered index. If the element exists, JS_HasElement sets *foundp to true. If not, it sets *foundp to false and returns true (to indicate no error occurred). If the search fails with an error or exception, JS_HasElement returns false, and the value left in *foundp is
undefined. See Also MXR ID Search for JS_HasElement JS_DefineElement JS_DeleteElement JS_GetArrayLength JS_GetElement JS_IsArrayObject JS_LookupElement JS_NewArrayObject JS_SetArrayLength JS_SetElement ...
JS_HasInstance
t parameter. On success, *bp receives the result of the test. Description JS_HasInstance determines if a specified JS value, v, is an instance of JS object, obj. This function is equivalent to v instanceof obj test in JavaScript. On success, JS_HasInstance stores the result of the instanceof test in *bp and returns true. On error or exception, it returns false, and the value left in *bp is
undefined. When providing a prototype as obj, the prototype's JSClass must have its hasInstance method set. Otherwise JS_HasInstance returns false. See Also MXR ID Search for JS_HasInstance JS_InstanceOf ...
JS_HasOwnProperty
y(obj, name). JS_HasOwnPropertyById is the same but takes a JS::HandleId for the property name. If the property exists, this function sets *foundp to true and returns true. If the object obj has no such property, the function sets *foundp to false and returns true (to indicate that no error occurred). If an error occurs during the search, the function returns false, and the value of *foundp is
undefined. See Also MXR ID Search for JS_HasOwnProperty MXR ID Search for JS_HasOwnPropertyById bug 1163423 ...
JS_HasProperty
onding Unicode API. JS_HasPropertyById is the same but takes a JS::HandleId for the property name. If the property exists, this function sets *foundp to true and returns true. If the object obj has no such property, the function sets *foundp to false and returns true (to indicate that no error occurred). If an error occurs during the search, the function returns false, and the value of *foundp is
undefined. See Also MXR ID Search for JS_HasProperty MXR ID Search for JS_HasUCProperty MXR ID Search for JS_HasPropertyById bug 461163 ...
JS_InitStandardClasses
es the built-in JavaScript global properties. These include all the standard ECMAScript global properties defined in ECMA 262-3 ?15.1: Array, Boolean, Date, decodeURI, decodeURIComponent, encodeURI, encodeURIComponent, Error, eval, EvalError, Function, Infinity, isNaN, isFinite, Math, NaN, Number, Object, parseInt, parseFloat, RangeError, ReferenceError, RegExp, String, SyntaxError, TypeError,
undefined, and URIError as well as a few SpiderMonkey-specific globals, depending on compile-time options: escape, unescape, uneval, InternalError, Script, XML, Namespace, QName, File, Generator, Iterator, and StopIteration, as of SpiderMonkey 1.7. These global objects, functions, constructors, and constants are created as properties of obj. As a side effect, JS_InitStandardClasses establishes obj a...
JS_IsExtensible
obj JS::HandleObject The object to examine. extensible bool * Out parameter. Receives true if extensible, false otherwise. Description JS_IsExtensible queries [[Extensible]] property of the specified object, obj. If successful, JS_IsExtensible stores [[Extensible]] property to *extensible and returns true, otherwise returns false and the value of *extensible is
undefined. See also MXR ID Search for JS_PreventExtensions JS_PreventExtensions bug 492845 ...
JS_IsIdentifier
size_t The length of chars. isIdentifier bool * Out parameter. On success, *isIdentifier receives whether str is an identifier or not. Description JS_IsIdentifier tests if the given string is a valid ECMAScript identifier. On successful, JS_IsIdentifier stores the test result to *isIdentifier and returns true, otherwise returns false and the value of *isIdentifier is
undefined. JS_IsIdentifier which takes chars and length is infallible, so just returns whether the chars are an identifier. See Also MXR ID Search for JS_IsIdentifier JS_ValueToId bug 692627 bug 990484 ...
JS_NewDouble
behave as desired in some cases but not others. The new jsdouble is subject to garbage collection until you protect it using a local root, an object property, or the JS_AddRoot function. On success, JS_NewDouble returns a pointer to the new number. Otherwise it returns NULL. The application must treat the returned pointer as read-only. Modifying a jsdouble allocated with this function can cause
undefined behavior. See Also JS_NumberValue bug 549143 ...
JS_NewObject
the prototype object's properties and methods, and the new object's __proto__ property will be a reference to the prototype object. JS_NewObject: If this is NULL, a default prototype object is used. Obsolete since JSAPI 38 JS_NewObject now always uses a default prototype object. JS_NewObjectWithGivenProto: If this is NULL, the new object has no prototype; its __proto__ property is
undefined. parent JS::Handle<JSObject*> Pointer to the parent of the new object. The new object's __parent__ property will be a reference to this object. If parent is NULL, a default parent object is used. Obsolete since JSAPI 39 Description JS_NewObject creates a new object based on a specified class. cx is a pointer to a context associated with the runtime in which to est...
JS_ParseJSON
e object to be searched. chars const jschar * The characters of the string. len uint32 The length of the string. index jsint (in JS_ParseJSONWithReviver only) A reviver function to apply to the created value after parsing; see JSON.parse. vp jsval * Out parameter. *vp receives the value after parsing (and optionally, processing by the reviver). If an error occurs, the value left in *vp is
undefined. Description Use these functions to parse a sequence of characters as JSON. The parsing rules applied by these methods are exactly those specified by ECMAScript 5. Various JSON extensions like trailing commas, unquoted property names, more generous number parsing, and so on are not supported. MXR ID Search for JS_ParseJSON MXR ID Search for JS_ParseJSONWithReviver ...
JS_SetParent
ut scripts cannot assign to the __parent__ property. In fact, once an object is exposed to a script, the object's parent must not change. The JavaScript engine relies on this invariant. JS_SetParent has no way to check that this is the case, but nonetheless, applications must not call JS_SetParent on an object that has already been exposed to a script. If an application does this, the behavior is
undefined. On success, JS_SetParent returns JS_TRUE. Otherwise, it reports an error or sets an exception and returns JS_FALSE. See Also MXR ID Search for JS_SetParent bug 1136980 - removed ...
JS_SetProperty
othing happens, but this is not an error. In strict mode, a warning is issued. Otherwise, if obj has an own property with the given name, then the existing property's value is set as described below. Creation of new properties One of the cases above involves creating a new own property on obj. The name of the new property is given by name or id. The initial stored value of the new property is
undefined. Its getter and setter are the JSClass.getProperty and setProperty hooks of obj's class, and its property attributes are exactly JSPROP_ENUMERATE. After the new property is added, the JSClass.addProperty hook is called with the arguments (cx, obj, id, &v). This hook may assign to v. If the hook succeeds and the property has a stored value, then the value left in v by the addProperty hook becomes ...
JS_SetPropertyAttributes
is read only. JSPROP_PERMANENT Property cannot be deleted. JSPROP_EXPORTED Property can be imported by other objects. JSPROP_INDEX Property is actually an index into an array of properties, and is cast to a const char *. If JS_SetPropertyAttributes cannot locate an object with the specified property, it returns JS_FALSE, and the value left in *foundp is
undefined. If the specified property or the specified object does not exist, foundp is set to JS_FALSE. Then, if the property exists, but is associated with a different object, JS_SetPropertyAttributes returns JS_TRUE. Otherwise, it sets foundp to JS_TRUE, and attempts to set the attributes as specified. If the attributes can be set, JS_SetPropertyAttributes returns JS_TRUE. If not, it returns JS_FALSE. ...
JS_ShutDown
h any JSRuntime, JSContext, or other structure. This method should be called after all other JSAPI data has been properly cleaned up: every JSRuntime created with JS_NewRuntime must have been destroyed with JS_DestroyRuntime, every JSContext created with JS_NewContext must have been destroyed with JS_DestroyContext, and so on. Calling this method before all other resources have been destroyed has
undefined behavior. Failure to call this method, at present, has no adverse effects other than leaking memory. This may not always be the case; it's recommended that all embedders call this method when all other JSAPI operations have completed, to be future-proof. It is currently not possible to initialize SpiderMonkey multiple times (that is, calling JS_Init, then other JSAPI methods, then JS_ShutDown in ...
JS_ValueToBoolean
* Out parameter. On success, *bp receives the converted boolean value. Description JS_ValueToBoolean converts a specified JavaScript value, v, to a boolean value. It implements the ToBoolean operator specified in ECMA 262-3 ?9.2. On success, JS_ValueToBoolean stores the converted value in *bp and returns JS_TRUE. On error or exception, it returns JS_FALSE, and the value left in *bp is
undefined. For versions greater than JSVERSION_1_2, all objects convert to JS_TRUE, even Boolean wrapper objects like the one produced by new Boolean(false). This is the behavior specified in ECMA 262-3 ?9.2. See related discussion on Google Groups. See Also MXR ID Search for JS_ValueToBoolean JS::ToBoolean bug 934557 ...
JS_ValueToECMAInt32
functions first convert v to a floating-point number as if by calling JS_ValueToNumber; NaN values are then converted to zero. If that succeeds, the result is then converted to the target integer type. This second conversion cannot fail. On success, JS_ValueToECMAInt32 stores the converted value in *ip and returns JS_TRUE. On error or exception, it returns JS_FALSE, and the value left in *ip is
undefined. See Also JS::ToUint16 JS::ToInt32 JS::ToUint32 JS::ToInt64 JS::ToUint64 JS::ToNumber bug 933810 bug 933946 ...
JS_ValueToFunction
e a native function, this means it isn't attached to any global or enclosing scope, and therefore must not be treated like a real function. Instead, use JSVAL_IS_OBJECT and JS_ObjectIsFunction() to check whether a value is already a function, or use JS_ConvertValue() to convert a value to JSTYPE_FUNCTION safely. If v is a Function object, this returns the associated JSFunction. If v is null,
undefined, a boolean, a number, or a string, a TypeError is reported and JS_ValueToFunction returns NULL. Otherwise, v is an object. The JavaScript engine attempts to convert it to a function. (Implementation note: The actual conversion is performed by the object itself. The object's JSObjectOps.defaultValue method is called with hint=JSTYPE_FUNCTION.) JS_ValueToFunction returns a pointer to the converte...
JS_ValueToInt32
umber as if by calling JS::ToNumber. If the result is NaN, an infinity, or a number outside the 32-bit range, JS_ValueToInt32 reports an error and conversion fails. Otherwise, the floating-point number is rounded to the nearest integer value. On success, JS_ValueToInt32 stores the converted value in *ip and returns JS_TRUE. On error or exception, it returns JS_FALSE, and the value left in *ip is
undefined. JS_ValueToInt32 is pre-ECMA-262 Edition 1, and rounds differently than JS_ValueToECMAInt32 and JS::ToInt32. This routine was added for layers-based graphics programming in Netscape 4, but unless you know you need its rounding behavior, it is best to avoid it in favour of JS::ToInt32. JS::ToInt32 rounds as specified in ECMA 262-3 ?9.5, while this routine rounds by adding 0.5 to the converted flo...
JS_ValueToString
ADSAFE build, the caller must be in a request on this JSContext. v jsval The value to convert. Description JS_ValueToString converts a specified JavaScript value, v, to a string. It implements the ToString operator specified in ECMA 262-3 ?9.8. The result is like the JavaScript expression ""+v. If v is already a string, conversion succeeds. If v is true, false, null, or
undefined, conversion succeeds, and the result is the string "true", "false", "null", or "
undefined", accordingly. If v is a number, conversion succeeds, and the result is a string representation of that number as specified in ECMA 262-3 ?9.8.1. This might be "NaN", "Infinity", or "-Infinity". Otherwise the result is a decimal representation of the number, possibly using exponential notation. Otherwise v...
Redis Tips
> r.set('foo', 42, console.log) null 'OK' > r.get('foo', console.log) null '42' For the rest of this, I'm going to use the synchronous redis-cli for demonstrations. Lines beginning with redis> are input to the redis-cli. Things are Strings, Mostly As you can see from that last example, the values pointed to by keys are strings or they are nil. Nil values will be given as null in node, not
undefined. But some commands only work with numbers (like INCR); for these, if your key can't be parsed as a number, it's an error: redis> set foo pie OK redis> incr foo (error) ERR value is not an integer or out of range Atomic Counters I guess that sounds like Geiger counters. I mean counters you can update atomically. GET key SET key value EXISTS key SETNX key value INCR key INCRBY key...
Frecency algorithm
ket weight and followed-link bonus +14 10 * (140/100.0) - Fifth bucket weight and bookmarked bonus +14 10 * (140/100.0) - Fifth bucket weight and bookmarked bonus -- 252 (4 * 252 / 4) - Final frecency score Notes The number of sampled visits is min(10 most recent visits pref, total visit counts). The total visit count includes embedded,
undefined, etc visits (does not exclude invalid or embedded visits). Developer notes There are various development notes you can read about Places that may offer additional insights: Initial algorithm ideas Implementation notes History The initial algorithm design was by Mike Connor and Seth Spitzer. The initial implementation was done by Seth and Dietrich Ayala. Further features and refineme...
extIPreferenceBranch
e() Gets the value of a preference. Returns a default value if the preference does not exist. nsIVariant getValue(in AString aName, in nsIVariant aDefaultValue) Parameters aName The name of a preference aDefaultValue The default value of a preference. This will be passed back to you without any processing and can be something which would not be valid as a preference. For example, null/
undefined/an object. Return value The value of the preference or the given default value if preference does not exists. The use of a variant as the return value means that to JavaScript code the value will appear as a value of the same type as is used in the preferences file and no coercion will occur. A quoted string in the preference file will always appear as a string, even if the value of the stri...
XPCOM glue
libs libxul.pc These instructions are for Mozilla 1.8 and above. When using a SDK from Mozilla 1.7 or earlier, you must define MOZILLA_STRICT_API when using any form of the glue. Linux and Mac: Make sure the Gecko libraries are listed after your object (.o) files on the link line. Linux and Mac: Write the linker options exactly as stated (just replacing the /path/to/sdk/), otherwise you get an
undefined symbol: ...NS_TableDrivenQI...QITableEntry... at runtime (not compile time) (in debug builds) or your module just won't load (in optimized builds). In principle, #include "mozilla-config.h" should also work, if it's the first #include in .cpp, but preprocessor option is how it's usually included. For XULRunner 2.0, you also need to link against mozalloc. This is not a backwards-compatible cha...
Mozilla internal string guide
8String nsACString UTF-8 string. Converted to UTF-16 as necessary when value is used across XPConnect boundaries. DOMString nsAString UTF-16 string type used in the DOM. The same as AString with a few odd XPConnect exceptions: When the special JavaScript value null is passed to a DOMString parameter of an XPCOM method, it becomes a void DOMString. The special JavaScript value
undefined becomes the string "
undefined". C++ Signatures In IDL, in parameters are read-only, and the C++ signatures for *String parameters follows the above guidelines by using const nsAString& for these parameters. out and inout parameters are defined simply as nsAString so that the callee can write to them. IDL C++ interface nsIFoo : nsISupports { attribute AStri...
Components.classes
asses to retrieve it. Note also that it is possible that a given add-on component with a given ContractID will be present on one machine but not have been installed on another machine. If the given element in the Components.classes object is not registered on the machine then trying to access it will generate a JavaScript warning in strict mode and the value returned will be the JavaScript value
undefined. You should use the in operator to test for the element before trying to access it: if (!("@some/bogus/class;1" in Components.classes)) // do something... The properties of the Components.classes object can be enumerated using a for...in loop. Usage In order to retrieve the object for a given ContractID, you can query the Components.classes array as follows: var clazz0 = Components.classe...
Components.utils.waiveXrays
t foo = "I'm an expando"; By default, chrome code won't see foo, because it sees the content window with Xray vision, but the chrome code can waive Xray protection: // chrome code // contentWindow is an Xray var isXray = Components.utils.isXrayWrapper(gBrowser.contentWindow); // true // expandos are not visible in Xrays var foo = gBrowser.contentWindow.foo; //
undefined // you can waive Xray vision for an object var waived = Components.utils.waiveXrays(gBrowser.contentWindow); isXray = Components.utils.isXrayWrapper(waived); // false foo = waived.foo; // "I'm an expando" // waiving is transitive isXray = Components.utils.isXrayWrapper(waived.document); // false ...
imgIDecoder
a separate char * buffer would need to be used in order to call the output stream's other write() method. unsigned long writeFrom( in nsIInputStream inStr, in unsigned long count ); Parameters inStr The stream from which to read the encoded image data. count The maximum number of bytes to write to the image. Return value The number of bytes actually written to the image, or
undefined if an error occurred. See also imgIDecoderObserver imgILoad ...
nsICachingChannel
followed by OnStopRequest. Methods isFromCache() Obsolete since Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) This method finds out whether or not this channel's data is being loaded from the cache. boolean isFromCache(); Parameters None. Return value Returns true if this channel's data is being loaded from the cache, otherwise returns false. This value is
undefined before the channel fires its OnStartRequest notification and after the channel fires its OnStopRequest notification. See also nsICache ...
nsICategoryManager
egoryEntry( in string aCategory, in string aEntry ); Parameters aCategory The category being queried. ("protocol") aEntry The entry being queried. ("http") Return value The value of the given category's entry. This pointer must be released using nsIMemory.free() when it is no longer needed. Exceptions thrown NS_ERROR_NOT_AVAILABLE Indicates that either the category or entry is
undefined. Examples Print out a list of all categories This snippet shows how to print out a list of all categories in C++. nsresult PrintAllCategories() { nsresult rv; nsCOMPtr<nsIServiceManager> svcMgr; rv = NS_GetServiceManager(getter_AddRefs(svcMgr)); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsICategoryManager> catMgr; rv = svcMgr->GetServiceByContractID(NS_CATEGORYMANAGER_CONTRACT...
nsIChannel
ovides a hint to the channel as to what the MIME type is. The channel may ignore this hint in deciding on the actual MIME type that it will report. Setting contentType after onStartRequest has been fired or after open() is called will override the type determined by the channel. Setting contentType between the time that asyncOpen() is called and the time when onStartRequest is fired has
undefined behavior at this time. The value of the contentType attribute is a lowercase string. A value assigned to this attribute will be parsed and normalized as follows: Any parameters (delimited with a ';') will be stripped. If a charset parameter is given, then its value will replace the the contentCharset attribute of the channel. The stripped contentType will be lowercased. ...
nsIContentPrefService
value is to be retrieved. aCallback An optional nsIContentPrefCallback to receive the result. If desired, JavaScript callers can instead provide a function to call upon completion. Return value The preference's value is returned; this value may be a string, integer, boolean, or any other value. The result may be null (nsIDataType:VTYPE_EMPTY) if the preference's value is either null, or
undefined (nsIDataType:VTYPE_VOID) if there is no saved preference by the specified name. Exceptions thrown NS_ERROR_ILLEGAL_VALUE If aGroup is not a string, nsIURI, or null. Or if aName is null or an empty string getPrefs() Get all preferences and their values for the specified URI. Note: Prior to Gecko 2.0, the site could only be specified by nsIURI. Now a string can be used as well. nsIProp...
nsIContentViewer
Missing Description resetCloseWindow() Works in tandem with permitUnload(), if the caller decides not to close() the window it indicated it will, it is the caller's responsibility to reset that with this method. Note: @Note this method is only meant to be called on documents for which the caller has indicated that it will close the window. If that is not the case the behavior of this method is
undefined. void resetCloseWindow(); Parameters None. Exceptions thrown Missing Exception Missing Description Native code only!setBounds void setBounds( [const] in nsIntRectRef aBounds ); Parameters aBounds Missing Description Native code only!setDocumentInternal Note: Prior to Gecko 10.0 (Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 2.7), this attribute was part of nsIDocumentView...
nsIDBChangeListener
reChanged(in nsIDBChangeListener aInstigator); Parameters aInstigator The caller who changed the junk score. This can be used to filter out events that you yourself started. aInstigator may also be null. onHdrPropertyChanged() Called in the general case where any field may have changed. OnHdrPropertyChanged is called twice per change. On the first call, aPreChange is true, and aStatus is
undefined. OnHdrPropertyChanged saves any required status in aStatus (such as a filter match). The calling function stores the value of aStatus, changes the header aHdrToChange, then calls OnHdrPropertyChanged again with aPreChange false. On this second call, the stored value of aStatus is provided, so that any changes may be noted. void onHdrPropertyChanged(in nsIMsgDBHdr aHdrToChange, ...
nsIDOMMozNetworkStatsManager
A Date object representing the end of data measurement. options Optional Filtering options. NetworkStatsGetOptions is a dictionary object providing filtering options. Return value An nsIDOMDOMRequest object. If successful, the request result is an nsIDOMMozNetworkStats object describing the network statistics. If network stats are not available for some dates, then rxBytes and txBytes are
undefined for those dates. If the filtering start date is greater than the end date, an exception is thrown. Exceptions thrown NS_ERROR_INVALID_ARG The filtering start date is greater than the end date. NS_ERROR_NOT_IMPLMENTED Both appManifestURL and serviceType are specified at the same time in the NetworkStatsGetOptions dictionary. InvalidNetwork The network must be in the return of getAvailable...
nsIINIParser
{String} prop * The name of the property to get. */ function getIniValue (iniFile, section, prop) { var iniFact = Components.manager.getClassObjectByContractID( "@mozilla.org/xpcom/ini-parser-factory;1", Components.interfaces.nsIINIParserFactory ); var iniParser = iniFact.createINIParser(iniFile); try { return iniParser.getString(section,prop); } catch(e) { return
undefined; } } // Usage: var lang = getIniValue(file,"Setting","Language"); Enumerating sections This example gets a list of all the sections in the INI file. // get all sections in the ini file var sectEnum = iniParser.getSections(); // save the sections in an array var sections = []; while (sectEnum && sectEnum.hasMore()) { var section = sectEnum.getNext(); // add an array entry for each section ...
nsILocalFile
herwise contains invalid characters. getRelativeDescriptor() Returns a relative file path in an opaque, cross platform format. It is therefore not a native path. ACString getRelativeDescriptor( in nsILocalFile fromFile ); Parameters fromFile The file from which the descriptor is relative. There is no defined result if this parameter is null. Return value An opaque string value with
undefined character encoding. This string is not intended for display to users. The result returned from this method may be used with setRelativeDescriptor() to initialize a nsILocalFile instance. initWithFile() Initializes this object with another file. void initWithFile( in nsILocalFile aFile ); Parameters aFile The file this becomes equivalent to. initWithNativePath() Used to set the full...
nsIMessageListener
Each listener is invoked with its own copy of the message parameter. When the listener is called, 'this' value is the target of the message. If the message is synchronous, the possible return value is returned as JSON (will be changed to use structured clones). When there are multiple listeners to synchronous messages, each listener's return value is sent back as an element in an array.
undefined return values show up as
undefined values in the array. ...
nsINavHistoryResultNode
QueryInterface to access the corresponding specialized result node interface. Read only. uri AUTF8String The URI of the resource represented by the node. For visits and URLs, this is the URL of the page. For folders and queries, this is the place: URI of the corresponding folder or query. This may be empty for other types of objects, like host containers. Read only. viewIndex long Value with
undefined meaning for use by the view. Its initial value will be -1. The result implementation treats nodes with this property set to -1 as invisible! View-implementations may use this value to track the node index in the view, for example the tree view uses this value to indicate the row in the tree that this node is at. Other views may choose not to use this, but should inititalize this value to anything...
nsIProxyInfo
in seconds for this proxy. If a nsIProxyInfo is reported as failed via nsIProtocolProxyService.getFailoverForProxy(), then the failed proxy will not be used again for this many seconds. Read only. flags unsigned long This attribute specifies flags that modify the proxy type. The value of this attribute is the bit-wise combination of the Proxy Flags defined below. Any
undefined bits are reserved for future use. Read only. host AUTF8String This attribute specifies the hostname of the proxy server. Read only. Note: Prior to Gecko 1.8 host was available by the host method. next nsIProxyInfo Proxy info objects may be chained if several proxies could be treated equivalently. This is used to support prox...
nsIResumableChannel
ameters listener As for asyncOpen. ctxt As for asyncOpen. startPos The starting offset, in bytes, to use to download. entityID Information about the file, to match before obtaining the file. Pass an empty string to use anything. resumeAt() Prepare this channel for resuming. The request will not start until asyncOpen or open is called. Calling resumeAt after open or asyncOpen has been called has
undefined behaviour. During OnStartRequest, this channel will have a status of NS_ERROR_NOT_RESUMABLE if the file cannot be resumed, for example because the server doesn't support this. This error may occur even if startPos is 0, so that the front end can warn the user. Similarly, the status of this channel during OnStartRequest may be NS_ERROR_ENTITY_CHANGED, which indicates that the entity has changed, a...
nsIStyleSheetService
s. A user sheet loaded via this API will come before userContent.css and userChrome.css in the cascade (so the rules in it will have lower precedence than rules in those sheets). An agent sheet loaded via this API will come after ua.css in the cascade (so the rules in it will have higher precedence than rules in ua.css). The relative ordering of two user or two agent sheets loaded via this API is
undefined. Sheets added via this API take effect on all documents, including already-loaded ones, immediately. void loadAndRegisterSheet( in nsIURI sheetURI, in unsigned long type ); Parameters sheetURI URI of the stylesheet to load and register. type One of the type constants. sheetRegistered() Check if a stylesheet has been registered boolean sheetRegistered( in nsIUR...
nsIURI
done using the current URI's scheme, setting the spec to a URI with a different scheme will produce incorrect results. Therefore, only protocol handler implementations should do this. If the URI stores information from the nsIIOService interface's nsIIOService.newURI() call that created it, other than just the parsed string, the behavior of this information when setting the spec attribute is
undefined. Note: Some characters may be escaped. specIgnoringRef AUTF8String Returns a string representation of the URI without the ref (part after the #) portion. Note: Some characters may be escaped. username AUTF8String The optional username, assuming the preHost consists of "username:password". Exceptions thrown NS_ERROR_FAILURE If u...
nsIWebContentHandlerRegistrar
The following code aims to add "Outlook.com Live Mail" to list of webservice handlers. In the image below "Gmail" and "Yahoo! Mail" already exist as webservice handlers. ...
nsIZipReader
y*' is not a valid pattern. (foo|bar) will match either the pattern foo or the pattern bar. Neither of the patterns foo or bar may use the 'pat~pat2' syntax described immediately above. \ will escape a special character. Escaping is required for all special characters unless otherwise specified. All other characters match case-sensitively. An aPattern not conforming to this syntax has
undefined behavior. Return value The nsIUTF8StringEnumerator containing the matching entry names. Exceptions thrown NS_ERROR_ILLEGAL_VALUE On many but not all invalid aPattern values. getCertificatePrincipal() Returns an object describing the entity which signed an entry. parseManifest must be called first. If aEntryName is an entry in the jar, getInputStream() must be called after parseManife...
nsIAbCard/Thunderbird3
ll values from one card to another. void copy(in nsIAbCard srcCard) Parameters srcCard The source card to copy values from. equals() Returns true if this card is equal to the other card. The default implementation defines equal as this card pointing to the same object as aCard. Another implementation defines it as equality of properties and values. The exact nature of equality is still
undefined, and actual results may not match theoretical results. Most notably, the code a.equals(b) == b.equals(a) might not return true. In particular, calling equals on cards from different address books may return inaccurate results. boolean equals(in nsIAbCard card) Parameters card The card you are comparing with. Return value true if the cards are the same. generatePhoneticName() Genera...
Troubleshooting XPCOM components registration
't need to be there, you can remove it. You may be able build your component using USE_STATIC_LIBS=1 in order to remove C runtime library dependencies. Linux-specific hints Check if you have missing dependent libraries: From your Firefox (/XULRunner) install directory, run "./run-mozilla.sh `which ldd` -r path/to/your/component.so". There should be no "not found" entries and no
undefined symbols. (The -r switch from GNU ldd lists function relocations; adjust as suitable for your version) Trace shared library loading by setting the environment variable LD_DEBUG=all while launching Firefox (see `man ld.so` for details). Use strace to see if Firefox is trying to load your components. Pass the -Wl,-z,defs flag to gcc when linking your component. This will ensure that undefine...
nsIMsgCloudFileProvider
callback to receive request start and stop notices. urlForFile() Returns the URL for a file that has been uploaded. ACString urlForFile(in nsILocalFile aFile); Parameters aFile The previously uploaded file to get the URL for. Return value The string representation of the URL for the uploaded file. If the file was not uploaded with this instance of the nsIMsgCloudFileProvider, returns
undefined. cancelFileUpload() Cancels an upload currently in progress for some nsILocalFile. void cancelFileUpload(in nsILocalFile aFile); Parameters aFile The nsILocalFile that is currently being uploaded to cancel. refreshUserInfo() Refreshes the data for this user account - for example, the storage quota, or the amount of storage being used. void refreshUserInfo(in boolean aWithUI, ...
Using tab-modal prompts
x is not shown', check]); //this here is just an alert, showing the values of the prompt prompt.alert.apply(null, ['Title Not Shown In Modal', 'User Clicked OK: ' + ok + '\n' + 'Checked: ' + check.value + '\nInput Value: ' + input.value]); Note: Because the prompts are shown in a tab, if the tab is closed while the prompt is open it will throw an exception. /* Exception: prompt aborted by user
undefined:425 */ ...
Add to iPhoto
ot on an image } } This code finds the image node the user right-clicked in by calling our getCurrentNode() method, then sets the hidden state of the "Add Image to iPhoto" menu item based on whether or not an image node was found. The code to identify the node looks like this: getCurrentNode: function() { var node = document.popupNode; // If no node, just return null now if (node ==
undefined || !node) { return null; } // Is it an image node? var elemName = node.localName.toUpperCase(); if (elemName == "IMG") { return node; } // Nope, return null return null; } This starts by getting the node the popup was opened from. If this is null or
undefined, we immediately return null, indicating there is no node associated with the context menu. Otherwise, we fetc...
CType
other function, pointer, and array types, this should be a valid C type expression. ptr CType Returns a CType representing the data type "pointer to this type". This is the result of calling ctypes.PointerType(the_type). Read only. size Number The size of the type, in bytes. This is the same value as the C sizeof. Read only. Note: ctypes.void_t.size is
undefined. Methods available on all CType objects array() Returns a new CType representing an array of elements of the type on which it was called. CType array( [n] }; Parameters n Optional The number of elements in the declared array type. If this parameter is left out, the array's size is indeterminate. Return value A CType representing the data type "array of this type". This is...
FunctionType
other function, pointer, and array types, this should be a valid C type expression. ptr CType Returns a CType representing the data type "pointer to this type". This is the result of calling ctypes.PointerType(the_type). Read only. size Number The size of the type, in bytes. This is the same value as the C sizeof. Read only. Note: ctypes.void_t.size is
undefined. Method overview Methods inherited from CType CType array([n]) String toSource() String toString() FunctionType CData FunctionType CData cannot be constructed. Function pointer is created with FunctionType.ptr. CData functiontype.ptr([func]); functiontype is FunctionType CType. Parameters func A pointer value or JavaScript Function. Return...
PointerType
other function, pointer, and array types, this should be a valid C type expression. ptr CType Returns a CType representing the data type "pointer to this type". This is the result of calling ctypes.PointerType(the_type). Read only. size Number The size of the type, in bytes. This is the same value as the C sizeof. Read only. Note: ctypes.void_t.size is
undefined. Method overview Methods inherited from CType CType array([n]) String toSource() String toString() PointerType CData Syntax CData pointertype(); pointertype is PointerType CType. Return value A CData representing the newly allocated pointer. PointerType CData Properties Property Type Description contents CData Rea...
StructType
other function, pointer, and array types, this should be a valid C type expression. ptr CType Returns a CType representing the data type "pointer to this type". This is the result of calling ctypes.PointerType(the_type). Read only. size Number The size of the type, in bytes. This is the same value as the C sizeof. Read only. Note: ctypes.void_t.size is
undefined. Method overview define(fields) Methods inherited from CType CType array([n]) String toSource() String toString() Methods define() Defines a previously declared opaque type's fields. This lets you convert an opaque structure type into a defined structure type. define( fields ); Parameters fields A field specification, as de...
ctypes
String libraryName(name); Library open(libSpec); CType PointerType(typeSpec); CType StructType(name[, fields]); CData UInt64(n); Properties Property Type Description errno Number The value of the latest system error. Similar to errno in libc, available on all platforms. Cannot be set. winLastError Number|
undefined The value of the latest Windows error. Similar to GetLastError under Windows, available only for Windows. Cannot be set. Constants ABI constants These constants are used to specify the ABI used to call a native function in the library. Constant Description default_abi Corresponds to cdecl; standard libraries use this ABI. You also use this for all system calls...
UI Tour - Firefox Developer Tools
l breakpoint and execution is paused here line 85 has a logpoint which logs the contents of tablerow to the console line 100 has a conditional breakpoint The third column shows more information about the breakpoints. For example, the logpoint at line 85 logs the value of the tableRow variable to the console and the conditional breakpoint at line 100 breaks if the contents of the todoList is
undefined. Toolbar At the top of the right-hand pane, there's a toolbar: The toolbar consists of: Four buttons to control the debugger's movement through the script: Play/pause (F8): pauses or resumes execution of the script you're debugging. When it displays a "play" icon, that means the script is paused, either because you've paused it with this button or because you've hit a breakpoint. ...
Debugger.Environment - Firefox Developer Tools
h a this value referring to a Debugger.Environment instance; they may not be used as methods of other kinds of objects. names() Return an array of strings giving the names of the identifiers bound by this environment. The result does not include the names of identifiers bound by enclosing environments. getVariable(name) Return the value of the variable bound toname in this environment, or
undefined if this environment does not bindname.Name must be a string that is a valid ECMAScript identifier name. The result is a debuggee value. JavaScript engines often omit variables from environments, to save space and reduce execution time. If the given variable should be in scope, but getVariable is unable to produce its value, it returns an ordinary JavaScript object (not a Debugger.Object instanc...
Debugger.Memory - Firefox Developer Tools
debuggee code. Unlike Debugger's hooks, Debugger.Memory's handlers' return values are not significant, and are ignored. The handler functions receive the Debugger.Memory's owning Debugger instance as their this value. The owning Debugger's uncaughtExceptionHandler is still fired for errors thrown in Debugger.Memory hooks. On a new Debugger.Memory instance, each of these properties is initially
undefined. Any value assigned to a debugging handler must be either a function or
undefined; otherwise a TypeError is thrown. Handler functions run in the same thread in which the event occurred. They run in the compartment to which they belong, not in a debuggee compartment. onGarbageCollection(statistics) A garbage collection cycle spanning one or more debuggees has just been completed. The stat...
Debugger.Script - Firefox Developer Tools
n* expression or statement. False otherwise. isAsyncFunction True if this instance refers to a JSScript for an async function, defined with an async function expression or statement. False otherwise. displayName If the instance refers to a JSScript, this is the script's display name, if it has one. If the script has no display name -- for example, if it is a top-level eval script -- this is
undefined. If the script's function has a given name, its display name is the same as its function's given name. If the script's function has no name, SpiderMonkey attempts to infer an appropriate name for it given its context. For example: function f() {} // display name: f (the given name) var g = function () {}; // display name: g o.p = function () {}; // display name: o.p var q = { ...
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
nable allocation tracking in dbg's debuggees. dbg.memory.trackingAllocationSites = true; } window.demoPlotAllocations = function() { // Grab the allocation log. var log = dbg.memory.drainAllocationsLog(); // Neutralize the Debugger, and drop it on the floor // for the GC to collect. console.log("Stopping allocation tracking."); dbg.removeAllDebuggees(); dbg =
undefined; // Analyze and display the allocation log. plot(log); } function handleUncaughtException(ex) { console.log('Debugger hook threw:'); console.log(ex.toString()); console.log('Stack:'); console.log(ex.stack); }; function plot(log) { // Given the log, compute a map from allocation sites to // allocation counts. Note that stack entries are '===' if // th...
Web Console remoting - Firefox Developer Tools
We change the arguments array - we create ObjectActor instances for each object passed as an argument - and, lastly, we remove some unneeded properties (like window IDs). In the case of long strings we use the LongStringActor. The Web Console can then inspect the ar...
Animation.play() - Web APIs
The play() method of the Web Animations API's Animation Interface starts or resumes playing of an animation. If the animation is finished, calling play() restarts the animation, playing it from the beginning. Syntax animation.play(); Parameters None. Return value
undefined Example In the Growing/Shrinking Alice Game example, clicking or tapping the cake causes Alice's growing animation (aliceChange) to play forward, causing her to get bigger, as well as triggering the cake's animation. Two Animation.play()s, one EventListener: // The cake has its own animation: var nommingCake = document.getElementById('eat-me_sprite').animate( [ { transform: 'translateY(0)' }, { transform: 'translateY(-80%)' } ], { fill: 'forwards', easing: 'steps(4, end)', duration: aliceChange.e...
Animation.reverse() - Web APIs
The Animation.reverse() method of the Animation Interface reverses the playback direction, meaning the animation ends at its beginning. If called on an unplayed animation, the whole animation is played backwards. If called on a paused animation, the animation will continue in reverse. Syntax animation.reverse(); Parameters None. Return value
undefined Example In the Growing/Shrinking Alice Game example, clicking or tapping the bottle causes Alice's growing animation (aliceChange) to play backwards, causing her to get smaller. It is done by setting aliceChange's Animation.playbackRate to -1 like so: var shrinkAlice = function() { // play Alice's animation in reverse aliceChange.playbackRate = -1; aliceChange.play(); // play the bottle's animation drinking.play() } B...
AudioBuffer.copyFromChannel() - Web APIs
artInChannel); Parameters destination A Float32Array to copy the channel's samples to. channelNumber The channel number of the current AudioBuffer to copy the channel data from. startInChannel Optional An optional offset into the source channel's buffer from which to begin copying samples. If not specified, a value of 0 (the beginning of the buffer) is assumed by default. Return value
undefined. Exceptions indexSizeError One of the input parameters has a value that is outside the accepted range: The value of channelNumber specifies a channel number which doesn't exist (that is, it's greater than or equal to the value of numberOfChannels on the channel). The value of startInChannel is outside the current range of samples that already exist in the source buffer; that is, it's g...
AudioBufferSourceNode.start() - Web APIs
dway point through a 10-second audio buffer is still 5. duration Optional The duration of the sound to be played, specified in seconds. If this parameter isn't specified, the sound plays until it reaches its natural conclusion or is stopped using the stop() method. Using this parameter is functionally identical to calling start(when, offset) and then calling stop(when+duration). Return value
undefined. Exceptions TypeError A negative value was specified for one or more of the three time parameters. Please don't attempt to tamper with the laws of temporal physics. InvalidStateError start() has already been called. You can only call this function once during the lifetime of an AudioBufferSourceNode. Examples The most simple example just starts the audio buffer playing from the beginnin...
AudioNode.connect() - Web APIs
only if there is at least one DelayNode in the cycle. Otherwise, a NotSupportedError exception is thrown. This parameter is not allowed if the destination is an AudioParam. Return value If the destination is a node, connect() returns a reference to the destination AudioNode object, allowing you to chain multiple connect() calls. In some browsers, older implementations of this interface return
undefined. If the destination is an AudioParam, connect() returns
undefined. Exceptions IndexSizeError The value specified as outputIndex or inputIndex doesn't correspond to an existing input or output. InvalidAccessError The destination node is not part of the same audio context as the source node. NotSupportedError The specified connection would create a cycle (in which the audio loops back thr...
AudioNode.disconnect() - Web APIs
The disconnect() method of the AudioNode interface lets you disconnect one or more nodes from the node on which the method is called. Syntax AudioNode.disconnect(); AudioNode.disconnect(output); AudioNode.disconnect(destination); AudioNode.disconnect(destination, output); AudioNode.disconnect(destination, output, input); Return value
undefined Parameters There are several versions of the disconnect() method, which accept different combinations of parameters to control which nodes to disconnect from. If no parameters are provided, all outgoing connections are disconnected. destination Optional An AudioNode or AudioParam specifying the node or nodes to disconnect from. If this value is an AudioNode, a single node is disconnected from, with any other, optional, parameters (output and...
AudioParam.setValueCurveAtTime() - Web APIs
n. If this value is lower than AudioContext.currentTime, it is clamped to currentTime. duration A double representing the total time (in seconds) over which the parameter's value will change following the specified curve. The specified values are spaced equally along this duration. Return value A reference to this AudioParam object. Some older browser implementations of this interface return
undefined. Exceptions InvalidStateError The specified array of values has fewer than 2 items in it. RangeError The specified startTime is either negative or a non-finite value, or duration is not a finite, strictly positive number. TypeError One or more of the values in the values array is non-finite. Non-finite values are NaN, Infinity, and -Infinity. Usage notes When the parameter's value fin...
AudioScheduledSourceNode.start() - Web APIs
al A floating-point number indicating the offset, in seconds, into the audio buffer where playback should begin. If 0 is passed then the playback will start from the beginning. duration Optional A floating-point number indicating the duration, in seconds, to be played. If no value is passed then the duration will be equal to the length of the audio buffer minus the offset value Return value
undefined Exceptions InvalidStateNode The node has already been started. This error occurs even if the node is no longer running because of a prior call to stop(). RangeError The value specified for when is negative. Example This example demonstrates how to create an OscillatorNode which is scheduled to start playing in 2 seconds and stop playing 1 second after that. The times are calculated by a...
AudioScheduledSourceNode.stop() - Web APIs
Syntax AudioScheduledSourceNode.stop([when]); Parameters when Optional The time, in seconds, at which the sound should stop playing. This value is specified in the same time coordinate system as the AudioContext is using for its currentTime attribute. Omitting this parameter, specifying a value of 0, or passing a negative value causes the sound to stop playback immediately. Return value
undefined Exceptions InvalidStateNode The node has not been started by calling start(). RangeError The value specified for when is negative. Example This example demonstrates starting an oscillator node, scheduled to begin playing at once and to stop playing in one second. The stop time is determined by taking the audio context's current time from AudioContext.currentTime and adding 1 second. co...
AudioWorkletGlobalScope.registerProcessor - Web APIs
e constructor of a class derived from AudioWorkletProcessor. Note: A key-value pair { name: constructor } is saved internally in the AudioWorkletGlobalScope once the processor is registered. The name is to be referred to when creating an AudioWorkletNode based on the registered processor. A new processor by the given name is internally created and associated with the new node. Return value
undefined Exceptions NotSupportedError The name is an empty string, or a constructor under the given name is already registered. Registering the same name twice is not allowed. TypeError The processorCtor is not a callable constructor, or the parameterDescriptors property of the constructor exists and doesn't return an array of AudioParamDescriptor-based objects. Examples In...
AudioWorkletProcessor.process - Web APIs
nected or are inactive (producing zero-channels). A processor implementing such a node should return true from the process method for the period of the tail-time, beginning as soon as inputs are found that contain zero-channels. An example of such a node is the DelayNode -- it has a tail-time equal to its delayTime property. Note: An absence of the return statement means that the method returns
undefined, and as this is a falsy value, it is like returning false. Omitting an explicit return statement may cause hard-to-detect problems for your nodes. Exceptions As the process() method is implemented by the user, it can throw anything. If an uncaught error is thrown, the node will emit an onprocessorerror event and will output silence for the rest of its lifetime. Examples In this example we cre...
Background Tasks API - Web APIs
an to avoid causing the user to experience performance lag. window.requestIdleCallback = window.requestIdleCallback || function(handler) { let startTime = Date.now(); return setTimeout(function() { handler({ didTimeout: false, timeRemaining: function() { return Math.max(0, 50.0 - (Date.now() - startTime)); } }); }, 1); } If window.requestIdleCallback is
undefined, we create it here. The function begins by recording the time at which our implementation was called. We'll be using that to compute the value returned by our shim for timeRemaining(). Then we call setTimeout(), passing into it a function which runs the callback passed into our implementation of requestIdleCallback(). The callback is passed an object which conforms to IdleDeadline, with didTimeo...
BiquadFilterNode.getFrequencyResponse() - Web APIs
array is NaN. These are unitless values. phaseResponseOutput A Float32Array to receive the computed phase response values in radians for each frequency value in the input frequencyArray. For any frequency in frequencyArray whose value is outside the range 0.0 to sampleRate/2 (where sampleRate is the sample rate of the AudioContext), the corresponding value in this array is NaN. Return value
undefined Exceptions InvalidAccessError The three arrays provided are not all of the same length. Example In the following example we are using a biquad filter on a media stream (for the full demo, see our stream-source-buffer demo live, or read the source.) As part of this demo, we get the frequency responses for this biquad filter, for five sample frequencies. We first create the Float32Arrays we...
BluetoothDevice - Web APIs
Product Version field in the pnp_id characteristic in the device_information service. BluetoothDevice.paired Read only A Boolean value indicating whether the device is paired with the system. BluetoothDevice.gattServer Read only A reference to the device's GATT server or null if the device is disconnected. Methods BluetoothDevice.watchAdvertisments() A Promise that resolves to
undefined or is rejected with an error if advetisments can't shown for any reason. BluetoothDevice.unwatchAdvertisments() Stops watching for advertisments. BluetoothDevice.connectGATT() A Promise that resolves to an instance of BluetoothGATTRemoteServer. Specifications Specification Status Comment Web BluetoothThe definition of 'BluetoothDevice' in that specification. ...
CSS.registerProperty() - Web APIs
MString indicating the name of the property being defined. syntax Optional A DOMString representing the expected syntax of the defined property. Defaults to "*". inherits A boolean value defining whether the defined property should be inherited (true), or not (false). Defaults to false. initialValue Optional A DOMString representing the initial value of the defined property. Return value
undefined. Exceptions InvalidModificationError The given name has already been registered. SyntaxError The given name isn't a valid custom property name (starts with two dashes, e.g. --foo). TypeError The required name and/or inherits dictionary members were not provided. Examples The following will register a custom property, --my-color, using registerProperty(), as a color, give it a defau...
CSSKeywordValue.value - Web APIs
e A USVString. Examples The following example resets the CSS display property to its defaults. let indicator = Document.getElementById('indicator'); indicator.attributeStyleMap.set('display', new CSSKeywordValue('initial')); indicator.attributeStyleMap.get('display').value // 'initial' Specifications Specification Status Comment CSS Typed OM Level 1The definition of '
undefined' in that specification. Working Draft Initial definition. ...
CSSNumericValue.toSum() - Web APIs
The toSum() method of the CSSNumericValue interface converts the object's value to a CSSMathSum object to values of the specified unit. Syntax var cssMathSum = CSSNumericValue.toSum(units); Parameters units The units to convert to. Return value A CSSNumericValue. Exceptions SyntaxError
undefined TypeError Indicates that an invalid type was passed to the method. Examples let v = CSS.px("23").add(CSS.percent("4")).add(CSS.cm("3")).add(CSS.in("9")); v.toString() // => "calc(23px + 4% + 3cm + 9in)" v.toSum("px", "percent").toString() // => "calc(1000.39px + 4%)" Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'toSum' in that specification. Working Draft Initial definition. ...
CSSStyleDeclaration.setProperty() - Web APIs
tring containing the new property value. If not specified, treated as the empty string. Note: value must not contain "!important" -- that should be set using the priority parameter. priority Optional is a DOMString allowing the "important" CSS priority to be set. If not specified, treated as the empty string. The following values are accepted: String value "important" Keyword
undefined String empty value "" Return value
undefined Exceptions DOMException (NoModificationAllowedError): if the property or declaration block is read only. If priority can be omitted, JavaScript has a special simpler syntax for setting a CSS property on a style declaration object: style.cssPropertyName = 'value'; Examples In this example we have three buttons, which can be presse...
CSSStyleDeclaration - Web APIs
ported CSS properties. Methods CSSStyleDeclaration.getPropertyPriority() Returns the optional priority, "important". CSSStyleDeclaration.getPropertyValue() Returns the property value given a property name. CSSStyleDeclaration.item() Returns a CSS property name by its index, or the empty string if the index is out-of-bounds. An alternative to accessing nodeList[i] (which instead returns
undefined when i is out-of-bounds). This is mostly useful for non-JavaScript DOM implementations. CSSStyleDeclaration.removeProperty() Removes a property from the CSS declaration block. CSSStyleDeclaration.setProperty() Modifies an existing CSS property or creates a new CSS property in the declaration block. CSSStyleDeclaration.getPropertyCSSValue() Only supported via getComputedStyle in Firefox. R...
CSSStyleSheet.addRule() - Web APIs
The obsolete CSSStyleSheet interface's addRule() legacy method adds a new rule to the stylesheet. You should avoid using this method, and should instead use the more standard insertRule() method. Syntax var result = cssStyleSheet.addRule(selector, styleBlock, index); Parameters selector A DOMString specifying the selector portion of the CSS rule. The default is the string
undefined. styleBlock A DOMString indicating the style block to apply to elements matching the selector. The default is the string
undefined. index Optional An optional index into the stylesheet's CSSRuleList at which to insert the new rule. If index is not specified, the next index after the last item currently in the list is used (that is, the value of cssStyleSheet.cssRules.length). Return value Always returns ...
CSSStyleSheet.deleteRule() - Web APIs
The CSSStyleSheet method deleteRule() removes a rule from the stylesheet object. Syntax cssStyleSheet.deleteRule(index) Parameters index The index into the stylesheet's CSSRuleList indicating the rule to be removed. Return value
undefined Example This example removes the first rule from the stylesheet myStyles. myStyles.deleteRule(0); Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleSheet.deleteRule()' in that specification. Working Draft ...
CSSStyleSheet.removeRule() - Web APIs
moves a rule from the stylesheet object. It is functionally identical to the standard, preferred method deleteRule(). Note: This is a legacy method which has been replaced by the standard method deleteRule(). You should use that instead. Syntax cssStyleSheet.removeRule(index) Parameters index The index into the stylesheet's CSSRuleList indicating the rule to be removed. Return value
undefined Example This example removes the first rule from the stylesheet myStyles. myStyles.removeRule(0); You can rewrite this to use the standard deleteRule() method very easily: myStyles.deleteRule(0); Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleSheet.removeRule()' in that specification. Working Draft ...
CSSUnparsedValue.forEach() - Web APIs
lback The function to execute for each element, taking three arguments: currentValue The value of the current element being processed. indexOptional The index of the current element being processed. arrayOptional The CSSUnparsedValue that forEach() is being called on. thisArg Optional Value to use as this (i.e the reference Object) when executing callback. Return value
undefined. Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'forEach()' in that specification. Working Draft Initial definition. ...
Cache.add() - Web APIs
erations, you'll need to use Cache.put() directly. Note: add() will overwrite any key/value pair previously stored in the cache that matches the request. Syntax cache.add(request).then(function() { // request has been added to the cache }); Parameters request The request you want to add to the cache. This can be a Request object or a URL. Return value A Promise that resolves with
undefined. Exceptions Exception Happens when TypeError The URL scheme is not http or https. The Response status is not in the 200 range (i.e., not a successful response.) This occurs if the request does not return successfully, but also if the request is a cross-origin no-cors request (in which case the reported status is always 0.) Examples This code blo...
Cache.addAll() - Web APIs
ulting put() operation would overwrite a previous cache entry stored by the same addAll() method. Syntax cache.addAll(requests[]).then(function() { // requests have been added to the cache }); Parameters requests An array of string URLs that you want to be fetched and added to the cache. You can specify the Request object instead of the URL. Return value A Promise that resolves with
undefined. Exceptions Exception Happens when TypeError The URL scheme is not http or https. The Response status is not in the 200 range (i.e., not a successful response.) This occurs if the request does not return successfully, but also if the request is a cross-origin no-cors request (in which case the reported status is always 0.) Examples This code blo...
Cache.put() - Web APIs
ult, Cache.add/Cache.addAll can't be used to store opaque responses, whereas Cache.put can. Syntax cache.put(request, response).then(function() { // request/response pair has been added to the cache }); Parameters request The Request object or URL that you want to add to the cache. response The Response you want to match up to the request. Return value A Promise that resolves with
undefined. Note: The promise will reject with a TypeError if the URL scheme is not http or https. Examples This example is from the MDN sw-test example (see sw-test running live). Here we wait for a FetchEvent to fire. We construct a custom response like so: Check whether a match for the request is found in the CacheStorage using CacheStorage.match(). If so, serve that. If not, open the v1 cache u...
Cache - Web APIs
// If there is an entry in the cache for event.request, then response will be defined // and we can just return it. Note that in this example, only font resources are cached. console.log(' Found response in cache:', response); return response; } // Otherwise, if there is no entry in the cache for event.request, response will be //
undefined, and we need to fetch() the resource. console.log(' No response for %s found in cache. About to fetch ' + 'from network...', event.request.url); // We call .clone() on the request since we might use it in a call to cache.put() later on. // Both fetch() and cache.put() "consume" the request, so we need to make a copy. // (see /docs/Web/API/Request/clone) ...
CanvasCaptureMediaStreamTrack.requestFrame() - Web APIs
eam. Applications that need to carefully control the timing of rendering and frame capture can use requestFrame() to directly specify when it's time to capture a frame. To prevent automatic capture of frames, so that frames are only captured when requestFrame() is called, specify a value of 0 for the captureStream() method when creating the stream. Syntax stream.requestFrame(); Return value
undefined Usage notes There is currently an issue flagged in the specification pointing out that at this time, no exceptions are being thrown if the canvas isn't origin-clean. This may change in the future, so it would be wise to plan ahead and watch for exceptions such as SecurityError (although the specific error that might be thrown is not mentioned in the spec, this is a likely candidate). Example ...
CanvasRenderingContext2D.createPattern() - Web APIs
(<video>, by using the capture of the video) HTMLCanvasElement (<canvas>) ImageBitmap OffscreenCanvas repetition A DOMString indicating how to repeat the pattern's image. Possible values are: "repeat" (both directions) "repeat-x" (horizontal only) "repeat-y" (vertical only) "no-repeat" (neither direction) If repetition is specified as an empty string ("") or null (but not
undefined), a value of "repeat" will be used. Return value CanvasPattern An opaque object describing a pattern. Examples Creating a pattern from an image This example uses the createPattern() method to create a CanvasPattern with a repeating source image. Once created, the pattern is assigned to the canvas context's fill style and applied to a rectangle. The original image looks like this: HT...
CanvasRenderingContext2D.fillText() - Web APIs
mber of pixels wide the text may be once rendered. If not specified, there is no limit to the width of the text. However, if this value is provided, the user agent will adjust the kerning, select a more horizontally condensed font (if one is available or can be generated without loss of quality), or scale down to a smaller font size in order to fit the text in the specified width. Return value
undefined. Examples Drawing filled text This example writes the words "Hello world" using the fillText() method. HTML First, we need a canvas to draw into. This code creates a context 400 pixels wide and 150 pixels across. <canvas id="canvas" width="400" height="150"></canvas> JavaScript The JavaScript code for this example follows. const canvas = document.getElementById('canvas'); const ctx = ca...
CanvasRenderingContext2D.lineTo() - Web APIs
ing the sub-path's last point to the specified (x, y) coordinates. Like other methods that modify the current path, this method does not directly render anything. To draw the path onto a canvas, you can use the fill() or stroke() methods. Syntax ctx.lineTo(x, y); Parameters x The x-axis coordinate of the line's end point. y The y-axis coordinate of the line's end point. Return value
undefined. Examples Drawing a straight line This example draws a straight line using the lineTo() method. HTML <canvas id="canvas"></canvas> JavaScript The line begins at (30, 50) and ends at (150, 100). const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath(); // Start a new path ctx.moveTo(30, 50); // Move the pen to (30, 50) ctx.lineTo(150...
CanvasRenderingContext2D.putImageData() - Web APIs
HTML <canvas id="canvas"></canvas> JavaScript var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); function putImageData(ctx, imageData, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight) { var data = imageData.data; var height = imageData.height; var width = imageData.width; dirtyX = dirtyX || 0; dirtyY = dirtyY || 0; dirtyWidth = dirtyWidth !==
undefined? dirtyWidth: width; dirtyHeight = dirtyHeight !==
undefined? dirtyHeight: height; var limitBottom = dirtyY + dirtyHeight; var limitRight = dirtyX + dirtyWidth; for (var y = dirtyY; y < limitBottom; y++) { for (var x = dirtyX; x < limitRight; x++) { var pos = y * width + x; ctx.fillStyle = 'rgba(' + data[pos*4+0] + ',' + data[pos*4+1] ...
CanvasRenderingContext2D.setLineDash() - Web APIs
eters segments An Array of numbers that specify distances to alternately draw a line and a gap (in coordinate space units). If the number of elements in the array is odd, the elements of the array get copied and concatenated. For example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25]. If the array is empty, the line dash list is cleared and line strokes return to being solid. Return value
undefined. Examples Basic example This example uses the setLineDash() method to draw a dashed line above a solid line. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Dashed line ctx.beginPath(); ctx.setLineDash([5, 15]); ctx.moveTo(0, 50); ctx.lineTo(300, 50); ctx.stroke(); // Solid line ctx.beginPath(); ctx.
CanvasRenderingContext2D.strokeText() - Web APIs
The maximum width the text may be once rendered. If not specified, there is no limit to the width of the text. However, if this value is provided, the user agent will adjust the kerning, select a more horizontally condensed font (if one is available or can be generated without loss of quality), or scale down to a smaller font size in order to fit the text in the specified width. Return value
undefined. Examples Drawing text outlines This example writes the words "Hello world" using the strokeText() method. HTML First, we need a canvas to draw into. This code creates a context 400 pixels wide and 150 pixels high. <canvas id="canvas" width="400" height="150"></canvas> JavaScript The JavaScript code for this example follows. const canvas = document.getElementById('canvas'); const ctx...
Client.postMessage() - Web APIs
client.postMessage(message[, transfer]); client.postMessage(message[, { transfer }]); Parameters message The message to send to the client. This can be any structured-clonable type. transfer Optional A sequence of objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side. Return value
undefined. Examples Sending a message from a service worker to a client: addEventListener('fetch', event => { event.waitUntil(async function() { // Exit early if we don't have access to the client. // Eg, if it's cross-origin. if (!event.clientId) return; // Get the client. const client = await clients.get(event.clientId); // Exit early if we don't get the client. // Eg, i...
Clients.claim() - Web APIs
en a service worker is initially registered, pages won't use it until they next load. The claim() method causes those pages to be controlled immediately. Be aware that this results in your service worker controlling pages that loaded regularly over the network, or possibly via a different service worker. Syntax await clients.claim(); Parameters None. Return value A Promise that resolves to
undefined. Example The following example uses claim() inside service worker's "activate" event listener so that clients loaded in the same scope do not need to be reloaded before their fetches will go through this service worker. self.addEventListener('activate', event => { event.waitUntil(clients.claim()); }); Specifications Specification Status Comment Service WorkersThe de...
Clients.get() - Web APIs
The get() method of the Clients interface gets a service worker client matching a given id and returns it in a Promise. Syntax self.clients.get(id).then(function(client) { // do something with your returned client }); Parameters id A DOMString representing the id of the client you want to get. Return value A Promise that resolves to a Client object or
undefined. Examples self.clients.get(id).then(function(client) { self.clients.openWindow(client.url); }); Specifications Specification Status Comment Service WorkersThe definition of 'get()' in that specification. Working Draft Initial definition ...
ContentIndex.add() - Web APIs
mpty String, this is the default. homepage article video audio icons: Optional An Array of image resources, defined as an Object with the following data: src: A url String of the source image. sizes: Optional A String representation of the image size. type: Optional The MIME type of the image. Return value Returns a Promise that resolves with
undefined Exceptions TypeError If the service worker's registration is not present or the service worker does not contain a FetchEvent. If the id, title, description or url are missing, not of type String, or an empty String. If icons images are not of image type. Examples Here we're declaring an item in the correct format and creating an asynchronous function which uses the add method to registe...
ContentIndex.delete() - Web APIs
The delete() method of the ContentIndex interface unregisters an item from the currently indexed content. Calling delete() only affects the index. It does not delete anything from the Cache. Syntax ContentIndex.delete(id).then(...); Parameters This method receives no parameters. Return value Returns a Promise that resolves with
undefined Exceptions No exceptions are thrown. Examples Below is an asynchronous function, that removes an item from the content index. We receive a reference to the current ServiceWorkerRegistration, which allows us to access the index property and thus access the delete method. async function unregisterContent(article) { // reference registration const registration = await navigator.serviceWorker.ready; // feature detect Content Index if ...
CustomElementRegistry.get() - Web APIs
The get() method of the CustomElementRegistry interface returns the constructor for a previously-defined custom element. Syntax constructor = customElements.get(name); Parameters name The name of the custom element whose constructor you want to return a reference to. Return value The constructor for the named custom element, or
undefined if there is no custom element definition with that name. Examples customElements.define('my-paragraph', class extends HTMLElement { constructor() { super(); let template = document.getElementById('my-paragraph'); let templateContent = template.content; const shadowRoot = this.attachShadow({mode: 'open'}) .appendChild(templateContent.cloneNode(true)); } }) // Return a reference to the my-paragraph constructor l...
CustomElementRegistry - Web APIs
The CustomElementRegistry interface provides methods for registering custom elements and querying registered elements. To get an instance of it, use the window.customElements property. Methods CustomElementRegistry.define() Defines a new custom element. CustomElementRegistry.get() Returns the constuctor for the named custom element, or
undefined if the custom element is not defined. CustomElementRegistry.upgrade() Upgrades a custom element directly, even before it is connected to its shadow root. CustomElementRegistry.whenDefined() Returns an empty promise that resolves when a custom element becomes defined with the given name. If such a custom element is already defined, the returned promise is immediately fulfilled. Examples The following code is taken from our word-count-web-compo...
DOMHighResTimeStamp - Web APIs
eptable. If neither of the above determines the time origin, then the time origin is the time at which the navigation responsible for creating the window's current Document took place. If the script's global object is a WorkerGlobalScope (that is, the script is running as a web worker), the time origin is the moment at which the worker was created. In all other cases, the time origin is
undefined. Methods This type has no methods. Usage notes You can get the current timestamp value--the time that has elapsed since the context was created--by calling the performance method now(). This method is available in both Window and Worker contexts. Example To determine how much time has elapsed since a particular point in your code, you can do something like this: let startTime = performanc...
DOMTokenList.forEach() - Web APIs
isArg]); Parameters callback Function to execute for each element, eventually taking three arguments: currentValue The current element being processed in the array. currentIndex The index of the current element being processed in the array. listObj The array that forEach() is being applied to. thisArg Optional Value to use as this when executing callback. Return value
undefined. Example In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We when retrieve an iterator containing the values using forEach(), writing each one to the <span>'s Node.textContent inside the forEach() inner function. HTML <span class="a b c"></span> JavaScript let span = document.querySelector("span"); let classes = span...
DOMTokenList.remove() - Web APIs
The remove() method of the DOMTokenList interface removes the specified tokens from the list. Syntax tokenList.remove(token1[, token2[, ...tokenN]]); Parameters tokenN A DOMString representing the token you want to remove from the list. If the string is not in the list, no error is thrown, and nothing happens. Return value
undefined Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We then remove a token from the list, and write the list into the <span>'s Node.textContent. First, the HTML: <span class="a b c"></span> Now the JavaScript: let span = document.querySelector("span"); let classes = span.classList; classes.remove("c"); span.textContent = classes; The output looks like this: To remove m...
DOMTokenList - Web APIs
is indexed beginning with 0 as with JavaScript Array objects. DOMTokenList is always case-sensitive. Properties DOMTokenList.length Read only Is an integer representing the number of objects stored in the object. DOMTokenList.value A stringifier property that returns the value of the list as a DOMString. Methods DOMTokenList.item(index) Returns the item in the list by its index, or
undefined if index is greater than or equal to the list's length. DOMTokenList.contains(token) Returns true if the list contains the given token, otherwise false. DOMTokenList.add(token1[, token2[, ...tokenN]]) Adds the specified token(s) to the list. DOMTokenList.remove(token1[, token2[, ...tokenN]]) Removes the specified token(s) from the list. DOMTokenList.replace(oldToken, newToken) Replaces to...
DataTransferItem.getAsString() - Web APIs
The DataTransferItem.getAsString() method invokes the given callback with the drag data item's string data as the argument if the item's kind is a Plain unicode string (i.e. kind is string). Syntax dataTransferItem.getAsString(callback); Parameters callback A callback function that has access to the data transfer item's string data. See Callback below for details. Return value
undefined Callback The callback parameter is a callback function which accepts one parameter: DOMString The drag data item's string data. The callback return value is
undefined. Example This example shows the use of the getAsString() method as an inline function in a drop event handler. function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = ev.dataTransfer.items; for (var i...
DataTransferItemList.DataTransferItem() - Web APIs
le syntax (that is DataTransferItem[index]). Syntax dataItem = DataTransferItem[index]; Parameters index The zero-based index of the item in the drag data list to return. Return value The DataTransferItem object at the specified index in the item list. If the index is less than zero or greater than or equal to the number of items in the list (as indicated by the list's length property,
undefined is returned. The returned value is never null. Example This example shows how to use drag and drop. JavaScript function dragstart_handler(ev) { console.log("dragStart"); // Add this element's id to the drag payload so the drop handler will // know which element to add to its tree var dataList = ev.dataTransfer.items; dataList.add(ev.target.id, "text/plain"); // Add some other item...
DataTransferItemList.clear() - Web APIs
lear() removes all DataTransferItem objects from the drag data items list, leaving the list empty. The drag data store in which this list is kept is only writable while handling the dragstart event. While handling drop, the drag data store is in read-only mode, and this method silently does nothing. No exception is thrown. Syntax DataTransferItemList.clear(); Parameters None. Return value
undefined Example This example shows the use of the clear() method. HTML <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</d...
DataTransferItemList.remove() - Web APIs
he specified index from the list. If the index is less than zero or greater than one less than the length of the list, the list will not be changed. Syntax DataTransferItemList.remove(index); Parameters index The zero-based index number of the item in the drag data list to remove. If the index doesn't correspond to an existing item in the list, the list is left unchanged. Return value
undefined. Exceptions InvalidStateError The drag data store is not in read/write mode, so the item can't be removed. Example This example shows the use of the remove() method. JavaScript function dragstart_handler(ev) { console.log("dragStart"); // Add this element's id to the drag payload so the drop handler will // know which element to add to its tree var dataList = ev.dataTransfer.ite...
Document.getElementsByClassName() - Web APIs
Here we'll find all div elements that have a class of 'test': var testElements = document.getElementsByClassName('test'); var testDivs = Array.prototype.filter.call(testElements, function(testEleme...
Document.requestStorageAccess() - Web APIs
to receive prompts. For example, if you want to configure Firefox to automatically grant access on the first site where requestStorageAccess() is called and then prompt afterwards, you should adjust the value of the dom.storage_access.max_concurrent_auto_grants preference to 1. Syntax var promise = document.requestStorageAccess(); Parameters None. Return value A Promise that fulfills with
undefined if the access to first-party storage was granted, and rejects if access was denied. When the promise gets resolved, the resolve handler will run as if a user gesture is being processed, whether the promise was fulfilled or rejected: In the former case, code can then start to call APIs that require user activation and things can move forward. In the latter case, code can run to inform the use...
Document.title - Web APIs
s "Goodbye World!" </script> </body> </html> Notes This property applies to HTML, SVG, XUL, and other documents in Gecko. For HTML documents the initial value of document.title is the text content of the <title> element. For XUL it's the value of the title attribute of the <xul:window> or other top-level XUL element. In XUL, accessing document.title before the document is fully loaded has
undefined behavior: document.title may return an empty string and setting document.title may have no effect. Specifications Specification Status Comment HTML Living StandardThe definition of 'document.title' in that specification. Living Standard ...
EffectTiming.iterationStart - Web APIs
irst run of the animation at which to begin the animation performance, but any positive, non-infinite value is allowed. Since all animations' iteration indexes start at 0, a value of 0.5 would start the animation halfway through its first iteration or loop. Meanwhile, a value of 1.2 means the animation will begin playback 20% of the way through its second iteration, and so forth. It's currently
undefined what happens if you specify a value of iterationStart which is greater than the value of AnimationEffectTimingProperties.iterations. See issue 170 in the Web Animations API specification's issue tracker for details and status of any changes to the specification in this regard. Specifications Specification Status Comment Web AnimationsThe definition of 'iterationStart' i...
Element.releasePointerCapture() - Web APIs
Element interface releases (stops) pointer capture that was previously set for a specific (PointerEvent) pointer. See the Element.setPointerCapture() method for a description of pointer capture and how to set it for a particular element. Syntax targetElement.releasePointerCapture(pointerId); Parameters pointerId The pointerId of a PointerEvent object. Return value This method returns
undefined. Exceptions Exception Explanation InvalidPointerId pointerId does not match any of the active pointers. Example This example sets pointer capture on a <div> when you press down on it. This lets you slide the element horizontally, even when you pointer moves outside of its boundaries. HTML <div id="slider">SLIDE ME</div> CSS div { width: 140px; height:...
Element.removeAttribute() - Web APIs
The Element method removeAttribute() removes the attribute with the specified name from the element. Syntax element.removeAttribute(attrName); Parameters attrName A DOMString specifying the name of the attribute to remove from the element. If the specified attribute does not exist, removeAttribute() returns without generating an error. Return value
undefined. Usage notes You should use removeAttribute() instead of setting the attribute value to null either directly or using setAttribute(). Many attributes will not behave as expected if you set them to null. DOM methods dealing with element's attributes: Not namespace-aware, most commonly used methods Namespace-aware variants (DOM Level 2) DOM Level 1 methods for dealing with Attr nodes directly (seldom used) DOM Level 2 namespace-...
Element.requestFullscreen() - Web APIs
l A FullscreenOptions object providing options that control the behavior of the transition to full-screen mode. Currently, the only option is navigationUI, which controls whether or not to show navigation UI while the element is in full-screen mode. The default value is "auto", which indicates that the browser should decide what to do. Return value A Promise which is resolved with a value of
undefined when the transition to full screen is complete. Exceptions Rather than throw a traditional exception, the requestFullscreen() procedure announces error conditions by rejecting the Promise it has returned. The rejection handler receives one of the following exception values: TypeError The TypeError exception may be delivered in any of the following situations: The document containing the...
Element.setAttribute() - Web APIs
his works but is non-standard). See the example below for a practical demonstration. Since the specified value gets converted into a string, specifying null doesn't necessarily do what you expect. Instead of removing the attribute or setting its value to be null, it instead sets the attribute's value to the string "null". If you wish to remove an attribute, call removeAttribute(). Return value
undefined. Exceptions InvalidCharacterError The specified attribute name contains one or more characters which are not valid in attribute names. Example In the following example, setAttribute() is used to set attributes on a <button>. HTML <button>Hello World</button> JavaScript var b = document.querySelector("button"); b.setAttribute("name", "helloButton"); b.setAttribute("disabled", ""); T...
Element.setPointerCapture() - Web APIs
nt instead of the normal (or hit test) target at a pointer's location. This can be used to ensure that an element continues to receive pointer events even if the pointer device's contact moves off the element (such as by scrolling or panning). Syntax targetElement.setPointerCapture(pointerId); Parameters pointerId The pointerId of a PointerEvent object. Return value This method returns
undefined. Exceptions Exception Explanation InvalidPointerId pointerId does not match any of the active pointers. Example This example sets pointer capture on a <div> when you press down on it. This lets you slide the element horizontally, even when you pointer moves outside of its boundaries. HTML <div id="slider">SLIDE ME</div> CSS div { width: 140px; height:...
Event.stopPropagation() - Web APIs
The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed. If you want to stop those behaviors, see the preventDefault() method. Syntax event.stopPropagation(); Parameters None. Return value
undefined. Examples See Example 5: Event Propagation in the Examples chapter for a more detailed example of this method and event propagation in the DOM. Specifications Specification Status Comment DOMThe definition of 'Event.stopPropagation()' in that specification. Living Standard DOM4The definition of 'Event.stopPropagation()' in that specification. Obsolete ...
EventTarget.removeEventListener() - Web APIs
ure Optional Specifies whether the EventListener to be removed is registered as a capturing listener or not. If this parameter is absent, a default value of false is assumed. If a listener is registered twice, one with capture and one without, remove each one separately. Removal of a capturing listener does not affect a non-capturing version of the same listener, and vice versa. Return value
undefined Matching event listeners for removal Given an event listener previously added by calling addEventListener(), you may eventually come to a point at which you need to remove it. Obviously, you need to specify the same type and listener parameters to removeEventListener(). But what about the options or useCapture parameters? While addEventListener() will let you add the same listener more than on...
ExtendableEvent.waitUntil() - Web APIs
events can rely on a completely upgraded state. The waitUntil() method must be initially called within the event callback, but after that it can be called multiple times, until all the promises passed to it settle. Note: The behaviour described in the above paragraph was fixed in Firefox 43 (see bug 1180274). Syntax extendableEvent.waitUntil(promise); Parameters A Promise. Return value
undefined. Example Using waitUntil() within a service worker's install event: addEventListener('install', event => { const preCache = async () => { const cache = await caches.open('static-v1'); return cache.addAll([ '/', '/about/', '/static/styles.css' ]); }; event.waitUntil(preCache()); }); Specifications Specification Status Comment Service...
FetchEvent.respondWith() - Web APIs
ions ends up using the request URL for the resulting Window.location. This means sites can still provide an "alternate" view of a web page when offline without changing the user-visible URL. Syntax fetchEvent.respondWith( // Promise that resolves to a Response. ); Parameters A Response or a Promise that resolves to a Response. Otherwise, a network error is returned to Fetch. Return value
undefined. Exceptions Exception Notes NetworkError A network error is triggered on certain combinations of FetchEvent.request.mode and Response.type values, as hinted at in the "global rules" listed above. InvalidStateError The event has not been dispatched or respondWithWith() has already been invoked. Examples This fetch event tries to return a response ...
FetchEvent - Web APIs
r FetchEvent() Creates a new FetchEvent object. This constructor is not typically used. The browser creates these objects itself and provides them to fetch event callbacks. Properties Inherits properties from its ancestor, Event. FetchEvent.clientId Read only The id of the same-origin client that initiated the fetch. FetchEvent.preloadResponse Read only A Promise for a Response, or
undefined if this fetch is not a navigation, or navigation preload is not enabled. FetchEvent.replacesClientId Read only The id of the client that is being replaced during a page navigation. FetchEvent.resultingClientId Read only The id of the client that replaces the previous client during a page navigation. FetchEvent.request Read only The Request the browser intends to make. Methods Inherits...
FileSystemDirectoryEntry.getDirectory() - Web APIs
texts. successCallback Optional A method to be called once the FileSystemDirectoryEntry has been created. The method receives a single parameter: the FileSystemDirectoryEntry object representing the directory in question. errorCallback Optional A method to be called if an error occurs. Receives as its sole input parameter a FileError object describing the error which occurred. Return value
undefined. Errors If an error occurs and an errorCallback was specified, it gets called with a single parameter: a FileError object describing the error. The FileError.code specifies what type of error occurred, as follows: FileError.NOT_FOUND_ERR The create option was not specified (or was specified as false), and the directory doesn't exist. FileError.PATH_EXISTS_ERR The create and exclusive opti...
FileSystemDirectoryEntry.getFile() - Web APIs
eful in Web contexts. successCallback Optional A method to be called once the FileSystemFileEntry has been created. The method receives a single parameter: the FileSystemFileEntry object representing the file in question. errorCallback Optional A method to be called if an error occurs. Receives as its sole input parameter a FileError object describing the error which occurred. Return value
undefined. Errors If an error occurs and an errorCallback was specified, it gets called with a single parameter: a FileError object describing the error. The {domxref("FileError.code")}} specifies what type of error occurred, as follows: FileError.NOT_FOUND_ERR The create option was not specified (or was specified as false), and the file doesn't exist. FileError.PATH_EXISTS_ERR The create and exclu...
FileSystemDirectoryEntry.removeRecursively() - Web APIs
rectoryEntry.removeRecursively(successCallback[, errorCallback]); Parameters successCallback A function to call once the directory removal process has completed. The callback has no parameters. errorCallback Optional A function to be called if an error occurs while attempting to remove the directory subtree. Receives a FileError describing the error which occurred as input. Return value
undefined. Errors If an error occurs and an errorCallback was specified, it gets called with a single parameter: a FileError object describing the error. The FileError.code specifies what type of error occurred, as follows: FileError.INVALID_MODIFICATION_ERR An attempt was made to remove the root directory; this is not permitted. FileError.NO_MODIFICATION_ALLOWED_ERR The file system's state doesn't...
FileSystemDirectoryReader.readEntries() - Web APIs
SystemDirectoryEntry objects, which represent directories. If there are no files left, or you've already called readEntries() on this FileSystemDirectoryReader, the array is empty. errorCallback Optional A callback function which is called if an error occurs while reading from the directory. It receives one input parameter: a FileError object describing the error which occurred. Return value
undefined. Example In this example, a drop zone is created, which responds to the drop event by scanning through the dropped files and directories, outputting a hierarchical directory listing. HTML content The HTML establishes the drop zone itself, which is a <div> element with the ID "dropzone", and an unordered list element with the ID "listing". <p>Drag files and/or directories to the box below!</p...
FileSystemEntry.copyTo() - Web APIs
ccessCallback Optional A function which is called when the copy operation is succesfully completed. Receives a single input parameter: a FileSystemEntry based object providing the copied item's new details. errorCallback Optional An optional callback which is executed if an error occurs while copying the items. There's a single parameter: a FileError describing what went wrong. Return value
undefined. Errors FileError.INVALID_MODIFICATION_ERR The requested operation involves an impossible change, such as moving a directory inside itself or one of its own child directories, or copying an item within the same directory without renaming it. FileError.QUOTA_EXCEEDED_ERR The operation exceeded the user's storage quota, or there isn't enough storage space left to complete the operation. Ex...
FileSystemEntry.getMetadata() - Web APIs
ack]); Parameters successCallback A function which is called when the copy operation is succesfully completed. Receives a single input parameter: a Metadata object with information about the file. errorCallback Optional An optional callback which is executed if an error occurs while looking up the metadata. There's a single parameter: a FileError describing what went wrong. Return value
undefined. Errors FileError.NOT_FOUND_ERR The FileSystemEntry refers to an item which doesn't exist. FileError.SECURITY_ERR Security restrictions prohibit obtaining the requested metadata. Example This example checks the size of a log file in a temporary folder and, if it exceeds a megabyte, moves it into a different directory. workingDirectory.getFile("tmp/log.txt", {}, function(fileEntry) { ...
FileSystemEntry.getParent() - Web APIs
ed. The callback receives a single input parameter: a FileSystemDirectoryEntry object representing the parent directory. The parent of the root directory is considered to be the root directory, itself, so be sure to watch for that. errorCallback Optional An optional callback which is executed if an error occurs. There's a single parameter: a FileError describing what went wrong. Return value
undefined. Errors FileError.INVALID_STATE_ERR The operation failed because the file system's state doesn't permit it. This can happen, for example, if the file system's cached state differs from the actual state of the file system. FileError.NOT_FOUND_ERR The specified path could not be found. FileError.SECURITY_ERR Security restrictions prohibit obtaining the parent directory's information. Exa...
FileSystemEntry.moveTo() - Web APIs
successCallback Optional A function which is called when the move operation is succesfully completed. Receives a single input parameter: a FileSystemEntry based object providing the moved item's new details. errorCallback Optional An optional callback which is executed if an error occurs while moving the items. There's a single parameter: a FileError describing what went wrong. Return value
undefined. Errors FileError.INVALID_MODIFICATION_ERR The requested operation involves an impossible change, such as moving a directory inside itself or one of its own child directories, or copying an item within the same directory without renaming it. FileError.QUOTA_EXCEEDED_ERR The operation exceeded the user's storage quota, or there isn't enough storage space left to complete the operation. Ex...
FileSystemEntry.remove() - Web APIs
ell as all of its contents and its subdirectories, call FileSystemDirectoryEntry.removeRecursively() instead. Syntax FileSystemEntry.remove(successCallback[, errorCallback]); Parameters successCallback A function which is called once the file has been successfully removed. errorCallback Optional An optional callback which is called if the attempt to remove the file fails. Return value
undefined. Errors FileError.INVALID_MODIFICATION_ERR The specified entry was the file system's root directory, or the specified entry is a directory which isn't empty. FileError.INVALID_STATE_ERR The file system's cached state is inconsistent with its state on disk, so the file could not be deleted for safety reasons. FileError.NO_MODIFICATION_ALLOWED_ERR The file system's state doesn't permit rem...
FileSystemFileEntry.createWriter() - Web APIs
rs successCallback A callback function which is called when the FileWriter has been created successfully; the FileWriter is passed into the callback as the only parameter. errorCallback Optional If provided, this must be a method which is caled when an error occurs while trying to create the FileWriter. This callback receives as input a FileError object describing the error. Return value
undefined. Example This example establishes a method, writeToFileEntry(), which outputs a text string to the file corresponding to the passed-in directory entry. function writeToFileEntry(entry, text) { entry.createWriter(function(fileWriter) { let data = Blob([text], { type: "text/plain" }); fileWriter.write(data); }, function(fileError) { /* do whatever to handle the error */ }); } ...
FileSystemFileEntry.file() - Web APIs
e has been created successfully; the File is passed into the callback as the only parameter. errorCallback Optional If provided, this must be a method which is called when an error occurs while trying to create the File. This callback receives as input a FileError object describing the error. Editor's note: We need to find out what kinds of errors can occur and document them. Return value
undefined. Example This example establishes a method, readFile(), reads a text file and calls a specified callback function with the received text (in a String object) once the read is completed. If an error occurs, a specified (optional) error callback is called. function readFile(entry, successCallback, errorCallback) { entry.file(function(file) { let reader = new FileReader(); reader.onloa...
Using the Frame Timing API - Web APIs
ted. Creating an observer To observe "frame" performance entry types, the application first creates a PerformanceObserver object with a specific frame observer callback. In the following example, two observers for the "frame" performance entry type are created and the first observer constructor uses inline function syntax. ...
HTMLMediaElement.load() - Web APIs
ly useful when you've made dynamic changes to the set of sources available for the media element, either by changing the element's src attribute or by adding or removing <source> elements nested within the media element itself. load() will reset the element and rescan the available sources, thereby causing the changes to take effect. Syntax mediaElement.load(); Parameters None. Return value
undefined. Usage notes Calling load() aborts all ongoing operations involving this media element, then begins the process of selecting and loading an appropriate media resource given the options specified in the <audio> or <video> element and its src attribute or child <source> element(s). This is described in more detail in Supporting multiple formats in Video and audio content. The process of aborting...
HTMLMediaElement.seekToNextFrame() - Web APIs
dia is already at the last frame, a seeked event occurs, followed immediately by an ended event. If there is no video on the media element, or the media isn't seekable, nothing happens. Syntax var seekCompletePromise = HTMLMediaElement.seekToNextFrame(); HTMLMediaElement.seekToNextFrame(); Return value A Promise which is fulfilled once the seek operation has completed. Firefox 49 returns
undefined instead of a promise, and performs the seek operation synchronously. Specifications Not part of any specification. ...
HTMLObjectElement.setCustomValidity - Web APIs
Examples In this example, we pass the ID of an input element, and set different error messages depending on whether the value is missing, too low or too high. Additionally you must call the reportValidity method on the same element or nothing will happen. ...
IDBCursor.delete() - Web APIs
is set to null. Be aware that you can't call delete() (or IDBCursor.update()) on cursors obtained from IDBIndex.openKeyCursor(). For such needs, you have to use IDBIndex.openCursor() instead. Note: This feature is available in Web Workers. Syntax myIDBCursor.delete(); Returns An IDBRequest object on which subsequent events related to this operation are fired. The result attribute is set to
undefined. Exceptions This method may raise a DOMException of one of the following types: Exception Description TransactionInactiveError This IDBCursor's transaction is inactive. ReadOnlyError The transaction mode is read-only. InvalidStateError The cursor was created using IDBIndex.openKeyCursor, is currently being iterated, or has iterated past its e...
IDBCursor.key - Web APIs
The cursor's key can be any data type. Note: This feature is available in Web Workers. Syntax var key = cursor.key; Value A value of any type. Example In this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. Within each iteration we log the key of the cursor to the console, something like this (its the album title in each case, which is our key). ...
IDBCursor.primaryKey - Web APIs
The cursor's primary key can be any data type. Note: This feature is available in Web Workers. Syntax var value = cursor.primaryKey; Value A value of any data type. Example In this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. ...
IDBCursor - Web APIs
returns null or throws an exception, even if the cursor is currently being iterated, has iterated past its end, or its transaction is not active. IDBCursor.direction Read only Returns the direction of traversal of the cursor. See Constants for possible values. IDBCursor.key Read only Returns the key for the record at the cursor's position. If the cursor is outside its range, this is set to
undefined. The cursor's key can be any data type. IDBCursor.primaryKey Read only Returns the cursor's current effective primary key. If the cursor is currently being iterated or has iterated outside its range, this is set to
undefined. The cursor's primary key can be any data type. IDBCursor.request Read only Returns the IDBRequest that was used to obtain the cursor. Methods IDBCursor.advance() ...
IDBObjectStore.createIndex() - Web APIs
ify a locale for the index. Any sorting operations performed on the data via key ranges will then obey sorting rules of that locale (see locale-aware sorting.) You can specify its value in one of three ways: string: A string containing a specific locale code, e.g. en-US, or pl. auto: The platform default locale will be used (may be changed by user agent settings.) null or
undefined: If no locale is specified, normal JavaScript sorting will be used -- not locale-aware. Return value An IDBIndex object: the newly created index. Exceptions This method may raise a DOMException of one of the following types: Exception Description ConstraintError Occurs if an index with the same name already exists in the database. Index name...
IDBObjectStore.delete() - Web APIs
Note: This feature is available in Web Workers. Syntax var request = objectStore.delete(Key); var request = objectStore.delete(KeyRange); Parameters Key The key of the record to be deleted, or an IDBKeyRange to delete all records with keys in range. Return value An IDBRequest object on which subsequent events related to this operation are fired. The request.result attribute is set to
undefined. Exceptions This method may raise a DOMException of the following types: Exception Description TransactionInactiveError This object store's transaction is inactive. ReadOnlyError The object store's transaction mode is read-only. InvalidStateError The object store has been deleted. DataError The key is not a valid key or a key...
IDBObjectStore.deleteIndex() - Web APIs
ted database, used during a version upgrade. Note that this method must be called only from a VersionChange transaction mode callback. Note that this method synchronously modifies the IDBObjectStore.indexNames property. Note: This feature is available in Web Workers. Syntax objectStore.deleteIndex(indexName); Parameters indexName The name of the existing index to remove. Return value
undefined Exceptions This method may raise a DOMException of one of the following types: Exception Description InvalidStateError Occurs if the method was not called from a versionchange transaction mode callback. TransactionInactiveError Occurs if the transaction this IDBObjectStore belongs to is not active (e.g. has been deleted or removed.) In Firefox previous t...
IDBObjectStore.get() - Web APIs
object, and, in a separate thread, returns the object store selected by the specified key. This is for retrieving specific records from an object store. If a value is successfully found, then a structured clone of it is created and set as the result of the request object. Note: This method produces the same result for: a) a record that doesn't exist in the database and b) a record that has an
undefined value. To tell these situations apart, call the openCursor() method with the same key. That method provides a cursor if the record exists, and no cursor if it does not. Note: This feature is available in Web Workers. Syntax var request = objectStore.get(key); Parameters key The key or key range that identifies the record to be retrieved. Return value An IDBRequest object on which subse...
IDBObjectStore.getAll() - Web APIs
face returns an IDBRequest object containing all objects in the object store matching the specified parameter or all objects in the store if no parameters are given. If a value is successfully found, then a structured clone of it is created and set as the result of the request object. This method produces the same result for: a record that doesn't exist in the database a record that has an
undefined value To tell these situations apart, you either call the openCursor() method with the same key. That method provides a cursor if the record exists, and no cursor if it does not. the count() method with the same key, which will return 1 if the row exists and 0 if it doesn't. Syntax var request = objectStore.getAll(); var request = objectStore.getAll(query); var request = objectStore.getA...
IDBObjectStore.getAllKeys() - Web APIs
IDBRequest object retrieves record keys for all objects in the object store matching the specified parameter or all objects in the store if no parameters are given. If a value is successfully found, then a structured clone of it is created and set as the result of the request object. This method produces the same result for: a record that doesn't exist in the database a record that has an
undefined value To tell these situations apart, you need to call the openCursor() method with the same key. That method provides a cursor if the record exists, and no cursor if it does not. Syntax var request = objectStore.getAllKeys(); var request = objectStore.getAllKeys(query); var request = objectStore.getAllKeys(query, count); Parameters query Optional A value that is or resolves to an IDBKey...
IIRFilterNode.getFrequencyResponse() - Web APIs
oat32Array containing an array of frequencies, specified in Hertz, which you want to filter. magResponseOutput A Float32Array to receive the computed magnitudes of the freqency response for each frequency value in the frequencyArray. phaseResponseOutput A Float32Array to receive the computed phase response values in radians for each frequency value in the input frequencyArray. Return value
undefined Exceptions NotSupportedError The three arrays provided are not all of the same length. Examples In the following example we are using an IIR filter on a media stream (for a complete full demo, see our stream-source-buffer demo live, or read its source.) As part of this demo, we get the frequency responses for this IIR filter, for five sample frequencies. We first create the Float32Array o...
Basic concepts - Web APIs
object store or index. A valid key path can include one of the following: an empty string, a JavaScript identifier, or multiple JavaScript identifiers separated by periods or an array containing any of those. It cannot include spaces. value Each record has a value, which could include anything that can be expressed in JavaScript, including boolean, number, string, date, object, array, regexp,
undefined, and null. When an object or array is stored, the properties and values in that object or array can also be anything that is a valid value. Blobs and files can be stored, cf. specification . Range and scope scope The set of object stores and indexes to which a transaction applies. The scopes of read-only transactions can overlap and execute at the same time. On the other hand, the sco...
IntersectionObserver.disconnect() - Web APIs
The IntersectionObserver method disconnect() stops watching all of its target elements for visibility changes. Syntax intersectionObserver.disconnect(); Parameters None. Return value
undefined. Specifications Specification Status Comment Intersection ObserverThe definition of 'IntersectionObserver.disconnect()' in that specification. Working Draft Initial definition. ...
IntersectionObserver.observe() - Web APIs
allows multiple elements' intersection changes to be processed by a single call to the callback. Syntax IntersectionObserver.observe(targetElement); Parameters targetElement An element whose visibility within the root is to be monitored. This element must be a descendant of the root element (or contained wtihin the current document, if the root is the document's viewport). Return value
undefined. Examples <<<...>>> Specifications Specification Status Comment Intersection ObserverThe definition of 'IntersectionObserver.observe()' in that specification. Working Draft Initial definition. ...
IntersectionObserver.unobserve() - Web APIs
The IntersectionObserver method unobserve() instructs the IntersectionObserver to stop observing the specified target element. Syntax IntersectionObserver.unobserve(target); Parameters target The Element to cease observing. If the specified element isn't being observed, this method does nothing and no exception is thrown. Return value
undefined. Example This snippet simply shows an observer being created, an element being observed, and then being unobserved. var observer = new IntersectionObserver(callback); observer.observe(document.getElementById("elementToObserve")); /* ... */ observer.unobserve(document.getElementById("elementToObserve")); Specifications Specification Status Comment Intersection ObserverThe definition of 'IntersectionObserver.unobser...
Keyboard.unlock() - Web APIs
The unlock() method of the Keyboard interface unlocks all keys captured by the Keyboard.lock() method and returns synchronously. Syntax Keyboard.unlock() Parameters None. Return value
undefined Specifications Specification Status Comment Keyboard MapThe definition of 'Keyboard' in that specification. Editor's Draft Defines the Keyboard interface. Keyboard LockThe definition of 'unlock()' in that specification. Editor's Draft Initial definition. ...
KeyboardEvent.keyCode - Web APIs
r Alt key pressed. When implementing a shortcut key handler, the keypress event is usually better (at least when Gecko is the runtime in use). See Gecko Keypress Event for details. Example window.addEventListener("keydown", function (event) { if (event.defaultPrevented) { return; // Should do nothing if the default action has been cancelled } var handled = false; if (event.key !==
undefined) { // Handle the event with KeyboardEvent.key and set handled true. } else if (event.keyCode !==
undefined) { // Handle the event with KeyboardEvent.keyCode and set handled true. } if (handled) { // Suppress "double action" if event handled event.preventDefault(); } }, true); Specifications Specification Status Comment Document Object Model ...
KeyboardLayoutMap.forEach() - Web APIs
ck The function to execute for each element, taking three arguments: currentValue The value of the current element being processed. index Optional The index of the current element being processed. array Optional The KeyboardLayoutMap that forEach() is being called on. thisArg Optional Value to use as this (i.e the reference Object) when executing callback. Return value
undefined. Specifications Specification Status Comment Keyboard MapThe definition of 'forEach()' in that specification. Editor's Draft Initial definition. ...
LockedFile.getMetadata() - Web APIs
ehavior may change in the future. Summary The getMetadata method allows to retrieve some metadata about the locked file. Syntax var request = instanceOfLockedFile.getMetadata(param); Parameters param Optional An object used to request specific metadata. Each key is a boolean where true means the metadata is expected and where false means it is not expected. Note that if the key is
undefined, it is considered as if it were true. The following metadata are supported: size : will provide the size of the file lastModified : will provide the date when the file was last modified Return A FileRequest object. In case of success, the request's result is an object with the metadata requested through the param object. They have the following format: size : a number lastModified : a...
MediaKeyStatusMap.forEach() - Web APIs
yStatusMap.forEach(callback[, thisArg]) Parameters callback Function to execute for each element, taking three arguments: currentValue The current element being processed in the array. index The index of the current element being processed in the array. array Which array forEach() is being applied to. thisArg Optional Value used as this when executing callback. Returns
undefined. Specifications Specification Status Comment Encrypted Media Extensions Recommendation Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFire...
MediaKeyStatusMap.get() - Web APIs
Specifications Specification Status Comment Encrypted Media Extensions Recommendation Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
MediaKeyStatusMap - Web APIs
Iterator object containing an array of [key, value] for each element in the status map, in insertion order. MediaKeyStatusMap.forEach(callback[, argument]) Read only Calls callback once for each key-value pair in the status map, in insertion order. If argument is present it will be passed to the callback. MediaKeyStatusMap.get() Read only Returns the value associated with the given key, or
undefined if there is none. MediaKeyStatusMap.has() Read only Returns a boolean asserting whether a value has been associated with the given key. MediaKeyStatusMap.keys() Read only Returns a new Iterator object containing keys for each element in the status map, in insertion order. MediaKeyStatusMap.values() Read only Returns a new Iterator object containing values for each element in the status m...
MediaRecorder.pause() - Web APIs
browser queues a task that runs the below steps: If MediaRecorder.state is "inactive", raise a DOM InvalidState error and terminate these steps. If not, continue to the next step. Set MediaRecorder.state to "paused". Stop gathering data into the current Blob, but keep it available so that recording can be resumed later on. Raise a pause event. Syntax MediaRecorder.pause() Return value
undefined. Exceptions InvalidStateError The MediaRecorder is currently "inactive"; you can't pause recording if it's not active. If you call pause() while already paused, it silently does nothing. Example ... pause.onclick = function() { mediaRecorder.pause(); console.log("recording paused"); } ... Specifications Specification Status Comment MediaStream Recor...
MediaRecorder.start() - Web APIs
rder.stop event. Syntax mediaRecorder.start(timeslice) Parameters timeslice Optional The number of milliseconds to record into each Blob. If this parameter isn't included, the entire media duration is recorded into a single Blob unless the requestData() method is called to obtain the Blob and trigger the creation of a new Blob into which the media continues to be recorded. Return value
undefined. Exceptions Errors that can be detected immediately are thrown as DOM exceptions. All other errors are reported through error events sent to the MediaRecorder object. You can implement the onerror event handler to respond to these errors. InvalidModificationError The number of tracks on the stream being recorded has changed. You can't add or remove tracks while recording media. InvalidStat...
MediaSession.setActionHandler() - Web APIs
MString representing an action type to listen for. It will be one of play, pause, seekbackward, seekforward, seekto, skipad,previoustrack, or nexttrack. Further details on the action types can be found below under Media session actions. callback A function to call when the specified action type is invoked. The callback receives no input parameters, and should not return a value. Return value
undefined. Description To remove a previously-established action handler, call setActionHandler() again, specifying null as the callback. The action handler receives as input a single parameter: an object conforming to the MediaSessionActionDetails dictionary, which provides both the action type (so the same function can handle multiple action types), as well as data needed in order to perform the actio...
MediaSession.setPositionState() - Web APIs
hod on the navigator object's mediaSession object. Syntax navigator.mediaSession.setPositionState(stateDict); Parameters stateDict Optional An object conforming to the MediaPositionState dictionary, providing updated information about the playback position and speed of the document's ongoing media. If the object is empty, the existing playback state information is cleared. Return value
undefined. Exceptions TypeError This error can occur in an array of circumstances: The specified MediaPositionState object's duration is missing, negative, or null. position is missing or null, or is either negative or greater than duration. The playbackRate is zero. Example In this example, a player for a non-standard media file format, written in JavaScript, uses setInterval() to e...
MediaSource.clearLiveSeekableRange() - Web APIs
The clearLiveSeekableRange() method of the MediaSource interface clears a seekable range previously set with a call to setLiveSeekableRange(). Syntax mediaSource.clearLiveSeekableRange() Parameters None. Return value
undefined Specifications Specification Status Comment Media Source ExtensionsThe definition of 'clearLiveSeekableRange()' in that specification. Recommendation Initial definition. ...
MediaSource.endOfStream() - Web APIs
and maybe retry the network request immediately or wait until the network is back up (via some kind of polling.) decode: Terminates playback and signals that a decoding error has occured. This can be used to indicate that a parsing error has occured while fetching media data; maybe the data is corrupt, or is encoded using a codec that the browser doesn't know how to decode. Return value
undefined Exceptions Exception Explanation InvalidStateError MediaSource.readyState is not equal to open, or one or more of the SourceBuffer objects in MediaSource.sourceBuffers are being updated (i.e. their SourceBuffer.updating property is true.) Example The following snippet is from a simple example written by Nick Desaulniers (view the full demo live, or download t...
MediaSource.removeSourceBuffer() - Web APIs
The removeSourceBuffer() method of the MediaSource interface removes the given SourceBuffer from the SourceBuffers list associated with this MediaSource object. Syntax mediaSource.removeSourceBuffer(sourceBuffer); Parameters sourceBuffer The SourceBuffer object to be removed. Return value
undefined Exceptions Exception Explanation NotFoundError The supplied sourceBuffer doesn't exist in MediaSource.sourceBuffers. Examples for (i = 0; i < 10; i++) { var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec); } mediaSource.removeSourceBuffer(mediaSource.sourceBuffers[0]); Specifications Specification Status Comment Media Source ExtensionsThe definition of 'removeSourceBuffer()' in that specification. Recommenda...
MediaSource.setLiveSeekableRange() - Web APIs
by the HTMLMediaElement.seekable property will have a start timestamp no greater than this value. end The end of the seekable range to set in seconds measured from the beginning of the source. If the duration of the media source is positive infinity, then the TimeRanges object returned by the HTMLMediaElement.seekable property will have an end timestamp no less than this value. Return value
undefined Example // TBD Specifications Specification Status Comment Media Source ExtensionsThe definition of 'setLiveSeekableRange()' in that specification. Recommendation Initial definition. ...
MediaStream.addTrack() - Web APIs
The MediaStream.addTrack() method adds a new track to the stream. The track is specified as a parameter of type MediaStreamTrack. If the specified track is already in the stream's track set, this method has no effect. Syntax stream.addTrack(track); Parameters track A MediaStreamTrack to add to the stream. Return value
undefined Example Specifications Specification Status Comment Media Capture and StreamsThe definition of 'addTrack()' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.aspectRatio - Web APIs
ionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax aspectConstraintSupported = supportedConstraintsDictionary.aspectRatio; Value This property is present in the dictionary (and its value is always true) if the user agent supports the aspectRatio constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get
undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().aspectRatio) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications ...
MediaTrackSupportedConstraints.autoGainControl - Web APIs
control as well; it's typically a feature provided by microphones. Syntax autoGainSupported = supportedConstraintsDictionary.autoGainControl; Value This property is present in the dictionary (and its value is always true) if the user agent supports the autoGainControl constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get
undefined if you try to look at its value. Example This example simply displays whether or not your browser supports the autoGainControl constraint. HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().autoGainControl) { result.inn...
MediaTrackSupportedConstraints.channelCount - Web APIs
y calling navigator.mediaDevices.getSupportedConstraints(). Syntax channelCountConstraintSupported = supportedConstraintsDictionary.channelCount; Value This property is present in the dictionary (and its value is always true) if the user agent supports the channelCount constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get
undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().channelCount) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications ...
MediaTrackSupportedConstraints.deviceId - Web APIs
dictionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax deviceIdConstraintSupported = supportedConstraintsDictionary.deviceId; Value This property is present in the dictionary (and its value is always true) if the user agent supports the deviceId constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get
undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().deviceId) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications ...
MediaTrackSupportedConstraints.echoCancellation - Web APIs
vigator.mediaDevices.getSupportedConstraints(). Syntax echoCancellationConstraintSupported = supportedConstraintsDictionary.echoCancellation; Value This property is present in the dictionary (and its value is always true) if the user agent supports the echoCancellation constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get
undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().echoCancellation) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications ...
MediaTrackSupportedConstraints.facingMode - Web APIs
nary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax facingModeConstraintSupported = supportedConstraintsDictionary.facingMode; Value This property is present in the dictionary (and its value is always true) if the user agent supports the facingMode constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get
undefined if you try to look at its value. Example HTML <div id="result"> </div> CSS #result { font: 14px "Arial", sans-serif; } JavaScript let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().facingMode) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification ...
MediaTrackSupportedConstraints.groupId - Web APIs
ts dictionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax groupIdConstraintSupported = supportedConstraintsDictionary.groupId; Value This property is present in the dictionary (and its value is always true) if the user agent supports the groupId constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get
undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().groupId) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications ...
MediaTrackSupportedConstraints.height - Web APIs
aints dictionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax heightConstraintSupported = supportedConstraintsDictionary.height; Value This property is present in the dictionary (and its value is always true) if the user agent supports the height constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get
undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().height) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications S...
MediaTrackSupportedConstraints.latency - Web APIs
ts dictionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax latencyConstraintSupported = supportedConstraintsDictionary.latency; Value This property is present in the dictionary (and its value is always true) if the user agent supports the latency constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get
undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().latency) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications ...
MediaTrackSupportedConstraints.noiseSuppression - Web APIs
Syntax noiseSuppressionSupported = supportedConstraintsDictionary.noiseSuppression; Value This property is present in the dictionary (and its value is always true) if the user agent supports the noiseSuppression constraint (and therefore supports noise suppression on audio tracks). If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get
undefined if you try to look at its value. Example This example simply displays whether or not your browser supports the noiseSuppression constraint. HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().noiseSuppression) { result.i...
MediaTrackSupportedConstraints.sampleRate - Web APIs
nary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax sampleRateConstraintSupported = supportedConstraintsDictionary.sampleRate; Value This property is present in the dictionary (and its value is always true) if the user agent supports the sampleRate constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get
undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().sampleRate) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications ...
MediaTrackSupportedConstraints.sampleSize - Web APIs
nary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax sampleSizeConstraintSupported = supportedConstraintsDictionary.sampleSize; Value This property is present in the dictionary (and its value is always true) if the user agent supports the sampleSize constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get
undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().sampleSize) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications ...
MediaTrackSupportedConstraints.volume - Web APIs
aints dictionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax volumeConstraintSupported = supportedConstraintsDictionary.volume; Value This property is present in the dictionary (and its value is always true) if the user agent supports the volume constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get
undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().volume) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result ...
MediaTrackSupportedConstraints.width - Web APIs
straints dictionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax widthConstraintSupported = supportedConstraintsDictionary.width; Value This property is present in the dictionary (and its value is always true) if the user agent supports the width constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get
undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().width) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Sp...
MerchantValidationEvent.complete() - Web APIs
chantvalidation event, passing in the data fetched from the validationURL. Syntax merchantValidationEvent.complete(validationData); merchantValidationEvent.complete(merchantSessionPromise); Parameters validationData or merchantSessionPromise An object containing the data needed to complete the merchant validation process, or a Promise which resolves to the validation data. Return value
undefined. Exceptions This exception may be passed into the rejection handler for the promise: InvalidStateError The event did not come directly from the user agent, but was instead dispatched by other code. another payment request is currently being processed, the current payment request is not currently being displayed to the user, or payment information is currently being updated. Example In th...
MimeTypeArray - Web APIs
meTypeArray.item() Returns the MimeType object with the specified index. MimeTypeArray.namedItem() Returns the MimeType object with the specified name. Example The following example tests whether a plugin is available for the application/pdf mime type and if so, which plugin that is. var mimeTypes = navigator.MimeType; var flashPlugin = mimeTypes['video/x-flv']; if (typeof flashPlugin === "
undefined") { var vid = document.createElement('video'); // Use vid.canPlayType() to test for a supported mime type. } else { // Notify the user that flash is being deprecated and they // should upgrade their browser. } Specifications Specification Status Comment HTML Living StandardThe definition of 'MimeTypeArray' in that specification. Living Standard Initial d...
MutationObserver.disconnect() - Web APIs
Note: All notifications of mutations that have already been detected, but not yet reported to the observer, are discarded. Usage notes If the element being observed is removed from the DOM, and then subsequently released by the browser's garbage collection mechanism, the MutationObserver is likewise deleted. ...
MutationObserver.observe() - Web APIs
tationObserver.disconnect(). Syntax mutationObserver.observe(target, options) Parameters target A DOM Node (which may be an Element) within the DOM tree to watch for changes, or to be the root of a subtree of nodes to be watched. options A MutationObserverInit object providing options that describe which DOM mutations should be reported to mutationObserver's callback. Return value
undefined. Exceptions TypeError Thrown in any of the following circumstances: The options are configured such that nothing will actually be monitored. (For example, if MutationObserverInit.childList, MutationObserverInit.attributes, and MutationObserverInit.characterData are all false.) The value of options.attributes is false (indicating that attribute changes are not to be monitored), but ...
NDEFReader.scan() - Web APIs
= NDEFReader.scan(options); Parameters options Optional id -- the match pattern for matching each NDEFRecord.id. recordType -- the match pattern for matching each NDEFRecord.recordType. mediaType -- the match pattern for matching each NDEFRecord.mediaType. signal -- optional AbortSignal that allows to cancell this scan() operation. Return value A Promise that resolves with
undefined immediatelly after scheduling read operations for the NFC adapter. Exceptions This method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a DOMException whose name is one of the following: AbortError The scan operation was aborted with AbortSignal passed in options. NotAllowedError The permission for this operation was rejected. NotSupportedError ...
NDEFWriter.write() - Web APIs
geInit. options Optional ignoreRead -- Boolean specifying whether or not to skip reading for the activated reader objects. Will be ignored if overwrite is false. overwrite -- Boolean specifying whether or not existing record should be overwritten, if such exists. signal -- optional AbortSignal that allows to cancell this write operation. Return value A Promise that resolves with
undefined when and if the message transfer is successfully completed. Exceptions This method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a DOMException whose name is one of the following: AbortError The write operation was aborted with AbortSignal passed in options. NotAllowedError The permission for this operation was rejected or overwrite is false and ...
Navigator.getUserMedia() - Web APIs
); video.srcObject = stream; video.onloadedmetadata = function(e) { // Do something with the video here. }; } errorCallback When the call fails, the function specified in the errorCallback is invokedwith a MediaStreamError object as its sole argument; this object is is modeled on DOMException. See {anch("Errors")}} below for a list of the errors which can occur. Return value
undefined. Errors Examples Width and height Here's an example of using getUserMedia(), including code to cope with various browsers' prefixes. Note that this is the deprecated way of doing it: See the Examples section under the MediaDevices.getUserMedia() for modern examples. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || ...
Navigator.msLaunchUri() - Web APIs
rs uri A DOMString specifying the URL containing including the protocol of the document or resource to be displayed. successCallbackOptional A function matching the signature of MSLaunchUriCallback to be executed if the protocol handler is present. noHandlerCallbackOptional A function matching MSLaunchUriCallback to be executed if the protocol handler is not present. Return value
undefined. Usage notes If a default protocol handler is available on the system that matches the URI, the successCallback is invoked, otherwise, the noHandlerCallback is called. To help protect a user's privacy, Windows displays a prompt for the user to allow the service or app to be launched. The user can choose to not see the prompt after the first instance for a particular protocol and automatically ...
Navigator.productSub - Web APIs
Sub read-only property returns the build number of the current browser. Syntax prodSub = window.navigator.productSub prodSub is a string. Example <script> function prodsub() { var dt = document.getElementById("d").childNodes[0]; dt.data = window.navigator.productSub; } </script> <button onclick="prodsub();">productSub</button> // returns: 20010725 Notes On IE, this property returns
undefined. On Apple Safari and Google Chrome this property always returns 20030107. Specifications Specification Status Comment HTML Living StandardThe definition of 'NavigatorID: productSub' in that specification. Living Standard Initial definition ...
Navigator.onLine - Web APIs
ffline. Syntax online = window.navigator.onLine; Value online is a boolean true or false. Example View a live example. To check if you are online, query window.navigator.onLine, as in the following example: if (navigator.onLine) { console.log('online'); } else { console.log('offline'); } If the browser doesn't support navigator.onLine the above example will always come out as false/
undefined. To see changes in the network state, use addEventListener to listen for the events on window.online and window.offline, as in the following example: window.addEventListener('offline', function(e) { console.log('offline'); }); window.addEventListener('online', function(e) { console.log('online'); }); Specifications Specification Status Comment HTML Living Standar...
NavigatorPlugins.mimeTypes - Web APIs
rsions. Syntax var mimeTypes[] = navigator.mimeTypes; mimeTypes is a MimeTypeArray object which has a length property as well as item(index) and namedItem(name) methods. Example function isJavaPresent() { return 'application/x-java-applet' in navigator.mimeTypes; } function getJavaPluginDescription() { var mimetype = navigator.mimeTypes['application/x-java-applet']; if (mimetype ===
undefined) { // no Java plugin present return
undefined; } return mimetype.enabledPlugin.description; } Specifications Specification Status Comment HTML Living StandardThe definition of 'NavigatorPlugins.mimeTypes' in that specification. Living Standard Initial definition. ...
NavigatorPlugins.plugins - Web APIs
operty and supports accessing individual items using bracket notation (plugins[2]), as well as via item(index) and namedItem("name") methods. Examples The following example function returns the version of the Shockwave Flash plugin. function getFlashVersion() { var flash = navigator.plugins.namedItem('Shockwave Flash'); if (typeof flash != 'object') { // flash is not present return
undefined; } if(flash.version){ return flash.version; } else { //No version property (e.g. in Chrome) return flash.description.replace(/Shockwave Flash /,""); } } The following example displays information about the installed plugin(s). var pluginsLength = navigator.plugins.length; document.body.innerHTML = pluginsLength + " Plugin(s)<br>" + '<table id="pluginTable"><thead>' +'<...
Node.insertBefore() - Web APIs
node to insert let newNode = document.createElement("span") // Get a reference to the parent node let parentDiv = document.getElementById("childElement").parentNode // Begin test case [ 1 ] : Existing childElement (all works correctly) let sp2 = document.getElementById("childElement") parentDiv.insertBefore(newNode, sp2) // End test case [ 1 ] // Begin test case [ 2 ] : childElement is of Type
undefined let sp2 =
undefined // Non-existent node of id "childElement" parentDiv.insertBefore(newNode, sp2) // Implicit dynamic cast to type Node // End test case [ 2 ] // Begin test case [ 3 ] : childElement is of Type "
undefined" ( string ) let sp2 = "
undefined" // Non-existent node of id "childElement" parentDiv.insertBefore(newNode, sp2) // Generates "Type Error: Invalid Argument" // End test case [ ...
Node.nodeName - Web APIs
ecause nodeName and tagName return in upper case on HTML elements in DOMs flagged as HTML documents. Read more details on nodeName case sensitivity in different browsers. Note that the Element.tagName property could have been used instead, since nodeName has the same value as tagName for an element. Bear in mind, however, that nodeName will return "#text" for text nodes while tagName will return
undefined. Specifications Specification Status Comment DOMThe definition of 'nodeName' in that specification. Living Standard ...
NodeList.prototype.forEach() - Web APIs
function to execute on each element of someNodeList. It accepts 3 parameters: currentValue The current element being processed in someNodeList. currentIndex Optional The index of the currentValue being processed in someNodeList. listObj Optional The someNodeList that forEach() is being applied to. thisArg Optional Value to use as this when executing callback. Return value
undefined. Example let node = document.createElement("div"); let kid1 = document.createElement("p"); let kid2 = document.createTextNode("hey"); let kid3 = document.createElement("span"); node.appendChild(kid1); node.appendChild(kid2); node.appendChild(kid3); let list = node.childNodes; list.forEach( function(currentValue, currentIndex, listObj) { console.log(currentValue + ', ' + currentIndex + ...
NodeList - Web APIs
It's good to keep this distinction in mind when you choose how to iterate over the items in the NodeList, and whether you should cache the list's length. Properties NodeList.length The number of nodes in the NodeList. Methods NodeList.item() Returns an item in the list by its index, or null if the index is out-of-bounds. An alternative to accessing nodeList[i] (which instead returns
undefined when i is out-of-bounds). This is mostly useful for non-JavaScript DOM implementations. NodeList.entries() Returns an iterator, allowing code to go through all key/value pairs contained in the collection. (In this case, the keys are numbers starting from 0 and the values are nodes.) NodeList.forEach() Executes a provided function once per NodeList element, passing the element as an argument t...
OrientationSensor.populateMatrix() - Web APIs
s because your code is inconsistent with the policies set on your server. This is not something that would ever be shown to a user. See Feature-Policy for implementation instructions. Syntax orientationInstance.populateMatrix(targetMatrix) Because OrientationSensor is a base class, populateMatrix may only be read from one of its derived classes. Parameters targetMatrix TBD Return value
undefined Example // TBD Specifications Specification Status Comment Orientation SensorThe definition of 'populateMatrix' in that specification. Candidate Recommendation Initial definition. ...
OscillatorNode.setPeriodicWave() - Web APIs
scillatorNode interface is used to point to a PeriodicWave defining a periodic waveform that can be used to shape the oscillator's output, when type is custom. This replaces the now-obsolete OscillatorNode.setWaveTable(). Syntax OscillatorNode.setPeriodicWave(wave); Parameters wave A PeriodicWave object representing the waveform to use as the shape of the oscillator's output. Returns
undefined Example The following example illustrates simple usage of createPeriodicWave(), recreating a sine wave from a periodic wave. var real = new Float32Array(2); var imag = new Float32Array(2); var ac = new AudioContext(); var osc = ac.createOscillator(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createPeriodicWave(real, imag); osc.setPeriodicWave(wave); osc.connect(ac.d...
PaintWorklet.registerPaint - Web APIs
The PaintWorklet.registerPaint() method of the PaintWorklet interface registers a class programmatically generate an image where a CSS property expects a file. Syntax registerPaint(name, class); Parameters name The name of the worklet class to register. class A reference to the class that implements the worklet. Return value
undefined Exceptions TypeError Thrown when one of the arguments is invalid or missing. InvalidModificationError Thrown when the a worklet already exists with the specified name. Examples The following shows registering an example worklet module. This should be in a separate js file. Note that registerPaint() is called without a reference to PaintWorklet. The file itself is loaded through CSS.paintWorklet.addModule() (documented here on the paren...
ParentNode.append() - Web APIs
allows you to also append DOMString objects, whereas Node.appendChild() only accepts Node objects. ParentNode.append() has no return value, whereas Node.appendChild() returns the appended Node object. ParentNode.append() can append several nodes and strings, whereas Node.appendChild() can only append one node. Syntax // [Throws, Unscopable] ParentNode.append(...nodesOrDOMStrings) // returns
undefined Parameters nodes A set of Node or DOMString objects to insert. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. Examples Appending an element let parent = document.createElement("div") let p = document.createElement("p") parent.append(p) console.log(parent.childNodes) // NodeList [ <p> ] Appending text let parent = document.crea...
ParentNode.prepend() - Web APIs
ring objects before the first child of the ParentNode. DOMString objects are inserted as equivalent Text nodes. Syntax ParentNode.prepend(...nodesToPrepend); Parameters nodesToPrepend One or more nodes to insert before the first child node currently in the ParentNode. Each node can be specified as either a Node object or as a string; strings are inserted as new Text nodes. Return value
undefined. Exceptions HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy. Examples Prepending an element var parent = document.createElement("div"); var p = document.createElement("p"); var span = document.createElement("span"); parent.append(p); parent.prepend(span); console.log(parent.childNodes); // NodeList [ <span>, <p> ] Prepending text var parent = doc...
PaymentRequestUpdateEvent.updateWith() - Web APIs
total Optional A PaymentItem providing an updated total for the payment. Make sure this equals the sum of all of the items in displayItems. This is not calculated automatically. You must update this value yourself anytime the total amount due changes. This lets you have flexibility for how to handle things like tax, discounts, and other adjustments to the total price charged. Return value
undefined. Specifications Specification Status Comment Payment Request APIThe definition of 'PaymentRequestUpdateEvent.updateWith()' in that specification. Candidate Recommendation Initial definition. ...
performance.clearResourceTimings() - Web APIs
BufferSize() method. Note: This feature is available in Web Workers. Syntax performance.clearResourceTimings(); Arguments void Return value none This method has no return value. ...
performance.getEntries() - Web APIs
EntriesByName(). Note: This feature is available in Web Workers. Syntax General syntax: entries = window.performance.getEntries(); Return value entries An array of PerformanceEntry objects. The items will be in chronological order based on the entries' startTime. Example function use_PerformanceEntry_methods() { console.log("PerformanceEntry tests ..."); if (performance.mark ===
undefined) { console.log("... performance.mark Not supported"); return; } // Create some performance entries via the mark() method performance.mark("Begin"); do_work(50000); performance.mark("End"); performance.mark("Begin"); do_work(100000); performance.mark("End"); do_work(200000); performance.mark("End"); // Use getEntries() to iterate through the each entry let p = per...
performance.getEntriesByName() - Web APIs
t have the specified name and type. If the type argument is not specified, only the name will be used to determine the entries to return. The items will be in chronological order based on the entries' startTime. If no objects meet the specified criteria, an empty list is returned. Example function use_PerformanceEntry_methods() { log("PerformanceEntry tests ..."); if (performance.mark ===
undefined) { log("... performance.mark Not supported"); return; } // Create some performance entries via the mark() method performance.mark("Begin"); do_work(50000); performance.mark("End"); performance.mark("Begin"); do_work(100000); performance.mark("End"); do_work(200000); performance.mark("End"); // Use getEntries() to iterate through the each entry var p = performance...
performance.getEntriesByType() - Web APIs
anceEntry.entryType. Return value entries A list of PerformanceEntry objects that have the specified type. The items will be in chronological order based on the entries' startTime. If no objects have the specified type, or no argument is provided, an empty list is returned. Example function usePerformanceEntryMethods() { log("PerformanceEntry tests ..."); if (performance.mark ===
undefined) { log("... performance.mark Not supported"); return; } // Create some performance entries via the mark() method performance.mark("Begin"); doWork(50000); performance.mark("End"); performance.mark("Begin"); doWork(100000); performance.mark("End"); doWork(200000); performance.mark("End"); // Use getEntries() to iterate through the each entry var p = performance.ge...
performance.setResourceTimingBufferSize() - Web APIs
s. Note: This feature is available in Web Workers. Syntax performance.setResourceTimingBufferSize(maxSize); Arguments maxSize A number representing the maximum number of performance entry objects the browser should hold in its performance entry buffer. Return value none This method has no return value. Example function setResourceTimingBufferSize(maxSize) { if (performance ===
undefined) { log("Browser does not support Web Performance"); return; } var supported = typeof performance.setResourceTimingBufferSize == "function"; if (supported) { log("... Performance.setResourceTimingBufferSize() = Yes"); performance.setResourceTimingBufferSize(maxSize); } else { log("... Performance.setResourceTimingBufferSize() = NOT supported"); } } Specifications ...
PerformanceEntry.duration - Web APIs
performance entry has an entryType of "resource" (i.e. the entry is a PerformanceResourceTiming object), this property returns the difference between the PerformanceEntry.responseEnd and PerformanceEntry.startTime timestamps. Example The following example shows the use of the duration property. function run_PerformanceEntry() { log("PerformanceEntry support ..."); if (performance.mark ===
undefined) { log("... performance.mark Not supported"); return; } // Create some performance entries via the mark() method performance.mark("Begin"); do_work(50000); performance.mark("End"); // Use getEntries() to iterate through the each entry var p = performance.getEntries(); for (var i=0; i < p.length; i++) { log("Entry[" + i + "]"); check_PerformanceEntry(p[i]); } } ...
PerformanceEntry.entryType - Web APIs
paint PerformancePaintTiming DOMString Either 'first-paint' or 'first-contentful-paint'. longtask PerformanceLongTaskTiming DOMString reports instances of long tasks Example The following example shows the use of the entryType property. ...
PerformanceEntry.name - Web APIs
MString PerformanceMeasure measure name used when the measure was created by calling performance.measure(). DOMString PerformancePaintTiming paint Either 'first-paint' or 'first-contentful-paint'. Example The following example shows the use of the name property. function run_PerformanceEntry() { log("PerformanceEntry support ..."); if (performance.mark ===
undefined) { log("... performance.mark Not supported"); return; } // Create some performance entries via the mark() method performance.mark("Begin"); do_work(50000); performance.mark("End"); // Use getEntries() to iterate through the each entry var p = performance.getEntries(); for (var i=0; i < p.length; i++) { log("Entry[" + i + "]"); check_PerformanceEntry(p[i]); } } ...
PerformanceEntry.startTime - Web APIs
when the performance entry was created. Note: if the performance entry has an entryType of "resource" (i.e. the entry is a PerformanceResourceTiming object), this property returns the PerformanceEntry.fetchStart timestamp. Example The following example shows the use of the startTime property. function run_PerformanceEntry() { log("PerformanceEntry support ..."); if (performance.mark ===
undefined) { log("... performance.mark Not supported"); return; } // Create some performance entries via the mark() method performance.mark("Begin"); do_work(50000); performance.mark("End"); // Use getEntries() to iterate through the each entry var p = performance.getEntries(); for (var i=0; i < p.length; i++) { log("Entry[" + i + "]"); check_PerformanceEntry(p[i]); } } ...
PerformanceEntry.toJSON() - Web APIs
formance entry object. Note: This feature is available in Web Workers. Syntax json = perfEntry.toJSON(); Arguments None Return value json A JSON object that is the serialization of the PerformanceEntry object. Example The following example shows the use of the toJSON() method. function run_PerformanceEntry() { log("PerformanceEntry support ..."); if (performance.mark ===
undefined) { log("... performance.mark Not supported"); return; } // Create some performance entries via the mark() method performance.mark("Begin"); do_work(50000); performance.mark("End"); // Use getEntries() to iterate through the each entry var p = performance.getEntries(); for (var i=0; i < p.length; i++) { log("Entry[" + i + "]"); check_PerformanceEntry(p[i]); } } ...
Using the Performance API - Web APIs
} Serializing the Performance object JSON serialization of the Performance object is done via the toJSON() method. In the following example, JSON serialization for the Performance, Performance.timing and Performance.navigation objects is printed in the object element. ...
PushManager.unregister() - Web APIs
DOMRequest object to handle the success or failure of the method call. If the method call is successful, the request's result will be a PushRegistration object representing the endpoint that has been unregistered. PushRegistration Those objects are anonymous JavaScript objects with the following properties: pushEndpoint A string representing the URL of the unregistered endpoint. version
Undefined when unregister.onsuccess is called. Example var req = navigator.push.unregister(pushEndpoint); req.onsuccess = function(e) { var endpoint = req.result; debug("Unregistered endpoint: " + endpoint ); } req.onerror = function(e) { debug("Error unregistering the endpoint: " + JSON.stringify(e)); } Specification Specification Status Comment Push API Workin...
RTCDTMFSender.insertDTMF() - Web APIs
amount of time, in milliseconds, that each DTMF tone should last. This value must be between 40 ms and 6000 ms (6 seconds), inclusive. The default is 100 ms. interToneGap Optional The length of time, in milliseconds, to wait between tones. The browser will enforce a minimum value of 30 ms (that is, if you specify a lower value, 30 ms will be used instead); the default is 70 ms. Return value
undefined Exceptions InvalidStateError The DTMF tones couldn't be sent because the track has been stopped, or is in a read-only or inactive state. InvalidCharacterError One or more of the characters in tones is not valid DTMF. Example tbd Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDTMFSender.inser...
RTCDataChannel.close() - Web APIs
hannel.readyState property is set to "closed". If the transport was closed with an error, the RTCDataChannel is sent a NetworkError event. A close event is sent to the channel. In Firefox, the RTCDataChannel interface was implemented under the name DataChannel until Firefox 24, so this method was called DataChannel.close(). Syntax RTCDataChannel.close(); Parameters None. Return value
undefined. Example var pc = new RTCPeerConnection(); var dc = pc.createDataChannel("my channel"); dc.onmessage = function (event) { console.log("received: " + event.data); dc.close(); // We decided to close after the first received message }; dc.onopen = function () { console.log("datachannel open"); }; dc.onclose = function ( console.log("datachannel close"); }; // Now negotiate the connecti...
RTCDataChannel.send() - Web APIs
them, and those that do have various additional restrictions. This will get less complicated over time, but for now, if you have questions, see Understanding message size limits in Using WebRTC data channels. Syntax RTCDataChannel.send(data); Parameters data The data to transmit across the connection. This may be a USVString, a Blob, an ArrayBuffer, or an ArrayBufferView. Return value
undefined. Exceptions InvalidStateError Since the data channel uses a separate transport channel from the media content, it must establish its own connection; if it hasn't finished doing so (that is, its readyState is "connecting"), this error occurs without sending or buffering the data. NetworkError The specified data would need to be buffered, and there isn't room for it in the buffer. In this sc...
RTCIceCandidatePairStats.availableOutgoingBitrate - Web APIs
e bitrate from availableIncomingBitrate. Syntax availableOutgoingBitrate = rtcIceCandidatePairStats.availableOutgoingBitrate; Value A floating-point value which approximates the amount of available bandwidth for outgoing data on the network connection described by the RTCIceCandidatePair. The value is reported in bits per second and is computed over a 1-second interval. The returned value is
undefined in each of the following situations: The underlying implementation doesn't support computing a sender-side estimate of the outgoing bit rate. The RTCIceCandidatePair described by this object has never been used. The candidate pair was once in use, but no longer is. The value returned is calculated by adding up the available bit rate for every RTP stream using the connection described by th...
RTCIceCandidatePairStats.consentExpiredTimestamp - Web APIs
arrived or passed, the bindings have expired. Syntax consentExpiration = rtcIceCandidatePairStats.consentExpiredTimestamp; Value A DOMHighResTimeStamp object that indicates the time at which the STUN binding that allows the two peers described by this RTCIceCandidatePair to communicate will expire (or the time at which the binding did expire, if the time has passed). This property's value is
undefined if there have been no STUN binding responses yet on the candidate pair. This is only possible if responsesReceived is 0. Specifications Specification Status Comment Identifiers for WebRTC's Statistics APIThe definition of 'RTCIceCandidatePairStats.consentExpiredTimestamp' in that specification. Candidate Recommendation Initial specification. ...
RTCIceCandidatePairStats - Web APIs
s comprising a TCP connection: source IP address, source port number, destination IP address, destination port number, and protocol). The circuit breaker is triggered whenever a connection times out or otherwise needs to be automatically aborted. consentExpiredTimestamp Optional A DOMHighResTimeStamp value indicating the time at which the most recent STUN binding response expired. This value is
undefined if no valid STUN binding responses have been sent on the candidate pair; this can only happen if responsesReceived is 0. consentRequestsSent Optional The total number of consent requests that have been sent on this candidate pair. currentRoundTripTime Optional A floating-point value indicating the total time, in seconds, that elapsed elapsed between the most recently-sent STUN request and the...
RTCInboundRtpStreamStats.pliCount - Web APIs
ss Indication (PLI) packet to the sender. A PLI packet indicates that some amount of encoded video data has been lost for one or more frames. Syntax var pliCount = RTCInboundRtpStreamStats.pliCount; Value An integer value indicating the number of times a PLI packet was sent by the RTCRtpReceiver to the sender. These are sent by the receiver's decoder to notify the encoder (the sender) that an
undefined amount of coded video data, which may span frame boundaries, has been lost. This information is only available for video streams. This may trigger the sender to send a full frame in order to allow the receiver to re-synchronize, since lost data may be an irrecoverable situation for decoding media. However, the primary purpose of this message is to allow the sender to consider techniques to mitig...
RTCOutboundRtpStreamStats.pliCount - Web APIs
s object provides statistics. A PLI packet indicates that some amount of encoded video data has been lost for one or more frames. Syntax var pliCount = RTCOutboundRtpStreamStats.pliCount; Value An integer value indicating the number of times a PLI packet was sent to this sender by the remote peer's RTCRtpReceiver. These are sent by the receiver's decoder to notify the sender's encoder that an
undefined amount of coded video data, which may span frame boundaries, has been lost. Note: This property is only used for video streams. Usage notes Upon receiving a PLI packet, the sender may have responded by sending a full frame to the remote peer to allow it to re-synchronize with the media. However, the primary purpose of a PLI packet is to allow the RTCRtpSender for which this RTCOutboundRtpStr...
RTCPeerConnection: addstream event - Web APIs
dler property RTCPeerConnection.onaddstream You can, similarly, watch for streams to be removed from the connection by monitoring the removestream event. Examples This example looks to determine if the user's browser supports the track event. If it does, a track event listener is set up; otherwise, an addstream event listener is set up. pc is an RTCPeerConnection. if (pc.addTrack !==
undefined) { pc.ontrack = ev => { ev.streams.forEach(stream => doAddStream(stream)); } } else { pc.onaddstream = ev => { doAddStream(ev.stream); } } This calls a function doAddStream() once for each stream being added to the RTCPeerConnection, regardless of whether the browser sends addstream or track. You can also use the addEventListener() method to set an event listener: pc.addEventL...
RTCPeerConnection.getConfiguration() - Web APIs
tion = RTCPeerConnection.getConfiguration(); Parameters This method takes no input parameters. Return value An RTCConfiguration object describing the RTCPeerConnection's current configuration. Example This example adds a new certificate to an active connection if it doesn't already have one in use. ...
RTCPeerConnection.removeStream() - Web APIs
) if your target browser versions have implemented it. If the signalingState is set to "closed", an InvalidStateError is raised. If the signalingState is set to "stable", the event negotiationneeded is sent on the RTCPeerConnection. Syntax RTCPeerConnection.removeStream(mediaStream); Parameters mediaStream A MediaStream specifying the stream to remove from the connection. Return value
undefined. Example var pc, videoStream; navigator.getUserMedia({video: true}, function(stream) { pc = new RTCPeerConnection(); videoStream = stream; pc.addStream(stream); } document.getElementById("closeButton").addEventListener("click", function(event) { pc.removeStream(videoStream); pc.close(); }, false); ...
RTCPeerConnection.removeTrack() - Web APIs
set to "stable"), it is marked as needing to be negotiated again; the remote peer won't experience the change until this negotiation occurs. A negotiationneeded event is sent to the RTCPeerConnection to let the local end know this negotiation must occur. Syntax pc.removeTrack(sender); Parameters mediaTrack A RTCRtpSender specifying the sender to remove from the connection. Return value
undefined. Exceptions InvalidStateError The connection is not open. Example This example adds a video track to a connection and sets up a listener on a close button which removes the track when the user clicks the button. var pc, sender; navigator.getUserMedia({video: true}, function(stream) { pc = new RTCPeerConnection(); var track = stream.getVideoTracks()[0]; sender = pc.addTrack(track, s...
RTCPeerConnection.restartIce() - Web APIs
ause incoming offers are in the process of being negotiated--the RTCPeerConnection will remember that you requested ICE restart. The next time the connection's signalingState changes to stable, the connection will fire the negotiationneeded event. This process continues until an ICE restart has been successfully completed. Syntax rtcPeerConnection.restartIce(); Parameters None. Return value
undefined. Usage notes After calling restartIce(), the next offer created using createOffer() will initiate ICE restart once sent to the remote peer over your signaling mechanism. Restarting ICE essentially resets ICE so that it creates all new candidates using new credentials. Existing media transmissions continue uninterrupted during this process. For details about how ICE restart works, see ICE resta...
RTCRtpSender.replaceTrack() - Web APIs
romise is rejected if the track cannot be replaced for any reason; this is commonly because the change would require renegotiation of the codec, which is not allowed (see Things that require negotiation). If newTrack was omitted or was null, replaceTrack() simply stops the sender. No negotiation is required in this case. When the promise is fulfilled, the fulfillment handler receives a value of
undefined. Exceptions If the returned promise is rejected, one of the following exceptions is provided to the rejection handler: InvalidModificationError Replacing the RTCRtpSender's current track with the new one would require negotiation. InvalidStateError The track on which this method was called is stopped rather than running. TypeError The new track's kind doesn't match the original track. ...
RTCRtpStreamStats.pliCount - Web APIs
A PLI packet indicates that some amount of encoded video data has been lost for one or more frames. Syntax var pliCount = RTCRtpStreamStats.pliCount; Value An integer value indicating the number of times a PLI packet was sent by the stream's receiver to the sender. A PLI message is used by video decoders (running on the receiving end of the stream) to notify the encoder (the sender) that an
undefined amount of coded video data, which may span frame boundaries, has been lost. This may trigger the sender to send a full frame in order to allow the receiver to re-synchronize, since lost data may be an irrecoverable situation for decoding media. However, the primary purpose of this message is to allow the sender to consider techniques to mitigate network performance issues. This is often achieved...
RTCRtpTransceiver.setCodecPreferences() - Web APIs
ity objects, in order of preference, each providing the parameters for one of the transceiver's supported codecs. If codecs is empty, the codec configurations are all returned to the user agent's defaults. Note: Any codecs not included in codecs will not be considered during the process of negotiating a connection. This lets you prevent the use of codecs you don't wish to use. Return value
undefined Exceptions InvalidAccessError The codecs list includes one or more codecs which are not supported by the transceiver. Usage notes Getting a list of supported codecs You can only include in the codecs list codecs which the transceiver actually supports. That means that either the associated RTCRtpSender or the RTCRtpReceiver needs to support every codec in the list. If any unsupported cod...
RTCRtpTransceiver.stop() - Web APIs
Note: Until recently, the stopped property was provided to return true if the connection is stopped. That property has been deprecated and will be removed at some point. Instead, check the value of currentDirection. If it's stopped, the transceiver has been stopped. This method does nothing if the transceiver is already stopped. Syntax RTCRtpTransceiver.stop() Paramters None. Return value
undefined Exceptions InvalidStateError The RTCPeerConnection of which the transceiver is a member is closed. Usage notes When you call stop() on a transceiver, the sender immediately stops sending media and each of its RTP streams are closed using the RTCP "BYE" message. The receiver then stops receiving media; the receiver's track is stopped, and the transceiver's direction is changed to stopped, ...
RTCSessionDescriptionCallback - Web APIs
) that make use of it). Syntax RTCSessionDescriptionCallback(description); Parameters description An RTCSessionDescriptionInit (or RTCSessionDescription) object describing the session being offered or being accepted. This object contains the type and sdp properties which are part of RTCSessionDescription. Return value The callback doesn't need to return anything, so the return value is
undefined. Example var pc = new RTCPeerConnection(); var descriptionCallback = function(offer) { pc.setLocalDescription(offer); } pc.createOffer(descriptionCallback); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCSessionDescriptionCallback' in that specification. Candidate Recommendation Initial def...
Range.setEnd() - Web APIs
r in the document) than the start point will result in a collapsed range with the start and end points both set to the specified end position. Syntax range.setEnd(endNode, endOffset); Parameters endNode The Node inside which the Range should end. endOffset An integer greater than or equal to zero representing the offset for the end of the Range from the start of endNode. Return value
undefined. Exceptions Exceptions are thrown as DOMException objects of the following types: InvalidNodeTypeError The node specified by endNode is a doctype node; range endpoints cannot be located inside a doctype node. IndexSizeError The value specified by endOffset is either greater than or equal to the length of the node or is less than zero. Usage notes If the endNode is a Node of type Text, ...
ReadableByteStreamController.close() - Web APIs
The close() method of the ReadableByteStreamController interface closes the associated stream. Note: Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. Syntax readableByteStreamController.close(); Parameters None. Return value
undefined. Exceptions TypeError The source object is not a ReadableByteStreamController, or the stream is not readable for some other reason. Examples TBD. Specifications Specification Status Comment StreamsThe definition of 'close()' in that specification. Living Standard Initial definition. ...
ReadableByteStreamController.enqueue() - Web APIs
The enqueue() method of the ReadableByteStreamController interface enqueues a given chunk in the associated stream. Syntax readableByteStreamController.enqueue(chunk); Parameters chunk The chunk to enqueue. Return value
undefined. Exceptions TypeError The source object is not a ReadableByteStreamController, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existant or detached. Examples TBD. Specifications Specification Status Comment StreamsThe definition of 'enqueue()' in that specification. Living Standard Initial definition. ...
ReadableByteStreamController.error() - Web APIs
The error() method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error. Syntax readableByteStreamController.error(e); Parameters e The error you want future interactions to fail with. Return value
undefined. Exceptions TypeError The source object is not a ReadableByteStreamController, or the stream is not readable for some other reason. Examples TBD. Specifications Specification Status Comment StreamsThe definition of 'error()' in that specification. Living Standard Initial definition. ...
ReadableStream.ReadableStream() - Web APIs
You could define your own custom queuingStrategy, or use an instance of ByteLengthQueuingStrategy or CountQueuingStrategy for this object value. If no queuingStrategy is supplied, the default used is the same as a CountQueuingStrategy with a high water mark of 1. Return value An instance of the ReadableStream object. Exceptions RangeError The supplied type value is neither "bytes" nor
undefined. Examples In the following simple example, a custom ReadableStream is created using a constructor (see our Simple random stream example for the full code). The start() function generates a random string of text every second and enqueues it into the stream. A cancel() fuction is also provided to stop the generation if ReadableStream.cancel() is called for any reason. When a button is pressed, ...
ReadableStream.pipeThrough() - Web APIs
jected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. signal: If set to an AbortSignal object, ongoing pipe operations can then be aborted via the corresponding AbortController. Return value The readable side of the transformStream. Exceptions TypeError The writable and/or readable property of transformStream are
undefined. Examples In the following example (see Unpack chunks of a PNG for the full code running live, and png-transform-stream for the source code), an image is fetched and its body retrieved as a ReadableStream. Next, we log the contents of the readable stream, use pipeThrough() to send it to a new function that creates a gray-scaled version of the stream, then log the new stream's contents too. //...
ReadableStream.tee() - Web APIs
ist3); } function fetchStream(stream, list) { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always
undefined when done is true. if (done) { console.log("Stream complete"); return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Read ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list.appendChild(listItem); // Read som...
ReadableStreamBYOBReader.read() - Web APIs
rs view The view to be read into. Return value A Promise, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: If a chunk is available, the promise will be fulfilled with an object of the form { value: theChunk, done: false }. If the stream becomes closed, the promise will be fulfilled with an object of the form { value:
undefined, done: true }. If the stream becomes errored, the promise will be rejected with the relevant error. Exceptions TypeError The source object is not a ReadableStreamBYOBReader, the stream has no owner, the view is not an object or has become detached, or the view's length is 0. Examples TBD. Specifications Specification Status Comment StreamsThe definition of 'rea...
ReadableStreamBYOBReader.releaseLock() - Web APIs
ll appear errored in that same way subsequently; otherwise, the reader will appear closed. A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by the reader's ReadableStreamBYOBReader.read() method has not finished. This will result in a TypeError being thrown. Syntax readableStreamBYOBReader.releaseLock(); Parameters None. Return value
undefined. Exceptions TypeError The source object is not a ReadableStreamBYOBReader, or a read request is pending. Examples TBD. Specifications Specification Status Comment StreamsThe definition of 'releaseLock()' in that specification. Living Standard Initial definition. ...
ReadableStreamDefaultController.close() - Web APIs
ssociated stream. Readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. If you want to completely get rid of the stream and discard any enqueued chunks, you'd use ReadableStream.cancel() or ReadableStreamDefaultReader.cancel(). Syntax readableStreamDefaultController.close(); Parameters None. Return value
undefined. Exceptions TypeError The source object is not a ReadableStreamDefaultController. Examples In the following simple example, a custom ReadableStream is created using a constructor (see our Simple random stream example for the full code). The start() function generates a random string of text every second and enqueues it into the stream. A cancel() function is also provided to stop the gene...
ReadableStreamDefaultController.enqueue() - Web APIs
Exceptions TypeError The source object is not a ReadableStreamDefaultController. Examples In the following simple example, a custom ReadableStream is created using a constructor (see our Simple random stream example for the full code). ...
ReadableStreamDefaultController.error() - Web APIs
The error() method of the ReadableStreamDefaultController interface causes any future interactions with the associated stream to error. Note: The error() method can be called more than once, and can be called when the stream is not readable. Syntax readableStreamDefaultController.error(e); Parameters e The error you want future interactions to fail with. Return value
undefined. Exceptions TypeError The source object is not a ReadableStreamDefaultController, or the stream is not readable for some other reason. Examples The A readable stream with an underlying push source and backpressure support example in the spec provides a good example of using ReadableStreamDefaultController.desiredSize to manually detect when the stream is full and apply backpressure, and also of using err...
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
ther part of the UI. function fetchStream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always
undefined when done is true. if (done) { console.log("Stream complete"); para.textContent = result; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Received ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list2.a...
ReadableStreamDefaultReader.cancel() - Web APIs
to use it any more. function fetchStream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always
undefined when done is true. if (done) { console.log("Stream complete"); reader.cancel(); para.textContent = result; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Received ' + charsReceived + ' characters so far. Current chunk =...
ReadableStreamDefaultReader.releaseLock() - Web APIs
ear errored in that same way subsequently; otherwise, the reader will appear closed. A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by the reader's ReadableStreamDefaultReader.read() method has not finished. This will result in a TypeError being thrown. Syntax readableStreamDefaultReader.releaseLock(); Parameters None. Return value
undefined. Exceptions TypeError The source object is not a ReadableStreamDefaultReader, or a read request is pending. Examples function fetchStream() { const reader = stream.getReader(); ... reader.releaseLock() ... } Specifications Specification Status Comment StreamsThe definition of 'releaseLock()' in that specification. Living Standard Initial definiti...
Response.useFinalURL - Web APIs
Syntax var isfinalURL = Response.useFinalURL; Value A Boolean indicating whether or not the URL is final rather than a redirect. ...
SVGAnimationElement - Web APIs
there is no current interval, then a DOMException with code INVALID_STATE_ERR is thrown. SVGAnimationElement.getCurrentTime() Returns a float representing the current time in seconds relative to time zero for the given time container. SVGAnimationElement.getSimpleDuration() Returns a float representing the number of seconds for the simple duration for this animation. If the simple duration is
undefined (e.g., the end time is indefinite), then a DOMException with code NOT_SUPPORTED_ERR is raised. SVGAnimationElement.beginElement() Creates a begin instance time for the current time. The new instance time is added to the begin instance times list. The behavior of this method is equivalent to beginElementAt(0). SVGAnimationElement.beginElementAt() Creates a begin instance time for the cur...
SVGSVGElement - Web APIs
n" is enabled (i.e., zoomAndPan="magnify"), then the effect is as if an extra transformation were placed at the outermost level on the SVG document fragment (i.e., outside the outermost <svg> element). SVGSVGElement.currentTranslate Read only An SVGPoint representing the translation factor that takes into account user "magnification" corresponding to an outermost <svg> element. The behavior is
undefined for <svg> elements that are not at the outermost level. Methods This interface also inherits methods from its parent, SVGGraphicsElement and also implements the ones from SVGZoomAndPan, SVGFitToViewBox, and WindowEventHandlers. SVGSVGElement.suspendRedraw() Takes a time-out value which indicates that redraw shall not occur until: the corresponding unsuspendRedraw() call has been made,...
Screen.orientation - Web APIs
ation || screen.msOrientation; if (orientation === "landscape-primary") { console.log("That looks good."); } else if (orientation === "landscape-secondary") { console.log("Mmmh... the screen is upside down!"); } else if (orientation === "portrait-secondary" || orientation === "portrait-primary") { console.log("Mmmh... you should rotate your device to landscape"); } else if (orientation ===
undefined) { console.log("The orientation API isn't supported in this browser :("); } Specifications Specification Status Comment Screen Orientation APIThe definition of 'orientation' in that specification. Working Draft Initial definition ...
Sensor.start() - Web APIs
The start method activates one of the sensors based on Sensor. Syntax Sensor.start() Parameters None. Return value
undefined Specifications Specification Status Comment Generic Sensor APIThe definition of 'start' in that specification. Candidate Recommendation Initial definition. ...
Sensor.stop() - Web APIs
The stop method of the Sensor interface deactivates the current sensor. Syntax Sensor.stop() Parameters None. Return value
undefined Example // TBD Specifications Specification Status Comment Generic Sensor APIThe definition of 'stop' in that specification. Candidate Recommendation Initial definition. ...
ServiceWorkerContainer.getRegistration() - Web APIs
The getRegistration() method of the ServiceWorkerContainer interface gets a ServiceWorkerRegistration object whose scope URL matches the provided document URL. The method returns a Promise that resolves to a ServiceWorkerRegistration or
undefined. Syntax serviceWorkerContainer.getRegistration(scope).then(function(serviceWorkerRegistration) { ... }); Parameters scope Optional A unique identifier for a service worker registration -- the scope URL of the registration object you want to return. This is usually a relative URL. Return value A Promise that resolves to a ServiceWorkerRegistration object or
undefined. Example navigator.serviceWorker.getRegistration('/app').then(function(registration) { if(registration){ document.querySelector('#status').textContent = 'ServiceWorkerRegist...
ServiceWorkerContainer.startMessages() - Web APIs
ed a message handler using EventTarget.addEventListener() before the page has finished loading, but want to start processing the messages right away. Note: The messages start being sent automatically when setting the handler directly using ServiceWorkerContainer.onmessage. In this you don't need startMessages(). Syntax serviceWorkerContainer.startMessages(); Parameters None. Return value
undefined. Examples if('serviceWorker' in navigator) { navigator.serviceWorker .register('/sw.js') .then(function() { console.log('Service Worker Registered'); }); } // ... navigator.serviceWorker.addEventListener('message', (e) => { // ... }); navigator.serviceWorker.startMessages(); Specifications Specification Status Comment Service WorkersThe de...
ServiceWorkerContainer - Web APIs
l.) Also available via the ServiceWorkerContainer.onmessage property. Methods ServiceWorkerContainer.register() Creates or updates a ServiceWorkerRegistration for the given scriptURL. ServiceWorkerContainer.getRegistration() Gets a ServiceWorkerRegistration object whose scope matches the provided document URL. The method returns a Promise that resolves to a ServiceWorkerRegistration or
undefined. ServiceWorkerContainer.getRegistrations() Returns all ServiceWorkerRegistration objects associated with a ServiceWorkerContainer in an array. The method returns a Promise that resolves to an array of ServiceWorkerRegistration. ServiceWorkerContainer.startMessages() explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via Clien...
ServiceWorkerGlobalScope.skipWaiting() - Web APIs
kerGlobalScope forces the waiting service worker to become the active service worker. Use this method with Clients.claim() to ensure that updates to the underlying service worker take effect immediately for both the current client and all other active clients. Syntax ServiceWorkerGlobalScope.skipWaiting().then(function() { //Do something }); Returns A Promise that immediately resolves with
undefined. Example While self.skipWaiting() can be called at any point during the service worker's execution, it will only have an effect if there's a newly installed service worker that might otherwise remain in the waiting state. Therefore, it's common to call self.skipWaiting() from inside of an InstallEvent handler. The following example causes a newly installed service worker to progress into the a...
ServiceWorkerRegistration.showNotification() - Web APIs
pattern to run with the display of the notification. A vibration pattern can be an array with as few as one member. The values are times in milliseconds where the even indices (0, 2, 4, etc.) indicate how long to vibrate and the odd indices indicate how long to pause. For example, [300, 100, 400] would vibrate 300ms, pause 100ms, then vibrate 400ms. Return value A Promise that resolves to
undefined. Examples navigator.serviceWorker.register('sw.js'); function showNotification() { Notification.requestPermission(function(result) { if (result === 'granted') { navigator.serviceWorker.ready.then(function(registration) { registration.showNotification('Vibration Sample', { body: 'Buzz! Buzz!', icon: '../images/touch/chrome-touch-icon-192x192.png', ...
Using Service Workers - Web APIs
Fortunately service workers' promise-based structure makes it trivial to provide further options towards success. We could do this: self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then((response) => { return response || fetch(event.request); }) ); }); If the resources aren't in the cache, they a...
SourceBuffer.abort() - Web APIs
Exceptions Exception Explanation InvalidStateError The MediaSource.readyState property of the parent media source is not equal to open, or this SourceBuffer has been removed from the MediaSource. Example The spec description of abort() is somewhat confusing -- consider for example step 1 of reset parser state. ...
SourceBuffer.appendBuffer() - Web APIs
The appendBuffer() method of the SourceBuffer interface appends media segment data from an ArrayBuffer or ArrayBufferView object to the SourceBuffer. Syntax sourceBuffer.appendBuffer(source); Parameters source A BufferSource (that is, either an ArrayBufferView or ArrayBuffer) which contains the media segment data you want to add to the SourceBuffer. Return value
undefined. Exceptions None. Example TBD. Specifications Specification Status Comment Media Source ExtensionsThe definition of 'appendBuffer()' in that specification. Recommendation Initial definition. ...
SourceBuffer.changeType() - Web APIs
it possible to change codecs or container type mid-stream. One scenario in which this is helpful is to support adapting the media source to changing bandwidth availability, by transitioning from one codec to another as resource constraints change. Syntax sourceBuffer.changeType(type); Parameters type A DOMString specifying the MIME type that future buffers will conform to. Return value
undefined. Exceptions TypeError The specified string is empty, rather than indicating a valid MIME type. InvalidStateError The SourceBuffer is not a member of the parent media source's sourceBuffers list, or the buffer's updating property indicates that a previously queued appendBuffer() or remove() is still being processed. NotSupportedError The specified MIME type is not supported, or is not sup...
SourceBuffer.remove() - Web APIs
pecific time range from the SourceBuffer. This method can only be called when SourceBuffer.updating equals false. If SourceBuffer.updating is not equal to false, call SourceBuffer.abort(). Syntax sourceBuffer.remove(start, end); Parameters start A double representing the start of the time range, in seconds. end A double representing the end of the time range, in seconds. Return value
undefined. Exceptions Exception Explanation InvalidAccessError The MediaSource.duration property is equal to NaN, the start parameter is negative or greater than MediaSource.duration, or the end parameter is less than or equal to start or equal to NaN. InvalidStateError The SourceBuffer.updating property is equal to true, or this SourceBuffer has been removed from ...
SourceBufferList: indexed property getter - Web APIs
jects in the list to be accessed with an array operator (i.e. [].) Syntax var mySourceBuffer = sourceBufferList[index]; Parameters index The index position of the SourceBuffer object you want to return. Return value A SourceBuffer object. Exceptions No specific exceptions are thrown, but if the supplied index is great than or equal to SourceBufferList.length, the operation will return
undefined. Example TBD. Specifications Specification Status Comment Media Source ExtensionsThe definition of 'SourceBuffer() getter' in that specification. Recommendation Initial definition. ...
SpeechSynthesis - Web APIs
= document.createElement('option'); option.textContent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textContent += ' -- DEFAULT'; } option.setAttribute('data-lang', voices[i].lang); option.setAttribute('data-name', voices[i].name); voiceSelect.appendChild(option); } } populateVoiceList(); if (speechSynthesis.onvoiceschanged !==
undefined) { speechSynthesis.onvoiceschanged = populateVoiceList; } inputForm.onsubmit = function(event) { event.preventDefault(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedOption) { utterThis.voice = voices[i]; } ...
SpeechSynthesisVoice - Web APIs
= document.createElement('option'); option.textContent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textContent += ' -- DEFAULT'; } option.setAttribute('data-lang', voices[i].lang); option.setAttribute('data-name', voices[i].name); voiceSelect.appendChild(option); } } populateVoiceList(); if (speechSynthesis.onvoiceschanged !==
undefined) { speechSynthesis.onvoiceschanged = populateVoiceList; } inputForm.onsubmit = function(event) { event.preventDefault(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedOption) { utterThis.voice = voices[i]; } ...
Storage.clear() - Web APIs
Examples The following function creates three data entries in local storage, and then deletes them by using clear(). function populateStorage() { localStorage.setItem('bgcolor', 'red'); localStorage.setItem('font', 'Helvetica'); localStorage.setItem('image', 'miGato.png'); localStorage.clear(); } Note: For a real world example, see our Web Storage Demo. ...
Storage.removeItem() - Web APIs
will remove that key from the given Storage object if it exists. The Storage interface of the Web Storage API provides access to a particular domain's session or local storage. If there is no item associated with the given key, this method will do nothing. Syntax storage.removeItem(keyName); Parameters keyName A DOMString containing the name of the key you want to remove. Return value
undefined. Example The following function creates three data items inside local storage, then removes the image data item. function populateStorage() { localStorage.setItem('bgcolor', 'red'); localStorage.setItem('font', 'Helvetica'); localStorage.setItem('image', 'myCat.png'); localStorage.removeItem('image'); } We can do the same for the session storage. function populateStorage() { sessi...
Storage.setItem() - Web APIs
Storage interface, when passed a key name and value, will add that key to the given Storage object, or update that key's value if it already exists. Syntax storage.setItem(keyName, keyValue); Parameters keyName A DOMString containing the name of the key you want to create/update. keyValue A DOMString containing the value you want to give the key you are creating/updating. Return value
undefined. Exceptions setItem() may throw an exception if the storage is full. Particularly, in Mobile Safari (since iOS 5) it always throws when the user enters private mode. (Safari sets the quota to 0 bytes in private mode, unlike other browsers, which allow storage in private mode using separate data containers.) Hence developers should make sure to always catch possible exceptions from setItem(). E...
StylePropertyMap.append() - Web APIs
The append() method of the StylePropertyMap interface adds a new CSS declaration to the StylePropertyMap with the given property and value. Syntax StylePropertyMap.append(property,value) Parameters property An identifier indicating the stylistic feature (e.g. font, width, background color) to add. value The value the given property should have. Return value
undefined. Example // TBD Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'append()' in that specification. Working Draft Initial definition. ...
StylePropertyMap.clear() - Web APIs
The clear() method of the StylePropertyMap interface removes all declarations in the StylePropertyMap. Syntax StylePropertMap.clear() Parameters None. Return value
undefined Example // TBD Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'clear()' in that specification. Working Draft Initial definition. ...
StylePropertyMap.delete() - Web APIs
The delete() method of the StylePropertyMap interface removes the CSS declaration with the given property. Syntax StylePropertyMap.delete(property) Parameters property An identifier indicating the stylistic feature (e.g. font, width, background color) to remove. Return value
undefined Example // TBD Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'delete()' in that specification. Working Draft Initial definition. ...
StylePropertyMap.set() - Web APIs
The set() method of the StylePropertyMap interface changes the CSS declaration with the given property. Syntax StylePropertyMap.set(property,value) Parameters property An identifier indicating the stylistic feature (e.g. font, width, background color) to change. value The value the given property should have. Return value
undefined Example // TBD Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'set()' in that specification. Working Draft Initial definition. ...
StylePropertyMapReadOnly.forEach() - Web APIs
The function to execute for each element, taking three arguments: currentValue The value of the current element being processed. indexOptional The index of the current element being processed. arrayOptional The StylePropertyMapReadOnly thatforEach() is being called on. thisArg Optional Value to use as this (i.e the reference Object) when executing callback. Return value
undefined. Example // TBD Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'forEach()' in that specification. Working Draft Initial definition. ...
TransformStream - Web APIs
controller.enqueue(new Uint8Array(chunk)) else if ('function' === typeof chunk.valueOf && chunk.valueOf() !== chunk) this.transform(chunk.valueOf(), controller) // hack else if ('toJSON' in chunk) this.transform(JSON.stringify(chunk), controller) break case 'symbol': controller.error("Cannot send a symbol as a chunk part") break case '
undefined': controller.error("Cannot send
undefined as a chunk part") default: controller.enqueue(this.textencoder.encode(String(chunk))) break }, flush() { /* do any destructor work here */ } } class AnyToU8Stream extends TransformStream { constructor() { super({...transformContent, textencoder: new TextEncoder()}) } } Polyfilling TextEncoderStream and TextDeco...
URLSearchParams.sort() - Web APIs
The URLSearchParams.sort() method sorts all key/value pairs contained in this object in place and returns
undefined. The sort order is according to unicode code points of the keys. This method uses a stable sorting algorithm (i.e. the relative order between key/value pairs with equal keys will be preserved). Note: This feature is available in Web Workers. Syntax searchParams.sort(); Parameters None. Return value
undefined. Examples // Create a test URLSearchParams object var searchParams = new URLSearchParams("c=4&a=2&b=3&a=1"); // Sort the key/value pairs searchParams.sort(); // Display the sorted query string console.log(searchParams.toString()); The result is: a=2&a=1&b=3&c=4 Specifications Specification Status Comment URLThe definition of 'sort()' in tha...
USBEndpoint - Web APIs
discovered at runtime. For example, a USB serial device must provide bulk input and output endpoints but their endpoint numbers will depend on what other interfaces the device provides. This code identifies the correct endpoints by searching for the interface implementing the USB CDC interface class and then identifying the candidate endpoints based on their type and direction. let inEndpoint =
undefined; let outEndpoint =
undefined; for (const interface of device.configuration.interfaces) { // Only support devices with out multiple alternate interfaces. const alternate = interface.alternates[0]; // Identify the interface implementing the USB CDC class. const USB_CDC_CLASS = 10; if (alternate.interfaceClass != USB_CDC_CLASS) { continue; } for (const endpoint of alternate.endp...
WebGLRenderingContext.bufferData() - Web APIs
ransfer operations. gl.PIXEL_UNPACK_BUFFER: Buffer used for pixel transfer operations. size A GLsizeiptr setting the size in bytes of the buffer object's data store. srcData Optional An ArrayBuffer, SharedArrayBuffer or one of the ArrayBufferView typed array types that will be copied into the data store. If null, a data store is still created, but the content is uninitialized and
undefined. usage A GLenum specifying the intended usage pattern of the data store for optimization purposes. Possible values: gl.STATIC_DRAW: The contents are intended to be specified once by the application, and used many times as the source for WebGL drawing and image specification commands. gl.DYNAMIC_DRAW: The contents are intended to be respecified repeatedly by the application, and used many ...
WebGLRenderingContext.enableVertexAttribArray() - Web APIs
be used to access the attribute, including vertexAttribPointer(), vertexAttrib*(), and getVertexAttrib(). Syntax void gl.enableVertexAttribArray(index); Parameters index A GLuint specifying the index number that uniquely identifies the vertex attribute to enable. If you know the name of the attribute but not its index, you can get the index by calling getAttribLocation(). Return value
undefined. Errors To check for errors after calling enableVertexAttribArray(), call getError(). WebGLRenderingContext.INVALID_VALUE The specified index is invalid; that is, it's greater than or equal to the maximum number of entries permitted in the context's vertex attribute list, as indicated by the value of WebGLRenderingContext.MAX_VERTEX_ATTRIBS. Example This code -- a snippet taken from the ...
WebGLRenderingContext.uniformMatrix[234]fv() - Web APIs
ose, value); Parameters location A WebGLUniformLocation object containing the location of the uniform attribute to modify. The location is obtained using getUniformLocation(). transpose A GLboolean specifying whether to transpose the matrix. Must be false. value A Float32Array or sequence of GLfloat values. The values are assumed to be supplied in column major order. Return value
undefined Examples gl.uniformMatrix2fv(loc, false, [2,1, 2,2]); Specifications Specification Status Comment WebGL 1.0The definition of 'uniformMatrix' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glUniform' in that specification. Standard Man page of the OpenGL API. ...
Clearing by clicking - Web APIs
= document.querySelector("#canvas-view"); var button = document.querySelector("#color-switcher"); canvas.addEventListener("click", switchColor, false); button.addEventListener("click", switchColor, false); // A variable to hold the WebGLRenderingContext. var gl; // The click event handler. function switchColor () { // Referring to the externally defined gl variable. // If
undefined, try to obtain the WebGLRenderingContext. // If failed, alert user of failure. // Otherwise, initialize the drawing buffer (the viewport). if (!gl) { gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { alert("Failed to get WebGL context.\n" + "Your browser or device may not support WebGL."); return; ...
Signaling and video calling - Web APIs
ocket object, so we can just call its send() method directly. Our original chat demo didn't support sending messages to a specific user. The next task is to update the main WebSocket message handler to support doing so. This involves a change near the end of the "connection" message handler: if (sendToClients) { var msgString = JSON.stringify(msg); var i; if (msg.target && msg.target !==
undefined && msg.target.length !== 0) { sendToOneUser(msg.target, msgString); } else { for (i=0; i<connectionArray.length; i++) { connectionArray[i].send(msgString); } } } This code now looks at the pending message to see if it has a target property. If that property is present, it specifies the username of the client to which the message is to be sent, and we call sendToOneUser() to...
Using DTMF with WebRTC - Web APIs
lButton = document.querySelector("#dial"); dialButton.addEventListener("click", connectAndDial, false); }); Starting the connection process When the dial button is clicked, connectAndDial() is called. This starts building the WebRTC connection in preparation for sending the DTMF codes. ...
WebXR application life cycle - Web APIs
es, which cover starting up and shutting down a WebXR session, geometry, simulating cameras, spatial tracking, and more. Life cycle outline Most applications using WebXR will follow a similar overall design pattern: Check to see if the user's device and browser are both capable of presenting the XR experience you want to provide. Make sure the WebXR API is available; if navigator.xr is
undefined, you can assume the user's browser and/or device doesn't support WebXR. If it's not supported, disable any user interface used to activate XR features and abort any attempts to enter XR mode. Call navigator.xr.isSessionSupported(), specifying the WebXR experience mode you want to provide: inline, immersive-vr, or immersive-ar, in order to determine whether or not the type of session you wish t...
Starting up and shutting down a WebXR session - Web APIs
on the user's equipment. There is a global XRSystem object available for use by your document through the the Navigator property xr, which returns the XRSystem object if suitable XR hardware is available for your use given the hardware available and your document's environment. Thus the simplest code that fetches the XRSystem object is: const xr = navigator.xr; The value of xr will be null or
undefined if WebXR isn't available. WebXR availability As a new and still in development API, WebXR support is limited to specific devices and browsers; and even on those, it may not be enabled by default. There may be options available to allow you to experiment with WebXR even if you don't have a compatible system, however. WebXR polyfill The team designing the WebXR specification has published a Web...
Using the Web Speech API - Web APIs
} } When we come to run the function, we do the following. This is because Firefox doesn't support SpeechSynthesis.onvoiceschanged, and will just return a list of voices when SpeechSynthesis.getVoices() is fired. With Chrome however, you have to wait for the event to fire before populating the list, hence the if statement seen below. populateVoiceList(); if (speechSynthesis.onvoiceschanged !==
undefined) { speechSynthesis.onvoiceschanged = populateVoiceList; } Speaking the entered text Next, we create an event handler to start speaking the text entered into the text field. We are using an onsubmit handler on the form so that the action happens when Enter/Return is pressed. We first create a new SpeechSynthesisUtterance() instance using its constructor -- this is passed the text input's value...
Window.back() - Web APIs
The obsolete and non-standard method back() on the window interface returns the window to the previous item in the history. This was a Firefox-specific method and was removed in Firefox 31. Note: Use the standard history.back method instead. Syntax window.back(); Parameters None. Return value
undefined. Example This simple example handles a click on a "Back" button by calling back(). function handleMyBackButton() { if (canGoBack) { window.back(); } } Specification This is not part of any specification. ...
Window.event - Web APIs
You should avoid using this property in new code, and should instead use the Event passed into the event handler function. This property is not universally supported and even when supported introduces potential fragility to your code. Note: This property can be fragile, in that there may be situations in which the returned Event is not the expected value. In addition, Window.event is not accurate for events dispatched within shadow trees. ...
Window.forward() - Web APIs
Moves the window one document forward in history. This was a Firefox-specific method and was removed in Firefox 31. Note: Use the standard window.history.forward() method instead. Syntax window.forward(); Parameters None Return value
undefined. Example function goForward() { if (canGoForward) { window.forward(); } } Specification This is not part of any specification. ...
Window.requestAnimationFrame() - Web APIs
s to the right, so its relative position (in CSS pixels) can be calculated in function of the time elapsed since the start of the animation (in milliseconds) with 0.1 * elapsed. The element's final position is 200px (0.1 * 2000) to the right of its initial position. const element = document.getElementById('some-element-you-want-to-animate'); let start; function step(timestamp) { if (start ===
undefined) start = timestamp; const elapsed = timestamp - start; // `Math.min()` is used here to make sure that the element stops at exactly 200px. element.style.transform = 'translateX(' + Math.min(0.1 * elapsed, 200) + 'px)'; if (elapsed < 2000) { // Stop the animation after 2 seconds window.requestAnimationFrame(step); } } window.requestAnimationFrame(step); Notes Edge versions b...
Window.requestFileSystem() - Web APIs
System object representing the file system the app has permission to use. errorCallback Optional An optional parameter specifying a function which is called if an error occurs while attempting to obtain the file system, or if the user denies permission to create or access the file system. The callback receives as input a single parameter: a FileError object describing the error. Return value
undefined Example Specifications Specification Status Comment File and Directory Entries API Draft Draft of proposed API This API has no official W3C or WHATWG specification. Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compa...
Window.scrollY - Web APIs
as for the scrollY property: window.pageYOffset === window.scrollY; // always true For cross-browser compatibility, use window.pageYOffset instead of window.scrollY. Additionally, older versions of Internet Explorer (< 9) do not support either property and must be worked around by checking other non-standard properties. ...
Window.speechSynthesis - Web APIs
= document.createElement('option'); option.textContent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textContent += ' -- DEFAULT'; } option.setAttribute('data-lang', voices[i].lang); option.setAttribute('data-name', voices[i].name); voiceSelect.appendChild(option); } } populateVoiceList(); if (speechSynthesis.onvoiceschanged !==
undefined) { speechSynthesis.onvoiceschanged = populateVoiceList; } inputForm.onsubmit = function(event) { event.preventDefault(); var utterThis = new SpeechSynthesisUtterance(inputTxt.value); var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedOption) { utterThis.voice = voices[i]; } ...
Window - Web APIs
that is one having four corners and four sides. Window.DOMRect Read only Returns a reference to a DOMRect object, which represents a rectangle. Window.DOMRectReadOnly Read only Returns a reference to a DOMRectReadOnly object, which represents a rectangle. Window.event Read only Returns the current event, which is the event currently being handled by the JavaScript code's context, or
undefined if no event is currently being handled. The Event object passed directly to event handlers should be used instead whenever possible. Window.frameElement Read only Returns the element in which the window is embedded, or null if the window is not embedded. Window.frames Read only Returns an array of the subframes in the current window. Window.fullScreen This property indicates whether the w...
WindowOrWorkerGlobalScope.clearInterval() - Web APIs
lID) Parameters intervalID The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to setInterval(). It's worth noting that the pool of IDs used by setInterval() and setTimeout() are shared, which means you can technically use clearInterval() and clearTimeout() interchangeably. However, for clarity, you should avoid doing so. Return value
undefined Example See the setInterval() examples. Specifications Specification Status Comment HTML Living StandardThe definition of 'WindowOrWorkerGlobalScope.clearInterval()' in that specification. Living Standard Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec. HTML Living StandardThe definition of 'clearInterval()' in that specification. ...
WindowOrWorkerGlobalScope.clearTimeout() - Web APIs
arTimeout() and clearInterval() interchangeably. However, for clarity, you should avoid doing so. Example Run the script below in the context of a web page and click on the page once. You'll see a message popping up in a second. If you click the page multiple times in one second, the alert only appears once. ...
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
ust-before-rendering tasks. queueMicrotask() is exposed on the WindowOrWorkerGlobalScope mixin. Syntax scope.queueMicrotask(function); Parameters function A function to be executed when the browser engine determines it is safe to call your code. Enqueued microtasks are executed after all pending tasks have completed but before yielding control to the browser's event loop. Return value
undefined. Examples self.queueMicrotask(() => { // function contents here }) Taken from the queueMicrotask spec: MyElement.prototype.loadData = function (url) { if (this._cache[url]) { queueMicrotask(() => { this._setData(this._cache[url]); this.dispatchEvent(new Event("load")); }); } else { fetch(url).then(res => res.arrayBuffer()).then(data => { this._cache[url] = ...
Worker.prototype.postMessage() - Web APIs
The object to deliver to the worker; this will be in the data field in the event delivered to the DedicatedWorkerGlobalScope.onmessage handler. This may be any value or JavaScript object handled by the structured clone algorithm, which includes cyclical references. If the message parameter is not provided, a TypeError will be thrown. If the data to be passed to the worker is unimportant, null or
undefined can be passed explicitly. transfer Optional An optional array of Transferable objects to transfer ownership of. If the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from and becomes available only to the worker it was sent to. Transferable objects are instances of classes like ArrayBuffer, MessagePort or ImageBitmap objects that can be transfe...
WritableStreamDefaultController.error() - Web APIs
uffices to return a rejected promise from one of the underlying sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the normal lifecycle of interactions with the underlying sink. Syntax writableStreamDefaultController.error(e); Parameters e A DOMString representing the error you want future interactions to fail with. Return value
undefined. Exceptions TypeError The stream you are trying to error is not a WritableStream. Examples const writableStream = new WritableStream({ start(controller) { // do stuff with controller // error stream if necessary controller.error('My error is broken'); }, write(chunk, controller) { ... }, close(controller) { ... }, abort(err) { ... } }); Specificat...
WritableStreamDefaultWriter.close() - Web APIs
leStreamDefaultWriter interface closes the associated writable stream. The underlying sink will finish processing any previously-written chunks, before invoking the close behavior. During this time any further attempts to write will fail (without erroring the stream). Syntax var promise = writableStreamDefaultWriter.close(); Parameters None. Return value A Promise, which fulfills with the
undefined if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. Exceptions TypeError The stream you are trying to close is not a WritableStream. Examples The following example shows the creation of a WritableStream with a custom sink and an API-supplied queuing strategy. It then calls a function called sendMessa...
WritableStreamDefaultWriter.releaseLock() - Web APIs
bleStreamDefaultWriter interface releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed. Syntax writableStreamDefaultWritere.releaseLock() Parameters None. Return value
undefined. Examples const writableStream = new WritableStream({ write(chunk) { ... }, close() { ... }, abort(err) { ... } }, queuingStrategy); ... const writer = writableStream.getWriter(); ... // release writer's lock on the stream when desired writer.releaseLock(); Specifications Specification Status Comment StreamsThe definition of 'releaseLock()' ...
WritableStreamDefaultWriter.write() - Web APIs
te operation. Note that what "success" means is up to the underlying sink; it might indicate simply that the chunk has been accepted, and not necessarily that it is safely saved to its ultimate destination. Syntax var promise = writableStreamDefaultWriter.write(chunk); Parameters chunk A block of binary data to pass to the WritableStream. Return value A Promise, which fulfills with the
undefined upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. Exceptions TypeError The target stream is not a writable stream, or it does not have an owner. Examples The following example shows the creation of a WritableStream with a custom sink and an API-supplied queuing strategy. It then calls a function called sendMessage(), ...
XMLHttpRequest.abort() - Web APIs
The XMLHttpRequest.abort() method aborts the request if it has already been sent. When a request is aborted, its readyState is changed to XMLHttpRequest.UNSENT (0) and the request's status code is set to 0. Syntax XMLHttpRequest.abort() Parameters None. Return value
undefined Example This example begins loading content from the MDN home page, then due to some condition, aborts the transfer by calling abort(). var xhr = new XMLHttpRequest(), method = "GET", url = "https://developer.mozilla.org/"; xhr.open(method, url, true); xhr.send(); if (OH_NOES_WE_NEED_TO_CANCEL_RIGHT_NOW_OR_ELSE) { xhr.abort(); } Specifications Specification Status Comment XMLHttpRequest Living Standard WHATWG living standard ...
XMLHttpRequest.overrideMimeType() - Web APIs
a stream to be treated and parsed as "text/xml", even if the server does not report it as such. This method must be called before calling send(). Syntax XMLHttpRequest.overrideMimeType(mimeType) Parameters mimeType A DOMString specifying the MIME type to use instead of the one specified by the server. If the server doesn't specify a type, XMLHttpRequest assumes "text/xml". Return value
undefined. Example This example specifies a MIME type of "text/plain", overriding the server's stated type for the data being received. Note: If the server doesn't provide a Content-Type header, XMLHttpRequest assumes that the MIME type is "text/xml". If the content isn't valid XML, an "XML Parsing Error: not well-formed" error occurs. You can avoid this by calling overrideMimeType() to specify a diffe...
XMLHttpRequest.send() - Web APIs
is serialized before being sent. An XMLHttpRequestBodyInit, which per the Fetch spec can be a Blob, BufferSource, FormData, URLSearchParams, or USVString object. null If no value is specified for the body, a default value of null is used. The best way to send binary content (e.g. in file uploads) is by using an ArrayBufferView or Blob in conjunction with the send() method. Return value
undefined. Exceptions Exception Description InvalidStateError send() has already been invoked for the request, and/or the request is complete. NetworkError The resource type to be fetched is a Blob, and the method is not GET. Example: GET var xhr = new XMLHttpRequest(); xhr.open('GET', '/server', true); xhr.onload = function () { // Request finished. Do ...
XMLHttpRequest.sendAsBinary() - Web APIs
end() method, which now supports binary data in various forms. Syntax XMLHttpRequest.sendAsBinary(binaryString); Parameters binaryString A DOMString which encodes the binary content to be sent. You can create the binary string using the FileReader method readAsBinaryString(). The string is converted to binary for transfer by removing the high-order byte of each character. Return value
undefined. Polyfill Since sendAsBinary() is an experimental feature, here is a polyfill for browsers that don't support the sendAsBinary() method but support typed arrays. /*\ |*| |*| :: XMLHttpRequest.prototype.sendAsBinary() Polyfill :: |*| |*| https://developer.mozilla.org/docs/DOM/XMLHttpRequest#sendAsBinary() |*| \*/ if (!XMLHttpRequest.prototype.sendAsBinary) { XMLHttpRequest.prototype.sendAs...
XMLHttpRequest.setRequestHeader() - Web APIs
trol-Allow-Headers in preflight response" exception when you send requests across domains. In this situation, you need to set up the Access-Control-Allow-Headers in your response header at server side. Syntax XMLHttpRequest.setRequestHeader(header, value) Parameters header The name of the header whose value is to be set. value The value to set as the body of the header. Return value
undefined. Specifications Specification Status Comment XMLHttpRequestThe definition of 'setRequestHeader()' in that specification. Living Standard WHATWG living standard ...
XRInputSourceArray.forEach() - Web APIs
r, you can omit this. sourceList Optional The XRInputSourceArray object which is being processed. If you don't need this information, you may omit this. thisArg Optional The value to be used for this while executing the callback. Note that if you use arrow function notation (=>) to provide the callback, you can omit thisArg, since all arrow functions lexically bind this. Return value
Undefined. Examples This example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using. let inputSources = xrSession.inputSources; inputSources.forEach((input) => { if (input.gamepad) { checkGamepad(input.gamepad); } else { if (input.targetRayMode === "tracked-pointer" && input.handedness === player.handedness) { /* Handl...
XRSystem: ondevicechange - Web APIs
The ondevicechange property of the XRSystem interface is passed a devicechange event whenever availability of an immersive device changes. The event that is fired is a "simple event" that implements the Event interface. Syntax navigator.xr.ondevicechange = function(event) { ... }; Value
undefined Example navigator.xr.ondevicechange = function(ev) { console.log("The availability of immersive XR devices has changed.") }; Specifications Specification Status Comment WebXR Device APIThe definition of 'ondevicechange ' in that specification. Working Draft Initial definition. ...
msRegionOverflow - Web APIs
hain, that means the named flow content is further fitted in subsequent regions. In particular, in this last case, that means the region may have received no content from the named flow (for example if the region is too small to accommodate any content). empty: The region element has no content and is empty. All content from the named flow was fitted in regions with a lower content-order value.
undefined: The element is not a region. When the region is an actual element, msRegionOverflow provides the ability to find out if content fully fits into the region or not. However, it is only available to regions that are document elements and not to regions that are pseudo-elements. See also Microsoft API extensions ...
Using the aria-hidden attribute - Accessibility
tent behind each attribute is different. aria-hidden="true" will remove the entire element from the accessibility API. role="presentation" and role="none" will remove the semantic meaning of an element while still exposing it to assistive technology. Values false (default) The element is exposed to the accessibility API. true The element is not exposed to the accessibility API.
undefined (default) The user agent determines if the element is exposed to or hidden from the accessibility API. Examples In the example below, the paragraph is not exposed to the accessibility API (e.g. would not be read aloud by a screen reader). <p aria-hidden="true"> Some things are better left unsaid. </p> Children elements can be omitted from accessibility APIs: <p> This is not hidden <sp...
ARIA: document role - Accessibility
y relation to other elements with a document role, it merely has a relationship to the containing composit widget. An article can have associated articles. Associated WAI-ARIA roles, states, and properties aria-expanded Include with a value of true or false if the document element is collapsible, to indicate if the document is currently expanded or collapsed. Other values include the default
undefined which means the document is not collapsible. tabindex="0" Used to make it focusable so the assistive technology user can tab to it and start reading right away. Keyboard interactions The element should be made focusable by setting the tabindex="0" attribute / value pair on it. This way, the user can tab to it, reading mode is invoked automatically, and the content can be read right away...
Web applications and ARIA FAQ - Accessibility
value="0" max="100">0% complete</progress> <button id="update-button">Update</button> </body> </html> ... and here is the JavaScript code that will ensure the progress bar still works in older browsers: var progressBar = document.getElementById("progress-bar"); // Check to see if the browser supports the HTML5 <progress> tag. var supportsHTML5Progress = (typeof (HTMLProgressElement) !== "
undefined"); function setupProgress() { if (!supportsHTML5Progress) { // HTML5 <progress> isn't supported in this browser, so we need to add // ARIA roles and states to the element. progressBar.setAttribute("role", "progressbar"); progressBar.setAttribute("aria-valuemin", 0); progressBar.setAttribute("aria-valuemax", 100); } } function updateProgress(percentComplete) { if (!supp...
Detecting CSS animation support - CSS: Cascading Style Sheets
og post by Chris Heilmann, demonstrates a technique for doing this. Testing for CSS animation support This code will check to see if CSS animation support is available: var animation = false, animationstring = 'animation', keyframeprefix = '', domPrefixes = 'Webkit Moz O ms Khtml'.split(' '), pfx = '', elem = document.createElement('div'); if( elem.style.animationName !==
undefined ) { animation = true; } if( animation === false ) { for( var i = 0; i < domPrefixes.length; i++ ) { if( elem.style[ domPrefixes[i] + 'AnimationName' ] !==
undefined ) { pfx = domPrefixes[ i ]; animationstring = pfx + 'Animation'; keyframeprefix = '-' + pfx.toLowerCase() + '-'; animation = true; break; } } } For starters we define a few variables. We as...
border-bottom-left-radius - CSS: Cascading Style Sheets
CSS <length> data type. Percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. Negative values are invalid. Formal definition Initial value0Applies toall elements; but User Agents are not required to apply to table and inline-table elements when border-collapse is collapse. The behavior on internal table elements is
undefined for the moment.. It also applies to ::first-letter.InheritednoPercentagesrefer to the corresponding dimension of the border boxComputed valuetwo absolute <length>s or <percentage>sAnimation typea length, percentage or calc(); Formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage> Examples Live example Code . An ...
border-bottom-right-radius - CSS: Cascading Style Sheets
CSS <length> data type. Percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. Negative values are invalid. Formal definition Initial value0Applies toall elements; but User Agents are not required to apply to table and inline-table elements when border-collapse is collapse. The behavior on internal table elements is
undefined for the moment.. It also applies to ::first-letter.InheritednoPercentagesrefer to the corresponding dimension of the border boxComputed valuetwo absolute <length>s or <percentage>sAnimation typea length, percentage or calc(); Formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage> Examples Live example Code . An ...
border-end-end-radius - CSS: Cascading Style Sheets
CSS <length> data type. Percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. Negative values are invalid. Formal definition Initial value0Applies toall elements; but User Agents are not required to apply to table and inline-table elements when border-collapse is collapse. The behavior on internal table elements is
undefined for the moment.. It also applies to ::first-letter.InheritednoPercentagesrefer to the corresponding dimension of the border boxComputed valuetwo absolute <length>s or <percentage>sAnimation typea length, percentage or calc(); Formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage> Examples Border radius with vertical text HTML <div> <p class="exampleText"...
border-end-start-radius - CSS: Cascading Style Sheets
CSS <length> data type. Percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. Negative values are invalid. Formal definition Initial value0Applies toall elements; but User Agents are not required to apply to table and inline-table elements when border-collapse is collapse. The behavior on internal table elements is
undefined for the moment.. It also applies to ::first-letter.InheritednoPercentagesrefer to the corresponding dimension of the border boxComputed valuetwo absolute <length>s or <percentage>sAnimation typea length, percentage or calc(); Formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage> Examples Border radius with vertical text HTML <div> <p class="exampleText"...
border-radius - CSS: Cascading Style Sheets
border-bottom-left-radius: 3px 4px; Formal definition Initial valueas each of the properties of the shorthand:border-top-left-radius: 0border-top-right-radius: 0border-bottom-right-radius: 0border-bottom-left-radius: 0Applies toall elements; but User Agents are not required to apply to table and inline-table elements when border-collapse is collapse. The behavior on internal table elements is
undefined for the moment.. It also applies to ::first-letter.InheritednoPercentagesrefer to the corresponding dimension of the border boxComputed valueas each of the properties of the shorthand:border-bottom-left-radius: two absolute <length>s or <percentage>sborder-bottom-right-radius: two absolute <length>s or <percentage>sborder-top-left-radius: two absolute <length>s or <percentage>sborder-top-right-ra...
border-start-end-radius - CSS: Cascading Style Sheets
CSS <length> data type. Percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. Negative values are invalid. Formal definition Initial value0Applies toall elements; but User Agents are not required to apply to table and inline-table elements when border-collapse is collapse. The behavior on internal table elements is
undefined for the moment.. It also applies to ::first-letter.InheritednoPercentagesrefer to the corresponding dimension of the border boxComputed valuetwo absolute <length>s or <percentage>sAnimation typea length, percentage or calc(); Formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage> Examples Border radius with vertical text HTML <div> <p class="exampleText"...
border-start-start-radius - CSS: Cascading Style Sheets
CSS <length> data type. Percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. Negative values are invalid. Formal definition Initial value0Applies toall elements; but User Agents are not required to apply to table and inline-table elements when border-collapse is collapse. The behavior on internal table elements is
undefined for the moment.. It also applies to ::first-letter.InheritednoPercentagesrefer to the corresponding dimension of the border boxComputed valuetwo absolute <length>s or <percentage>sAnimation typea length, percentage or calc(); Formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage> Examples Border radius with vertical text HTML <div> <p class="exampleText"...
border-top-left-radius - CSS: Cascading Style Sheets
CSS <length> data type. Percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. Negative values are invalid. Formal definition Initial value0Applies toall elements; but User Agents are not required to apply to table and inline-table elements when border-collapse is collapse. The behavior on internal table elements is
undefined for the moment.. It also applies to ::first-letter.InheritednoPercentagesrefer to the corresponding dimension of the border boxComputed valuetwo absolute <length>s or <percentage>sAnimation typea length, percentage or calc(); Formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage> Examples Live example Code An arc of elli...
border-top-right-radius - CSS: Cascading Style Sheets
CSS <length> data type. Percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. Negative values are invalid. Formal definition Initial value0Applies toall elements; but User Agents are not required to apply to table and inline-table elements when border-collapse is collapse. The behavior on internal table elements is
undefined for the moment.. It also applies to ::first-letter.InheritednoPercentagesrefer to the corresponding dimension of the border boxComputed valuetwo absolute <length>s or <percentage>sAnimation typea length, percentage or calc(); Formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage> Examples Live example Code An arc of circ...
max-height - CSS: Cascading Style Sheets
ox for AndroidOpera for AndroidSafari on iOSSamsung Internetmax-heightChrome Full support 18Edge Full support 12Firefox Full support 1Notes Full support 1Notes Notes CSS 2.1 leaves the behavior of max-height with table
undefined. Firefox supports applying max-height to table elements.IE Full support 7Opera Full support 7Notes Full support 7Notes Notes CSS 2.1 leaves the behavior of max-height with table
undefined. Opera supports applying max-height to table elements.Safari ...
position - CSS: Cascading Style Sheets
o itself based on the values of top, right, bottom, and left. The offset does not affect the position of any other elements; thus, the space given for the element in the page layout is the same as if position were static. This value creates a new stacking context when the value of z-index is not auto. Its effect on table-*-group, table-row, table-column, table-cell, and table-caption elements is
undefined. absolute The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to its closest positioned ancestor, if any; otherwise, it is placed relative to the initial containing block. Its final position is determined by the values of top, right, bottom, and left. This value creates a new stacking context when the value...
Video player styling basics - Developer guides
Play/Pause and Mute Now that the buttons actually look like buttons and have images that indicate what they do, some changes need to be made so that the "dual functionality" buttons (such as the play/pause button) a...
Introduction to HTML5 - Developer guides
s was done to tighten security and prevent some types of attacks. Using the new HTML5 parser The parsing rules of HTML5, which analyze the meaning of mark-up, have been more precisely defined in HTML5. Until the introduction of HTML5, only the meaning of valid mark-up was defined, meaning that as soon as one small error was made in the mark-up (most websites have at least one), the behavior was
undefined. Essentially, it meant that all browsers behaved differently, which is no longer the case. Now, faced with errors in the mark-up, all compliant browsers must behave exactly in the same way. This requirement helps web developers quite a bit. While it is true that all modern browsers now use these HTML5 parsing rules, non-HTML5-compliant browsers are still used by some. Keep in mind that it's stil...
Reason: Did not find method in CORS header ‘Access-Control-Allow-Methods’ - HTTP
d when using CORS to access the URL specified in the request; if the request is using any other method, this error occurs. For example, if the response includes: Access-Control-Allow-Methods: GET,HEAD,POST Trying to use a PUT request will fail with this error. Make sure your code only uses the permitted HTTP methods when accessing the service. Note: If the server includes any unrecognized or
undefined method names in its Access-Control-Allow-methods header, a different error occurs: Reason: invalid token 'xyz' in CORS header 'Access-Control-Allow-Methods'. ...
Control flow and error handling - JavaScript
Caution: Do not confuse the primitive boolean values true and false with the true and false values of the Boolean object! For example: var b = new Boolean(false); if (b) // this condition evaluates to true if (b == true) // this condition evaluates t...
Keyed collections - JavaScript
The following code shows some basic operations with a Map. See also the Map reference page for more examples and the complete API. You can use a for...of loop to return an array of [key, value] for each iteration. let sayings = new Map(); sayings.set('dog', 'woof'); sayings.set('cat', 'meow'); sayings.set('elephant', 'toot'); sayings.size; // 3 sayings.get('dog'); // woof sayings.get('fox'); //
undefined sayings.has('bird'); // false sayings.delete('dog'); sayings.has('dog'); // false for (let [key, value] of sayings) { console.log(key + ' goes ' + value); } // "cat goes meow" // "elephant goes toot" sayings.clear(); sayings.size; // 0 Object and Map compared Traditionally, objects have been used to map strings to values. Objects allow you to set keys to values, retrieve those values, dele...
Unicode property escapes - JavaScript
t, we could use the Script_Extensions property (Scx for short). // ? is the digit 2 in Arabic-Indic notation // while it is predominantly written within the Arabic script // it can also be written in the Thaana script "?".match(/\p{Script=Thaana}/u); // null as Thaana is not the predominant script super() "?".match(/\p{Script_Extensions=Thaana}/u); // ["?", index: 0, input: "?", groups:
undefined] Unicode property escapes vs. character classes With JavaScript regular expressions, it is also possible to use character classes and especially \w or \d to match letters or digits. However, such forms only match characters from the Latin script (in other words, a to z and A to Z for \w and 0 to 9 for \d). As shown in this example, it might be a bit clumsy to work with non Latin texts. Unicod...
TypeError: invalid Array.prototype.sort argument - JavaScript
The JavaScript exception "invalid Array.prototype.sort argument" occurs when the argument of Array.prototype.sort() isn't either
undefined or a function which compares its operands. Message TypeError: argument is not a function object (Edge) TypeError: invalid Array.prototype.sort argument (Firefox) Error type TypeError What went wrong? The argument of Array.prototype.sort() is expected to be either
undefined or a function which compares its operands. Examples Invalid cases [1, 3, 2].sort(5); // TypeError var cmp = { asc: (x, y) => x >= y, dsc: (x, y) => x <= y }; [1, 3, 2].sort(cmp[this.key] || 'asc'); // TypeError Valid cases [1, 3, 2].sort(); // [1, 2, 3] var cmp = { asc: (x, y) => x >= y, dsc: (x, y) => x <= y }; [1, 3, 2].sort(cmp[this.key || 'asc']); // [1, 2, 3] ...
TypeError: X.prototype.y called on incompatible type - JavaScript
occurs when a function (on a given object), is called with a this not corresponding to the type expected by the function. Message TypeError: 'this' is not a Set object (EdgE) TypeError: Function.prototype.toString called on incompatible object (Firefox) TypeError: Function.prototype.bind called on incompatible target (Firefox) TypeError: Method Set.prototype.add called on incompatible receiver
undefined (Chrome) TypeError: Bind must be called on a function (Chrome) Error type TypeError What went wrong? When this error is thrown, a function (on a given object), is called with a this not corresponding to the type expected by the function. This issue can arise when using the Function.prototype.call() or Function.prototype.apply() methods, and providing a this argument which does not have the ...
TypeError: cannot use 'in' operator to search for 'x' in 'y' - JavaScript
e types. Examples Searching in strings Unlike in other programming languages (e.g. Python), you can't search in strings using the in operator. "Hello" in "Hello World"; // TypeError: cannot use 'in' operator to search for 'Hello' in 'Hello World' Instead you will need to use String.prototype.indexOf(), for example. "Hello World".indexOf("Hello") !== -1; // true The operand can't be null or
undefined Make sure the object you are inspecting isn't actually null or
undefined. var foo = null; "bar" in foo; // TypeError: cannot use 'in' operator to search for 'bar' in 'foo' (Chrome) // TypeError: right-hand side of 'in' should be an object, got null (Firefox) The in operator always expects an object. var foo = { baz: "bar" }; "bar" in foo; // false "PI" in Math; // true "pi" in Math; // fals...
TypeError: invalid 'instanceof' operand 'x' - JavaScript
wrong? The instanceof operator expects the right hand side operands to be a constructor object, i.e. an object which has a prototype property and is callable. Examples instanceof vs typeof "test" instanceof ""; // TypeError: invalid 'instanceof' operand "" 42 instanceof 0; // TypeError: invalid 'instanceof' operand 0 function Foo() {} var f = Foo(); // Foo() is called and returns
undefined var x = new Foo(); x instanceof f; // TypeError: invalid 'instanceof' operand f x instanceof x; // TypeError: x is not a function To fix these errors, you will either need to replace the instanceof operator with the typeof operator, or to make sure you use the function name, instead of the result of its evaluation. typeof "test" == "string"; // true typeof 42 == "number" // t...
JavaScript error reference - JavaScript
are deprecatedSyntaxError: "use strict" not allowed in function with non-simple parametersSyntaxError: "x" is a reserved identifierSyntaxError: JSON.parse: bad parsingSyntaxError: Malformed formal parameterSyntaxError: Unexpected tokenSyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# insteadSyntax...
setter - JavaScript
property current of object language. When current is assigned a value, it updates log with that value: const language = { set current(name) { this.log.push(name); }, log: [] } language.current = 'EN'; console.log(language.log); // ['EN'] language.current = 'FA'; console.log(language.log); // ['EN', 'FA'] Note that current is not defined, and any attempts to access it will result in
undefined. Removing a setter with the delete operator If you want to remove the setter, you can just delete it: delete language.current; Defining a setter on existing objects using defineProperty To append a setter to an existing object, use Object.defineProperty(). const o = {a: 0}; Object.defineProperty(o, 'b', { set: function(x) { this.a = x / 2; } }); o.b = 10; // Runs the setter, which ass...
Array.prototype.copyWithin() - JavaScript
var relativeTarget = target >> 0; var to = relativeTarget < 0 ? Math.max(len + relativeTarget, 0) : Math.min(relativeTarget, len); // Steps 9-11. var relativeStart = start >> 0; var from = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len); // Steps 12-14. var end = arguments[2]; var relativeEnd = end ===
undefined ? len : end >> 0; var final = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len); // Step 15. var count = Math.min(final - from, len - to); // Steps 16-17. var direction = 1; if (from < to && to < (from + count)) { direction = -1; from += count - 1; to += count - 1; } // Step 18. while (count > 0) { ...
Array.prototype.fill() - JavaScript
; } var O = Object(this); // Steps 3-5. var len = O.length >>> 0; // Steps 6-7. var start = arguments[1]; var relativeStart = start >> 0; // Step 8. var k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len); // Steps 9-10. var end = arguments[2]; var relativeEnd = end ===
undefined ? len : end >> 0; // Step 11. var finalValue = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len); // Step 12. while (k < finalValue) { O[k] = value; k++; } // Step 13. return O; } }); } If you need to support truly obsolete JavaScript engines that don't support Object.definePro...
Array.prototype.join() - JavaScript
o a string if necessary. If omitted, the array elements are separated with a comma (","). If separator is an empty string, all elements are joined without any characters in between them. Return value A string with all array elements joined. If arr.length is 0, the empty string is returned. Description The string conversions of all array elements are joined into one string. If an element is
undefined, null or an empty array [], it is converted to an empty string. Examples Joining an array four different ways The following example creates an array, a, with three elements, then joins the array four times: using the default separator, then a comma and a space, then a plus and an empty string. var a = ['Wind', 'Water', 'Fire']; a.join(); // 'Wind,Water,Fire' a.join(', '); // 'Wind, Wat...
Array.prototype.length - JavaScript
, 4, 6, 8, 10] Shortening an array The following example shortens the array numbers to a length of 3 if the current length is greater than 3. var numbers = [1, 2, 3, 4, 5]; if (numbers.length > 3) { numbers.length = 3; } console.log(numbers); // [1, 2, 3] console.log(numbers.length); // 3 Create empty array of fixed length var numbers = []; numbers.length = 3; console.log(numbers); // [
undefined,
undefined,
undefined] Specifications Specification ECMAScript (ECMA-262)The definition of 'Array.length' in that specification. ...
Array.prototype.slice() - JavaScript
to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax arr.slice([start[, end]]) Parameters start Optional Zero-based index at which to start extraction. A negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence. If start is
undefined, slice starts from the index 0. If start is greater than the index range of the sequence, an empty array is returned. end Optional Zero-based index before which to end extraction. slice extracts up to but not including end. For example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). A negative index can be used, indicating an offset from the ...
Array.prototype.values() - JavaScript
var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); iterator.next(); // Object { value: "a", done: false } iterator.next().value; // "b" iterator.next()["value"]; // "c" iterator.next(); // Object { value: "d", done: false } iterator.next(); // Object { value: "e", done: false } iterator.next(); // Object { value:
undefined, done: true } iteraror.next().value; //
undefined One-use: the array iterator object is one use or temporary object example: var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" for (let letter of iterator) { console.log(letter); } //
undefined reason: When next().done=true or currentInde...
ArrayBuffer.prototype.byteLength - JavaScript
byteLength accessor property represents the length of an ArrayBuffer in bytes. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Description The byteLength property is an accessor property whose set accessor function is
undefined, meaning that you can only read this property. The value is established when the array is constructed and cannot be changed. This property returns 0 if this ArrayBuffer has been detached. Examples Using byteLength var buffer = new ArrayBuffer(8); buffer.byteLength; // 8 Specifications Specification ECMAScript (ECMA-262)The definition of 'ArrayBuffer.prototype.byteLength' i...
ArrayBuffer.isView() - JavaScript
.isView(value) Parameters value The value to be checked. Return value true if the given argument is one of the ArrayBuffer views; otherwise, false. ...
BigInt64Array - JavaScript
dex to an end index with a static value. See also Array.prototype.fill(). BigInt64Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). BigInt64Array.prototype.find() Returns the found value in the array if an element in the array satisfies the provided testing function, or
undefined if not found. See also Array.prototype.find(). BigInt64Array.prototype.findIndex() Returns the found index in the array if an element in the array satisfies the provided testing function, or -1 if not found. See also Array.prototype.findIndex(). BigInt64Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). BigInt64Array.prototype.includ...
BigUint64Array - JavaScript
x to an end index with a static value. See also Array.prototype.fill(). BigUint64Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). BigUint64Array.prototype.find() Returns the found value in the array if an element in the array satisfies the provided testing function, or
undefined if not found. See also Array.prototype.find(). BigUint64Array.prototype.findIndex() Returns the found index in the array if an element in the array satisfies the provided testing function, or -1 if not found. See also Array.prototype.findIndex(). BigUint64Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). BigUint64Array.prototype.inc...
Boolean - JavaScript
The Boolean object is an object wrapper for a boolean value. Description The value passed as the first parameter is converted to a boolean value, if necessary. If the value is omitted or is 0, -0, null, false, NaN,
undefined, or the empty string (""), the object has an initial value of false. All other values, including any object, an empty array ([]), or the string "false", create an object with an initial value of true. Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. Any object of which the value is not
undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement. For example, the condition in the following if statement evaluates to true: var x = new Boolean(false...
DataView.prototype.buffer - JavaScript
e ArrayBuffer or SharedArrayBuffer referenced by the DataView at construction time. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Description The buffer property is an accessor property whose set accessor function is
undefined, meaning that you can only read this property. The value is established when the DataView is constructed and cannot be changed. Examples Using the buffer property var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dataview.buffer; // ArrayBuffer { byteLength: 8 } Specifications Specification ECMAScript (ECMA-262)The definition of 'DataView.prototype.buff...
DataView.prototype.byteLength - JavaScript
(in bytes) of this view from the start of its ArrayBuffer or SharedArrayBuffer. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Description The byteLength property is an accessor property whose set accessor function is
undefined, meaning that you can only read this property. The value is established when an DataView is constructed and cannot be changed. If the DataView is not specifying an offset or a byteLength, the byteLength of the referenced ArrayBuffer or SharedArrayBuffer will be returned. Examples Using the byteLength property var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dataview.byteLe...
DataView.prototype.byteOffset - JavaScript
(in bytes) of this view from the start of its ArrayBuffer or SharedArrayBuffer. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Description The byteOffset property is an accessor property whose set accessor function is
undefined, meaning that you can only read this property. The value is established when an DataView is constructed and cannot be changed. Examples Using the byteOffset property var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dataview.byteOffset; // 0 (no offset specified) var dataview2 = new DataView(buffer, 3); dataview2.byteOffset; // 3 (as specified when constructing the DataVie...
DataView.prototype.getBigInt64() - JavaScript
tribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.getBigInt64(byteOffset [, littleEndian]) Parameters byteOffset The offset, in bytes, from the start of the view to read the data from. littleEndian Optional Indicates whether the 64-bit int is stored in little- or big-endian format. If false or
undefined, a big-endian value is read. Return value A BigInt. Errors thrown RangeError Thrown if the byteOffset is set such that it would read beyond the end of the view. Description There is no alignment constraint; multi-byte values may be fetched from any offset. Examples Using the getBigInt64 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dataview.getBigInt64...
DataView.prototype.getBigUint64() - JavaScript
ribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.getBigUint64(byteOffset [, littleEndian]) Parameters byteOffset The offset, in bytes, from the start of the view to read the data from. littleEndian Optional Indicates whether the 64-bit int is stored in little- or big-endian format. If false or
undefined, a big-endian value is read. Return value A BigInt. Errors thrown RangeError Thrown if the byteOffset is set such that it would read beyond the end of the view. Description There is no alignment constraint; multi-byte values may be fetched from any offset. Examples Using the getBigUint64 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dataview.getBigUint...
DataView.prototype.getFloat32() - JavaScript
ribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.getFloat32(byteOffset [, littleEndian]) Parameters byteOffset The offset, in byte, from the start of the view where to read the data. littleEndian Optional Indicates whether the 32-bit float is stored in little- or big-endian format. If false or
undefined, a big-endian value is read. Return value A signed 32-bit float number. Errors thrown RangeError Thrown if the byteOffset is set such as it would read beyond the end of the view. Description There is no alignment constraint; multi-byte values may be fetched from any offset. Examples Using the getFloat32 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dat...
DataView.prototype.getFloat64() - JavaScript
ribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.getFloat64(byteOffset [, littleEndian]) Parameters byteOffset The offset, in byte, from the start of the view where to read the data. littleEndian Optional Indicates whether the 64-bit float is stored in little- or big-endian format. If false or
undefined, a big-endian value is read. Return value A signed 64-bit float number. Errors thrown RangeError Thrown if the byteOffset is set such as it would read beyond the end of the view. Description There is no alignment constraint; multi-byte values may be fetched from any offset. Examples Using the getFloat64 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dat...
DataView.prototype.getInt16() - JavaScript
contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.getInt16(byteOffset [, littleEndian]) Parameters byteOffset The offset, in byte, from the start of the view where to read the data. littleEndian Optional Indicates whether the 16-bit int is stored in little- or big-endian format. If false or
undefined, a big-endian value is read. Return value A signed 16-bit integer number. Errors thrown RangeError Thrown if the byteOffset is set such as it would read beyond the end of the view. Description There is no alignment constraint; multi-byte values may be fetched from any offset. Examples Using the getInt16 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dat...
DataView.prototype.getInt32() - JavaScript
ontribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.getInt32(byteOffset [, littleEndian]) Parameters byteOffset The offset, in bytes, from the start of the view where to read the data. littleEndian Optional Indicates whether the 32-bit int is stored in little- or big-endian format. If false or
undefined, a big-endian value is read. Return value A signed 32-bit integer number. Errors thrown RangeError Thrown if the byteOffset is set such as it would read beyond the end of the view. Description There is no alignment constraint; multi-byte values may be fetched from any offset. Examples Using the getInt32 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dat...
DataView.prototype.getUint16() - JavaScript
ontribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.getUint16(byteOffset [, littleEndian]) Parameters byteOffset The offset, in byte, from the start of the view where to read the data. littleEndian Optional Indicates whether the 16-bit int is stored in little- or big-endian format. If false or
undefined, a big-endian value is read. Return value An unsigned 16-bit integer number. Errors thrown RangeError Thrown if the byteOffset is set such as it would read beyond the end of the view. Description There is no alignment constraint; multi-byte values may be fetched from any offset. Examples Using the getUint16 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer);...
DataView.prototype.getUint32() - JavaScript
ontribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.getUint32(byteOffset [, littleEndian]) Parameters byteOffset The offset, in byte, from the start of the view where to read the data. littleEndian Optional Indicates whether the 32-bit int is stored in little- or big-endian format. If false or
undefined, a big-endian value is read. Return value An unsigned 32-bit integer number. Errors thrown RangeError Thrown if the byteOffset is set such as it would read beyond the end of the view. Description There is no alignment constraint; multi-byte values may be fetched from any offset. Examples Using the getUint32 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer);...
DataView.prototype.setBigInt64() - JavaScript
set The offset, in bytes, from the start of the view to store the data from. value The value to set as a BigInt. The highest possible value that fits in a signed 64-bit integer is 2n ** (64n -1n) - 1n (9223372036854775807n). Upon overflow, it will be negative (-9223372036854775808n). littleEndian Optional Indicates whether the 64-bit int is stored in little- or big-endian format. If false or
undefined, a big-endian value is written. Return value
undefined. Errors thrown RangeError Thrown if the byteOffset is set such that it would store beyond the end of the view. Examples Using the setBigInt64 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dataview.setBigInt64(0, 3n); dataview.getBigInt64(0); // 3n Specifications Specification ECM...
DataView.prototype.setBigUint64() - JavaScript
]) Parameters byteOffset The offset, in bytes, from the start of the view to store the data from. value The value to set as a BigInt. The highest possible value that fits in an unsigned 64-bit integer is 2n ** 64n - 1n (18446744073709551615n). Upon overflow, it will be zero (0n). littleEndian Optional Indicates whether the 64-bit int is stored in little- or big-endian format. If false or
undefined, a big-endian value is written. Return value
undefined. Errors thrown RangeError Thrown if the byteOffset is set such that it would store beyond the end of the view. Examples Using the setBigUint64 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dataview.setBigUint64(0, 3n); dataview.getBigUint64(0); // 3n Specifications Specification ...
DataView.prototype.setFloat32() - JavaScript
project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.setFloat32(byteOffset, value [, littleEndian]) Parameters byteOffset The offset, in byte, from the start of the view where to store the data. value The value to set. littleEndian Optional Indicates whether the 32-bit float is stored in little- or big-endian format. If false or
undefined, a big-endian value is written. Return value
undefined. Errors thrown RangeError Thrown if the byteOffset is set such as it would store beyond the end of the view. Examples Using the setFloat32 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dataview.setFloat32(1, 3); dataview.getFloat32(1); // 3 Specifications Specification ECMAScript...
DataView.prototype.setFloat64() - JavaScript
project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.setFloat64(byteOffset, value [, littleEndian]) Parameters byteOffset The offset, in byte, from the start of the view where to store the data. value The value to set. littleEndian Optional Indicates whether the 64-bit float is stored in little- or big-endian format. If false or
undefined, a big-endian value is written. Return value
undefined. Errors thrown RangeError Thrown if the byteOffset is set such as it would store beyond the end of the view. Examples Using the setFloat64 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dataview.setFloat64(0, 3); dataview.getFloat64(0); // 3 Specifications Specification ECMAScript...
DataView.prototype.setInt16() - JavaScript
ples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.setInt16(byteOffset, value [, littleEndian]) Parameters byteOffset The offset, in byte, from the start of the view where to store the data. value The value to set. littleEndian Optional Indicates whether the 16-bit int is stored in little- or big-endian format. If false or
undefined, a big-endian value is written. Return value
undefined. Errors thrown RangeError Thrown if the byteOffset is set such as it would store beyond the end of the view. Examples Using the setInt16 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dataview.setInt16(1, 3); dataview.getInt16(1); // 3 Specifications Specification ECMAScript (ECMA...
DataView.prototype.setInt32() - JavaScript
ples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.setInt32(byteOffset, value [, littleEndian]) Parameters byteOffset The offset, in byte, from the start of the view where to store the data. value The value to set. littleEndian Optional Indicates whether the 32-bit int is stored in little- or big-endian format. If false or
undefined, a big-endian value is written. Return value
undefined. Errors thrown RangeError Thrown if the byteOffset is set such as it would store beyond the end of the view. Examples Using the setInt32 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dataview.setInt32(1, 3); dataview.getInt32(1); // 3 Specifications Specification ECMAScript (ECMA...
DataView.prototype.setInt8() - JavaScript
for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.setInt8(byteOffset, value) Parameters byteOffset The offset, in byte, from the start of the view where to store the data. value The value to set. Return value
undefined. Errors thrown RangeError Thrown if the byteOffset is set such as it would store beyond the end of the view. Examples Using the setInt8 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dataview.setInt8(1, 3); dataview.getInt8(1); // 3 Specifications Specification ECMAScript (ECMA-262)The definition of 'DataView.prototype.setInt8' in that s...
DataView.prototype.setUint16() - JavaScript
les project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.setUint16(byteOffset, value [, littleEndian]) Parameters byteOffset The offset, in byte, from the start of the view where to store the data. value The value to set. littleEndian Optional Indicates whether the 16-bit int is stored in little- or big-endian format. If false or
undefined, a big-endian value is written. Return value
undefined. Errors thrown RangeError Thrown if the byteOffset is set such as it would store beyond the end of the view. Examples Using the setUint16 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dataview.setUint16(1, 3); dataview.getUint16(1); // 3 Specifications Specification ECMAScript (E...
DataView.prototype.setUint32() - JavaScript
les project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.setUint32(byteOffset, value [, littleEndian]) Parameters byteOffset The offset, in byte, from the start of the view where to store the data. value The value to set. littleEndian Optional Indicates whether the 32-bit int is stored in little- or big-endian format. If false or
undefined, a big-endian value is written. Return value
undefined. Errors thrown RangeError Thrown if the byteOffset is set such as it would store beyond the end of the view. Examples Using the setUint32 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dataview.setUint32(1, 3); dataview.getUint32(1); // 3 Specifications Specification ECMAScript (E...
DataView.prototype.setUint8() - JavaScript
or this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dataview.setUint8(byteOffset, value) Parameters byteOffset The offset, in byte, from the start of the view where to store the data. value The value to set. Return value
undefined. Errors thrown RangeError Thrown if the byteOffset is set such as it would store beyond the end of the view. Examples Using the setUint8 method var buffer = new ArrayBuffer(8); var dataview = new DataView(buffer); dataview.setUint8(1, 3); dataview.getUint8(1); // 3 Specifications Specification ECMAScript (ECMA-262)The definition of 'DataView.prototype.setUint8' in th...
Date.prototype.toLocaleDateString() - JavaScript
d let applications specify the language whose formatting conventions should be used. In implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. See the Intl.DateTimeFormat() constructor for details on these parameters and how to use them. The default value for each date-time component property is
undefined, but if the weekday, year, month, day properties are all
undefined, then year, month, and day are assumed to be "numeric". Return value A string representing the date portion of the given Date instance according to language-specific conventions. Performance When formatting large numbers of dates, it is better to create an Intl.DateTimeFormat object and use the function provided by its format ...
Date.prototype.toLocaleString() - JavaScript
d let applications specify the language whose formatting conventions should be used. In implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. See the Intl.DateTimeFormat() constructor for details on these parameters and how to use them. The default value for each date-time component property is
undefined. But, if the weekday, year, month, and day properties are all
undefined, then year, month, and day are assumed to be "numeric". Return value A string representing the given date according to language-specific conventions. Performance When formatting large numbers of dates, it is better to create an Intl.DateTimeFormat object and use the function provided by its format property. Examples U...
Date.prototype.toLocaleTimeString() - JavaScript
d let applications specify the language whose formatting conventions should be used. In implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. See the Intl.DateTimeFormat() constructor for details on these parameters and how to use them. The default value for each date-time component property is
undefined, but if the hour, minute, second properties are all
undefined, then hour, minute, and second are assumed to be "numeric". Return value A string representing the time portion of the given Date instance according to language-specific conventions. Performance When formatting large numbers of dates, it is better to create an Intl.DateTimeFormat object and use the function provided by its format p...
FinalizationRegistry.prototype.register() - JavaScript
, the registry's callback may get called. Syntax registry.register(target, heldValue, [unregisterToken]); Parameters target The target object to register. heldValue The value to pass to the finalizer for this object. This cannot be the target object. unregisterToken Optional A token that may be used with the unregister method later to unregister the target object. If provided (and not
undefined), this must be an object. If not provided, the target cannot be unregistered. Return value
undefined. Notes See the Avoid where possible and Notes on cleanup callbacks sections of the FinalizationRegistry page for important caveats. Examples Using register The following registers the target object referenced by target, passing in the held value "some value" and passing the target object i...
FinalizationRegistry.prototype.unregister() - JavaScript
Notes When a target object has been reclaimed, it is no longer registered in the registry. There is no need to all unregister in your cleanup callback. Only call unregister if you haven't received a cleanup callback and no longer need to receive one. ...
FinalizationRegistry - JavaScript
e value"); The registry does not keep a strong reference to the object, as that would defeat the purpose (if the registry held it strongly, the object would never be reclaimed). If theObject is reclaimed, your cleanup callback may be called at some point with the held value you provided for it ("some value" in the above). The held value can be any value you like: a primitive or an object, even
undefined. If the held value is an object, the registry keeps a strong reference to it (so it can pass it to your cleanup callback later). If you might want to unregister an object later, you pass a third value, which is the unregistration token you'll use later when calling the registry's unregister function to unregister the object. The registry only keeps a weak reference to the unregister token. It's...
Float32Array - JavaScript
index to an end index with a static value. See also Array.prototype.fill(). Float32Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). Float32Array.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function or
undefined if not found. See also Array.prototype.find(). Float32Array.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). Float32Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). Float32Array.prototype.includes(...
Float64Array - JavaScript
index to an end index with a static value. See also Array.prototype.fill(). Float64Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). Float64Array.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function or
undefined if not found. See also Array.prototype.find(). Float64Array.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). Float64Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). Float64Array.prototype.includes(...
Function() constructor - JavaScript
laring a function with a function expression or function statement and calling it within your code because such functions are parsed with the rest of the code. All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. Omitting an argument will result in the value of that parameter being
undefined. Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor. Examples Specifying arguments with the Function constructor The following code creates a Function object that takes two arguments. // Example can be run directly in your JavaScript console // Create a function that takes two arguments, and returns the sum of...
Function.prototype.bind() - JavaScript
value to be passed as the this parameter to the target function func when the bound function is called. The value is ignored if the bound function is constructed using the new operator. When using bind to create a function (supplied as a callback) inside a setTimeout, any primitive value passed as thisArg is converted to object. If no arguments are provided to bind , or if the thisArg is null or
undefined, the this of the executing scope is treated as the thisArg for the new function. arg1, arg2, ...argN Optional Arguments to prepend to arguments provided to the bound function when invoking func. Return value A copy of the given function with the specified this value, and initial arguments (if provided). Description The bind() function creates a new bound function, which is an exotic functi...
Int16Array - JavaScript
art index to an end index with a static value. See also Array.prototype.fill(). Int16Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). Int16Array.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function or
undefined if not found. See also Array.prototype.find(). Int16Array.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). Int16Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). Int16Array.prototype.includes() Det...
Int32Array - JavaScript
art index to an end index with a static value. See also Array.prototype.fill(). Int32Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). Int32Array.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function or
undefined if not found. See also Array.prototype.find(). Int32Array.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). Int32Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). Int32Array.prototype.includes() Det...
Int8Array - JavaScript
start index to an end index with a static value. See also Array.prototype.fill(). Int8Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). Int8Array.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function or
undefined if not found. See also Array.prototype.find(). Int8Array.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). Int8Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). Int8Array.prototype.includes() Determ...
Intl.DateTimeFormat.prototype.format() - JavaScript
by design and allowed by the specification. Most notably, the IE and Edge browsers insert bidirectional control characters around dates, so the output text will flow properly when concatenated with other text. For this reason you cannot expect to be able to compare the results of format() to a static value: let d = new Date("2019-01-01T00:00:00.000000Z"); let formattedDate = Intl.DateTimeFormat(
undefined, { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' }).format(d); "1.1.2019, 01:00:00" === formattedDate; // true in Firefox and others // false in IE and Edge Note: See also this StackOverflow thread for more details and examples. Specifications Specification ECMAScript Internationalization API (ECMA...
Intl.DateTimeFormat.prototype.resolvedOptions() - JavaScript
sion values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. calendar E.g. "gregory" numberingSystem The values requested using the Unicode extension keys "ca" and "nu" or filled in as default values. timeZone The value provided for this property in the options argument;
undefined (representing the runtime's default time zone) if none was provided. Warning: Applications should not rely on
undefined being returned, as future versions may return a String value identifying the runtime's default time zone instead. hour12 The value provided for this property in the options argument or filled in as a default. weekday era year month day hour minute second timeZoneName ...
Map.prototype.clear() - JavaScript
The clear() method removes all elements from a Map object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax myMap.clear(); Return value
undefined. Examples Using clear() var myMap = new Map(); myMap.set('bar', 'baz'); myMap.set(1, 'foo'); myMap.size; // 2 myMap.has('bar'); // true myMap.clear(); myMap.size; // 0 myMap.has('bar') // false Specifications Specification ECMAScript (ECMA-262)The definition of 'Map.prototype.clear' in that specification. ...
Map.prototype.get() - JavaScript
object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax myMap.get(key) Parameters key The key of the element to return from the Map object. Return value The element associated with the specified key, or
undefined if the key can't be found in the Map object. Examples Using get() let myMap = new Map(); myMap.set('bar', 'foo'); myMap.get('bar'); // Returns "foo" myMap.get('baz'); // Returns
undefined Specifications Specification ECMAScript (ECMA-262)The definition of 'Map.prototype.get' in that specification. ...
Map.prototype.size - JavaScript
the number of elements in a Map object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Description The value of size is an integer representing how many entries the Map object has. A set accessor function for size is
undefined; you can not change this property. Examples Using size var myMap = new Map(); myMap.set('a', 'alpha'); myMap.set('b', 'beta'); myMap.set('g', 'gamma'); myMap.size // 3 Specifications Specification ECMAScript (ECMA-262)The definition of 'Map.prototype.size' in that specification. ...
Math.abs() - JavaScript
st. Syntax Math.abs(x) Parameters x A number. Return value The absolute value of the given number. Description Because abs() is a static method of Math, you always use it as Math.abs(), rather than as a method of a Math object you created (Math is not a constructor). Examples Behavior of Math.abs() Passing an empty object, an array with more than one member, a non-numeric string or
undefined/empty variable returns NaN. Passing null, an empty string or an empty array returns 0. Math.abs('-1'); // 1 Math.abs(-2); // 2 Math.abs(null); // 0 Math.abs(''); // 0 Math.abs([]); // 0 Math.abs([2]); // 2 Math.abs([1,2]); // NaN Math.abs({}); // NaN Math.abs('string'); // NaN Math.abs(); // NaN Specifications Specification ECM...
Math.ceil() - JavaScript
7.004); // -7 Decimal adjustment // Closure (function() { /** * Decimal adjustment of a number. * * @param {String} type The type of adjustment. * @param {Number} value The number. * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base). * @returns {Number} The adjusted value. */ function decimalAdjust(type, value, exp) { // If the exp is
undefined or zero... if (typeof exp === '
undefined' || +exp === 0) { return Math[type](value); } value = +value; exp = +exp; // If the value is not a number or the exp is not an integer... if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { return NaN; } // Shift value = value.toString().split('e'); value = Math[type](+(value[0] + 'e' + (va...
Math.clz32() - JavaScript
resentation of n. // Return p. var asUint = x >>> 0; if (asUint === 0) { return 32; } return 31 - (log(asUint) / LN2 | 0) |0; // the "| 0" acts like math.floor }; })(Math.log, Math.LN2); Examples Using Math.clz32() Math.clz32(1); // 31 Math.clz32(1000); // 22 Math.clz32(); // 32 var stuff = [NaN, Infinity, -Infinity, 0, -0, false, null,
undefined, 'foo', {}, []]; stuff.every(n => Math.clz32(n) == 32); // true Math.clz32(true); // 31 Math.clz32(3.5); // 30 Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.clz32' in that specification. ...
Math.floor() - JavaScript
4 Math.floor(-45.05); // -46 Math.floor(-45.95); // -46 Decimal adjustment /** * Decimal adjustment of a number. * * @param {String} type The type of adjustment. * @param {Number} value The number. * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base). * @returns {Number} The adjusted value. */ function decimalAdjust(type, value, exp) { // If the exp is
undefined or zero... if (typeof exp === '
undefined' || +exp === 0) { return Math[type](value); } value = +value; exp = +exp; // If the value is not a number or the exp is not an integer... if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { return NaN; } // Shift value = value.toString().split('e'); value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - ex...
NaN - JavaScript
variable in global scope. The initial value of NaN is Not-A-Number -- the same as the value of Number.NaN. In modern browsers, NaN is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it. It is rather rare to use NaN in a program. There are five different types of operations that return NaN: Number cannot be parsed (e.g. parseInt("blabla") or Number(
undefined)) Math operation where the result is not a real number (e.g. Math.sqrt(-1)) Operand of an argument is NaN (e.g. 7 ** NaN) Indeterminate form (e.g. 0 * Infinity) Any operation that involves a string and is not an addition operation (e.g. "foo"/3) Examples Testing against NaN NaN compares unequal (via ==, !=, ===, and !==) to any other value -- including to another NaN value. Use Number.isN...
Number.EPSILON - JavaScript
one https://github.com/mdn/interactive-examples and send us a pull request. Property attributes of Number.EPSILON Writable no Enumerable no Configurable no Description The EPSILON property has a value of approximately 2.2204460492503130808472633361816E-16, or 2-52. Polyfill if (Number.EPSILON ===
undefined) { Number.EPSILON = Math.pow(2, -52); } Examples Testing equality x = 0.2; y = 0.3; z = 0.1; equal = (Math.abs(x - y + z) < Number.EPSILON); Specifications Specification ECMAScript (ECMA-262)The definition of 'Number.EPSILON' in that specification. ...
Number.isFinite() - JavaScript
te(value) Parameters value The value to be tested for finiteness. Return value A Boolean indicating whether or not the given value is a finite number. Description In comparison to the global isFinite() function, this method doesn't forcibly convert the parameter to a number. This means only values of the type number, that are also finite, return true. ...
Number.isNaN() - JavaScript
nly value in javascript which is not equal to itself. Number.isNaN = Number.isNaN || function isNaN(input) { return typeof input === 'number' && input !== input; } Examples Using isNaN Number.isNaN(NaN); // true Number.isNaN(Number.NaN); // true Number.isNaN(0 / 0); // true // e.g. these would have been true with global isNaN() Number.isNaN('NaN'); // false Number.isNaN(
undefined); // false Number.isNaN({}); // false Number.isNaN('blabla'); // false // These all return false Number.isNaN(true); Number.isNaN(null); Number.isNaN(37); Number.isNaN('37'); Number.isNaN('37.37'); Number.isNaN(''); Number.isNaN(' '); Specifications Specification ECMAScript (ECMA-262)The definition of 'Number.isnan' in that specification. ...
Number.parseFloat() - JavaScript
.parseFloat(string) Parameters string The value to parse. If this argument is not a string, then it is converted to one using the ToString abstract operation. Leading whitespace in this argument is ignored. Return value A floating point number parsed from the given string. Or NaN when the first non-whitespace character cannot be converted to a number. Polyfill if (Number.parseFloat ===
undefined) { Number.parseFloat = parseFloat; } Examples Number.parseFloat vs parseFloat This method has the same functionality as the global parseFloat() function: Number.parseFloat === parseFloat; // true This method is also part of ECMAScript 2015. (Its purpose is modularization of globals.) See parseFloat() for more detail and examples. Specifications Specification ECMA...
Number.parseInt() - JavaScript
dix Optional An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. Be careful--this does not default to 10! Return value An integer parsed from the given string. If the radix is smaller than 2 or bigger than 36, and the first non-whitespace character cannot be converted to a number, NaN is returned. Polyfill if (Number.parseInt ===
undefined) { Number.parseInt = window.parseInt } Examples Number.parseInt vs parseInt This method has the same functionality as the global parseInt() function: Number.parseInt === parseInt // true and is part of ECMAScript 2015 (its purpose is modularization of globals). Please see parseInt() for more detail and examples. Specifications Specification ECMAScript (ECMA-262)...
Number - JavaScript
meric lexical grammar here. Description When used as a function, Number(value) converts a string or other value to the Number type. If the value can't be converted, it returns NaN. Literal syntax 123 // one-hundred twenty-three 123.0 // same 123 === 123.0 // true Function syntax Number('123') // returns the number 123 Number('123') === 123 // true Number("unicorn") // NaN Number(
undefined) // NaN Constructor Number() Creates a new Number value. Static properties Number.EPSILON The smallest interval between two representable numbers. Number.MAX_SAFE_INTEGER The maximum safe integer in JavaScript (253 - 1). Number.MAX_VALUE The largest positive representable number. Number.MIN_SAFE_INTEGER The minimum safe integer in JavaScript (-(253 - 1)). Number.MIN_VALUE The...
Object.prototype.__defineGetter__() - JavaScript
method should not be used since better alternatives exist. The __defineGetter__ method binds an object's property to a function to be called when that property is looked up. Syntax obj.__defineGetter__(prop, func) Parameters prop A string containing the name of the property to bind to the given function. func A function to be bound to a lookup of the specified property. Return value
undefined. Description The __defineGetter__ allows a getter to be defined on a pre-existing object. Examples Non-standard and deprecated way var o = {}; o.__defineGetter__('gimmeFive', function() { return 5; }); console.log(o.gimmeFive); // 5 Standard-compliant ways // Using the get operator var o = { get gimmeFive() { return 5; } }; console.log(o.gimmeFive); // 5 // Using Object.defineProperty va...
Object.getOwnPropertyDescriptors() - JavaScript
descriptor types and their attributes can be found in Object.defineProperty(). A property descriptor is a record with some of the following attributes: value The value associated with the property (data descriptors only). writable true if and only if the value associated with the property may be changed (data descriptors only). get A function which serves as a getter for the property, or
undefined if there is no getter (accessor descriptors only). set A function which serves as a setter for the property, or
undefined if there is no setter (accessor descriptors only). configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. enumerable true if and only if this property shows up during enumerat...
Object.is() - JavaScript
rmines whether two values are the same value. Syntax Object.is(value1, value2); Parameters value1 The first value to compare. value2 The second value to compare. Return value A Boolean indicating whether or not the two arguments are the same value. Description Object.is() determines whether two values are the same value. Two values are the same if one of the following holds: both
undefined both null both true or both false both strings of the same length with the same characters in the same order both the same object (means both object have same reference) both numbers and both +0 both -0 both NaN or both non-zero and both not NaN and both have the same value This is not the same as being equal according to the == operator. The == operator applies various...
Object.prototype.isPrototypeOf() - JavaScript
object prototype chain is checked against AFunction.prototype, not against AFunction itself. Syntax prototypeObj.isPrototypeOf(object) Parameters object The object whose prototype chain will be searched. Return value A Boolean indicating whether the calling object lies in the prototype chain of the specified object. Errors thrown TypeError A TypeError is thrown if prototypeObj is
undefined or null. Description The isPrototypeOf() method allows you to check whether or not an object exists within another object's prototype chain. Examples Using isPrototypeOf This example demonstrates that Baz.prototype, Bar.prototype, Foo.prototype and Object.prototype exist in the prototype chain for object baz: function Foo() {} function Bar() {} function Baz() {} Bar.prototype = Object.cre...
Object.setPrototypeOf() - JavaScript
obj The object which is to have its prototype set. prototype The object's new prototype (an object or null). Return value The specified object. Description Throws a TypeError exception if the object whose [[Prototype]] is to be modified is non-extensible according to Object.isExtensible(). Does nothing if the prototype parameter isn't an object or null (i.e., number, string, boolean, or
undefined). Otherwise, this method changes the [[Prototype]] of obj to the new value. Object.setPrototypeOf() is in the ECMAScript 2015 specification. It is generally considered the proper way to set the prototype of an object, vs. the more controversial Object.prototype.__proto__ property. Appending Prototype Chains A combination of Object.getPrototypeOf() and Object.prototype.__proto__ permits appendi...
Promise.prototype.finally() - JavaScript
riable for it A finally callback will not receive any argument, since there's no reliable means of determining if the promise was fulfilled or rejected. This use case is for precisely when you do not care about the rejection reason, or the fulfillment value, and so there's no need to provide it. So for example: Unlike Promise.resolve(2).then(() => {}, () => {}) (which will be resolved with
undefined), Promise.resolve(2).finally(() => {}) will be resolved with 2. Similarly, unlike Promise.reject(3).then(() => {}, () => {}) (which will be fulfilled with
undefined), Promise.reject(3).finally(() => {}) will be rejected with 3. Note: A throw (or returning a rejected promise) in the finally callback will reject the new promise with the rejection reason specified when calling throw. Ex...
handler.get() - JavaScript
r Inherited property access: Object.create(proxy)[foo] Reflect.get() Invariants If the following invariants are violated, the proxy will throw a TypeError: The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. The value reported for a property must be
undefined if the corresponding target object property is a non-configurable own accessor property that has
undefined as its [[Get]] attribute. Examples Trap for getting a property value The following code traps getting a property value. const p = new Proxy({}, { get: function(target, property, receiver) { console.log('called: ' + property); return 10; } }); console.log(p.a); // "called: a...
handler.ownKeys() - JavaScript
turn ['a', 'b', 'c']; } }); console.log(Object.getOwnPropertyNames(p)); // "called" // [ 'a', 'b', 'c' ] The following code violates an invariant. const obj = {}; Object.defineProperty(obj, 'a', { configurable: false, enumerable: true, value: 10 } ); const p = new Proxy(obj, { ownKeys: function(target) { return [123, 12.5, true, false,
undefined, null, {}, []]; } }); console.log(Object.getOwnPropertyNames(p)); // TypeError: proxy [[OwnPropertyKeys]] must return an array // with only string and symbol elements Specifications Specification ECMAScript (ECMA-262)The definition of '[[OwnPropertyKeys]]' in that specification. ...
handler.set() - JavaScript
invariants are violated, the proxy will throw a TypeError: Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property. Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has
undefined as its [[Set]] attribute. In strict mode, a false return value from the set() handler will throw a TypeError exception. Examples Trap setting of a property value The following code traps setting a property value. const p = new Proxy({}, { set: function(target, prop, value, receiver) { target[prop] = value; console.log('property set: ' + prop + ' = ' + value); return true; } ...
Comparing Reflect and Object methods - JavaScript
lue of the property. Throws a TypeError if the target was not an Object. deleteProperty() N/A Reflect.deleteProperty() returns true if the property was deleted from the object and false if it was not. getOwnPropertyDescriptor() Object.getOwnPropertyDescriptor() returns a property descriptor of the given property if it exists on the object argument passed in, and returns
undefined if it does not exist. However, if an object is not passed in as the first argument, it will be coerced into an object. Reflect.getOwnPropertyDescriptor() returns a property descriptor of the given property if it exists on the object. Returns
undefined if it does not exist, and a TypeError if anything other than an object (a primitive) is passed in as the first argument. getOwnProperty...
Reflect.deleteProperty() - JavaScript
lean indicating whether or not the property was successfully deleted. It is almost identical to the non-strict delete operator. Examples Using Reflect.deleteProperty() let obj = { x: 1, y: 2 } Reflect.deleteProperty(obj, 'x') // true obj // { y: 2 } let arr = [1, 2, 3, 4, 5] Reflect.deleteProperty(arr, '3') // true arr // [1, 2, 3,
undefined, 5] // Returns true if no such property exists Reflect.deleteProperty({}, 'foo') // true // Returns false if a property is unconfigurable Reflect.deleteProperty(Object.freeze({foo: 1}), 'foo') // false Specifications Specification ECMAScript (ECMA-262)The definition of 'Reflect.deleteProperty' in that specification. ...
Reflect.set() - JavaScript
operty accessor syntax as a function. Examples Using Reflect.set() // Object let obj = {} Reflect.set(obj, 'prop', 'value') // true obj.prop // "value" // Array let arr = ['duck', 'duck', 'duck'] Reflect.set(arr, 2, 'goose') // true arr[2] // "goose" // It can truncate an array. Reflect.set(arr, 'length', 1) // true arr // ["duck"] // With just one argument, propertyKey and value are "
undefined". let obj = {} Reflect.set(obj) // true Reflect.getOwnPropertyDescriptor(obj, '
undefined') // { value:
undefined, writable: true, enumerable: true, configurable: true } Specifications Specification ECMAScript (ECMA-262)The definition of 'Reflect.set' in that specification. ...
Reflect - JavaScript
n. Equivalent to calling delete target[propertyKey]. Reflect.get(target, propertyKey[, receiver]) Returns the value of the property. Works like getting a property from an object (target[propertyKey]) as a function. Reflect.getOwnPropertyDescriptor(target, propertyKey) Similar to Object.getOwnPropertyDescriptor(). Returns a property descriptor of the given property if it exists on the object,
undefined otherwise. Reflect.getPrototypeOf(target) Same as Object.getPrototypeOf(). Reflect.has(target, propertyKey) Returns a Boolean indicating whether the target has the property. Either as own or inherited. Works like the in operator as a function. Reflect.isExtensible(target) Same as Object.isExtensible(). Returns a Boolean that is true if the target is extensible. Reflect.ownKeys(target) Ret...
RegExp.prototype.flags - JavaScript
//github.com/mdn/interactive-examples and send us a pull request. Property attributes of RegExp.prototype.flags Writable no Enumerable no Configurable yes Description Flags in the flags property are sorted alphabetically (from left to right, e.g. "gimsuy"). Polyfill if (RegExp.prototype.flags ===
undefined) { Object.defineProperty(RegExp.prototype, 'flags', { configurable: true, get: function() { return this.toString().match(/[gimsuy]*$/)[0]; } }); } Examples Using flags /foo/ig.flags; // "gi" /bar/myu.flags; // "muy" Specifications Specification ECMAScript (ECMA-262)The definition of 'RegExp.prototype.flags' in that specification. ...
RegExpInstance.lastIndex - JavaScript
is reset to 0. Otherwise, lastIndex is set to the next position following the most recent match. Examples Using lastIndex Consider the following sequence of statements: var re = /(hi)?/g; Matches the empty string. console.log(re.exec('hi')); console.log(re.lastIndex); Returns ["hi", "hi"] with lastIndex equal to 2. console.log(re.exec('hi')); console.log(re.lastIndex); Returns ["",
undefined], an empty array whose zeroth element is the match string. In this case, the empty string because lastIndex was 2 (and still is 2) and hi has length 2. Specifications Specification ECMAScript (ECMA-262)The definition of 'RegExp.lastIndex' in that specification. ...
Set.prototype.clear() - JavaScript
The clear() method removes all elements from a Set object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax mySet.clear(); Return value
undefined. Examples Using the clear method var mySet = new Set(); mySet.add(1); mySet.add('foo'); mySet.size; // 2 mySet.has('foo'); // true mySet.clear(); mySet.size; // 0 mySet.has('bar') // false Specifications Specification ECMAScript (ECMA-262)The definition of 'Set.prototype.clear' in that specification. ...
Set.prototype.size - JavaScript
er of (unique) elements in a Set object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Description The value of size is an integer representing how many entries the Set object has. A set accessor function for size is
undefined; you cannot change this property. Examples Using size var mySet = new Set(); mySet.add(1); mySet.add(5); mySet.add('some text') mySet.size; // 3 Specifications Specification ECMAScript (ECMA-262)The definition of 'Set.prototype.size' in that specification. ...
Set - JavaScript
ue equality will be checked. In an earlier version of ECMAScript specification, this was not based on the same algorithm as the one used in the === operator. Specifically, for Sets, +0 (which is strictly equal to -0) and -0 were different values. However, this was changed in the ECMAScript 2015 specification. See "Key equality for -0 and 0" in the browser compatibility table for details. NaN and
undefined can also be stored in a Set. All NaN values are equated (i.e. NaN is considered the same as NaN, even though NaN !== NaN). Constructor Set() Creates a new Set object. Static properties get Set[@@species] The constructor function that is used to create derived objects. Instance properties Set.prototype.size Returns the number of values in the Set object. Instance methods Set.
SharedArrayBuffer.prototype.byteLength - JavaScript
ength accessor property represents the length of an SharedArrayBuffer in bytes. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Description The byteLength property is an accessor property whose set accessor function is
undefined, meaning that you can only read this property. The value is established when the shared array is constructed and cannot be changed. Examples Using byteLength var sab = new SharedArrayBuffer(1024); sab.byteLength; // 1024 Specifications Specification ECMAScript (ECMA-262)The definition of 'SharedArrayBuffer.prototype.byteLength' in that specification. ...
SharedArrayBuffer.prototype.slice() - JavaScript
ctive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax sab.slice() sab.slice(begin) sab.slice(begin, end) Parameters begin Optional Zero-based index at which to begin extraction. A negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence. If begin is
undefined, slice begins from index 0. end Optional Zero-based index before which to end extraction. slice extracts up to but not including end. For example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). A negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last ele...
String.prototype.endsWith() - JavaScript
ot a string ends with another string. This method is case-sensitive. Polyfill This method has been added to the ECMAScript 6 specification and may not be available in all JavaScript implementations yet. ...
String.prototype.indexOf() - JavaScript
sitory. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Note: For the Array method, see Array.prototype.indexOf(). Syntax str.indexOf(searchValue [, fromIndex]) Parameters searchValue The string value to search for. If no string is explicitly provided, searchValue will be coerced to "
undefined", and this value will be searched for in str. So, for example: '
undefined'.indexOf() will return 0, as
undefined is found at position 0 in the string
undefined. 'undefine'.indexOf() however will return -1, as
undefined is not found in the string undefine. fromIndex Optional An integer representing the index at which to start the search. Defaults to 0. For fromIndex values lower than 0, ...
String.prototype.match() - JavaScript
g flag is not used, only the first complete match and its related capturing groups are returned. In this case, the returned item will have additional properties as described below. Additional properties As explained above, some results contain additional properties as described below. groups An object of named capturing groups whose keys are the names and values are the capturing groups or
undefined if no named capturing groups were defined. See Groups and Ranges for more information. index The index of the search at which the result was found. input A copy of the search string. Description If the regular expression does not include the g flag, str.match() will return the same result as RegExp.exec(). Other methods If you need to know if a string matches a regular expression RegEx...
String.prototype.normalize() - JavaScript
the string. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.normalize([form]) Parameters form Optional One of "NFC", "NFD", "NFKC", or "NFKD", specifying the Unicode Normalization Form. If omitted or
undefined, "NFC" is used. These values have the following meanings: "NFC" Canonical Decomposition, followed by Canonical Composition. "NFD" Canonical Decomposition. "NFKC" Compatibility Decomposition, followed by Canonical Composition. "NFKD" Compatibility Decomposition. Return value A string containing the Unicode Normalization Form of the given string. Errors thrown RangeE...
String.prototype.replace() - JavaScript
the matched substring within the whole string being examined. (For example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1.) string The whole string being examined. groups In browser versions supporting named capturing groups, will be an object whose keys are the used group names, and whose values are the matched portions (
undefined if not matched). (The exact number of arguments depends on whether the first argument is a RegExp object--and, if so, how many parenthesized submatches it specifies.) The following example will set newString to 'abc - 12345 - #$*%': function replacer(match, p1, p2, p3, offset, string) { // p1 is nondigits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(' - '); } let new...
String.prototype.substr() - JavaScript
g at the start of the string. Its value is capped at str.length. If start is a negative number, the index starts counting from the end of the string. Its value is capped at -str.length. Note: In Microsoft JScript, negative values of the start argument are not considered to refer to the end of the string. If length is omitted, substr() extracts characters to the end of the string. If length is
undefined, substr() extracts characters to the end of the string. If length is a negative number, it is treated as 0. For both start and length, NaN is treated as 0. Polyfill Microsoft's JScript does not support negative values for the start index. To use this feature in JScript, you can use the following code: // only run when the substr() function is broken if ('ab'.substr(-1) != 'b') { /** * ...
String.prototype.toUpperCase() - JavaScript
isn't one). The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.toUpperCase() Return value A new string representing the calling string converted to upper case. Exceptions TypeError When called on null or
undefined, for example, String.prototype.toUpperCase.call(
undefined). Description The toUpperCase() method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable. Examples Basic usage console.log('alphabet'.toUpperCase()); // 'ALPHABET' Conversion of non-string this values to strings This method will...
String - JavaScript
For example: let outputStrings = [] for (let i = 0, n = inputValues.length; i < n; ++i) { outputStrings.push(String(inputValues[i])); } Specifications Specification ECMAScript (ECMA-262)The definition of 'String' in that specification. ...
Symbol.prototype.description - JavaScript
symbol itself. The Symbol.prototype.description property can be used to read that description. It is different to Symbol.prototype.toString() as it does not contain the enclosing "Symbol()" string. See the examples. Examples Using description Symbol('desc').toString(); // "Symbol(desc)" Symbol('desc').description; // "desc" Symbol('').description; // "" Symbol().description; //
undefined // well-known symbols Symbol.iterator.toString(); // "Symbol(Symbol.iterator)" Symbol.iterator.description; // "Symbol.iterator" // global symbols Symbol.for('foo').toString(); // "Symbol(foo)" Symbol.for('foo').description; // "foo" Specifications Specification ECMAScript (ECMA-262)The definition of 'get Symbol.prototype.description' in that specification. ...
TypedArray.prototype.buffer - JavaScript
roperty represents the ArrayBuffer referenced by a TypedArray at construction time. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Description The buffer property is an accessor property whose set accessor function is
undefined, meaning that you can only read this property. The value is established when the TypedArray is constructed and cannot be changed. TypedArray is one of the TypedArray objects. Examples Using the buffer property var buffer = new ArrayBuffer(8); var uint16 = new Uint16Array(buffer); uint16.buffer; // ArrayBuffer { byteLength: 8 } Specifications Specification ECMAScript (ECMA-...
TypedArray.prototype.byteLength - JavaScript
byteLength accessor property represents the length (in bytes) of a typed array. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Description The byteLength property is an accessor property whose set accessor function is
undefined, meaning that you can only read this property. The value is established when a TypedArray is constructed and cannot be changed. If the TypedArray is not specifying an byteOffset or a length, the length of the referenced ArrayBuffer will be returned. TypedArray is one of the TypedArray objects. Examples Using the byteLength property var buffer = new ArrayBuffer(8); var uint8 = new Uint8Array(b...
TypedArray.prototype.every() - JavaScript
e every method immediately returns false. Otherwise, if callback returned a true value for all elements, every will return true. callback is invoked with three arguments: the value of the element, the index of the element, and the array object being traversed. If a thisArg parameter is provided to every, it will be passed to callback when invoked, for use as its this value. Otherwise, the value
undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. every does not mutate the typed array on which it is called. Examples Testing size of all typed array elements The following example tests whether all elements in the typed array are bigger than 10. function isBigE...
TypedArray.prototype.filter() - JavaScript
Typed array elements which do not pass the callback test are simply skipped, and are not included in the new typed array. callback is invoked with three arguments: the value of the element the index of the element the typed array object being traversed If a thisArg parameter is provided to filter, it will be passed to callback when invoked, for use as its this value. Otherwise, the value
undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. filter() does not mutate the typed array on which it is called. The range of elements processed by filter() is set before the first invocation of callback. Elements which are appended to the typed array after the call ...
TypedArray.prototype.length - JavaScript
The length accessor property represents the length (in elements) of a typed array. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Description The length property is an accessor property whose set accessor function is
undefined, meaning that you can only read this property. The value is established when a TypedArray is constructed and cannot be changed. If the TypedArray is not specifying an byteOffset or a length, the length of the referenced ArrayBuffer will be returned. TypedArray is one of the TypedArray objects. Examples Using the length property var buffer = new ArrayBuffer(8); var uint8 = new Uint8Array(buffe...
TypedArray.prototype.map() - JavaScript
n. thisArg Optional Value to use as this when executing mapFn. Return value A new typed array. Description The map() method calls a provided callback function (mapFn) once for each element in a typed array, in order, and constructs a new typed array from the results. mapFn is invoked only for indexes of the typed array which have assigned values; it is not invoked for indexes that are
undefined, those which have been deleted, or which have never been assigned values. mapFn is invoked with three arguments: the value of the element, the index of the element, and the typed array object being traversed. If a thisArg parameter is provided to map(), it will be passed to mapFn when invoked, for use as its this value. Otherwise, the value
undefined will be passed for use as its this value. Th...
TypedArray.of() - JavaScript
ng a new Array. TypedArray.of uses [[Put]] where Array.of uses [[DefineProperty]]. Hence, when working with Proxy objects, it calls handler.set to create new elements rather than handler.defineProperty. Examples Using of Uint8Array.of(1); // Uint8Array [ 1 ] Int8Array.of('1', '2', '3'); // Int8Array [ 1, 2, 3 ] Float32Array.of(1, 2, 3); // Float32Array [ 1, 2, 3 ] Int16Array.of(
undefined); // Int16Array [ 0 ] Specifications Specification ECMAScript (ECMA-262)The definition of '%TypedArray%.of' in that specification. ...
TypedArray.prototype.slice() - JavaScript
bute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax typedarray.slice([begin[, end]]) Parameters begin Optional Zero-based index at which to begin extraction. A negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence. If begin is
undefined, slice begins from index 0. end Optional Zero-based index before which to end extraction. slice extracts up to but not including end. For example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). A negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last ele...
TypedArray.prototype.some() - JavaScript
e where callback returns a true value. If such an element is found, some immediately returns true. Otherwise, some returns false. callback is invoked with three arguments: the value of the element, the index of the element, and the array object being traversed. If a thisArg parameter is provided to some, it will be passed to callback when invoked, for use as its this value. Otherwise, the value
undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. some does not mutate the typed array on which it is called. Polyfill Since there is no global object with the name TypedArray, polyfilling must be done on an "as needed" basis. // https://tc39.github.io/ecma262/#sec...
Uint16Array - JavaScript
t index to an end index with a static value. See also Array.prototype.fill(). Uint16Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). Uint16Array.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function or
undefined if not found. See also Array.prototype.find(). Uint16Array.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). Uint16Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). Uint16Array.prototype.includes() ...
Uint32Array - JavaScript
t index to an end index with a static value. See also Array.prototype.fill(). Uint32Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). Uint32Array.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function or
undefined if not found. See also Array.prototype.find(). Uint32Array.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). Uint32Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). Uint32Array.prototype.includes() ...
Uint8Array - JavaScript
art index to an end index with a static value. See also Array.prototype.fill(). Uint8Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). Uint8Array.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function or
undefined if not found. See also Array.prototype.find(). Uint8Array.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). Uint8Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). Uint8Array.prototype.includes() Det...
Uint8ClampedArray - JavaScript
n end index with a static value. See also Array.prototype.fill(). Uint8ClampedArray.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). Uint8ClampedArray.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function or
undefined if not found. See also Array.prototype.find(). Uint8ClampedArray.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). Uint8ClampedArray.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). Uint8ClampedArray.prot...
WeakMap.prototype.get() - JavaScript
red in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax wm.get(key); Parameters key Required. The key of the element to return from the WeakMap object. Return value The element associated with the specified key in the WeakMap object. If the key can't be found,
undefined is returned. Examples Using the get method var wm = new WeakMap(); wm.set(window, 'foo'); wm.get(window); // Returns "foo". wm.get('baz'); // Returns
undefined. Specifications Specification ECMAScript (ECMA-262)The definition of 'WeakMap.prototype.get' in that specification. ...
WeakSet() constructor - JavaScript
The WeakSet constructor lets you create WeakSet objects that store weakly held objects in a collection. Syntax new WeakSet([iterable]); Parameters iterable If an iterable object is passed, all of its elements will be added to the new WeakSet. null is treated as
undefined. Examples Using the WeakSet object var ws = new WeakSet(); var foo = {}; var bar = {}; ws.add(foo); ws.add(bar); ws.has(foo); // true ws.has(bar); // true ws.delete(foo); // removes foo from the set ws.has(foo); // false, foo has been removed ws.has(bar); // true, bar is retained Note that foo !== bar. While they are similar objects, they are not the same object. And so they are both added to the set. Specifications Specification ECMAScript (ECMA-262)The definition of 'WeakSet constru...
isFinite() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax isFinite(testValue) Parameters testValue The value to be tested for finiteness. Return value false if the argument is positive or negative Infinity or NaN or
undefined; otherwise, true. Description isFinite is a top-level function and is not associated with any object. You can use this function to determine whether a number is a finite number. The isFinite function examines the number in its argument. If the argument is NaN, positive infinity, or negative infinity, this method returns false; otherwise, it returns true. Examples Using isFinite isFinite(Inf...
Standard built-in objects - JavaScript
er script or provided by the host application. The host objects available in browser contexts are documented in the API reference. For more information about the distinction between the DOM and core JavaScript, see JavaScript technologies overview. Standard objects by category Value properties These global properties return a simple value. They have no properties or methods. Infinity NaN
undefined globalThis Function properties These global functions--functions which are called globally, rather than on an object--directly return their results to the caller. eval() uneval() isFinite() isNaN() parseFloat() parseInt() encodeURI() encodeURIComponent() decodeURI() decodeURIComponent() Deprecated escape() unescape() Fundamental objects These are the f...
Conditional (ternary) operator - JavaScript
value is used as a condition. exprIfTrue An expression which is evaluated if the condition evaluates to a truthy value (one which equals or can be converted to true). exprIfFalse An expression which is executed if the condition is falsy (that is, has a value which can be converted to false). Description Besides false, possible falsy expressions are: null, NaN, 0, the empty string (""), and
undefined. If condition is any of these, the result of the conditional expression will be the result of executing the expression exprIfFalse. Examples A simple example var age = 26; var beverage = (age >= 21) ? "Beer" : "Juice"; console.log(beverage); // "Beer" Handling null values One common usage is to handle a value that may be null: let greeting = person => { let name = person ? person.name ...
Greater than (>) - JavaScript
ole.log(5 > "hello"); // false console.log("5" > 3n); // true console.log("3" > 5n); // false Number to Number comparison console.log(5 > 3); // true console.log(3 > 3); // false console.log(3 > 5); // false Number to BigInt comparison console.log(5n > 3); // true console.log(3 > 5n); // false Comparing Boolean, null,
undefined, NaN console.log(true > false); // true console.log(false > true); // false console.log(true > 0); // true console.log(true > 1); // false console.log(null > 0); // false console.log(1 > null); // true console.log(
undefined > 3); // false console.log(3 >
undefined); // false console.log(3 > NaN); // false console.log(NaN > 3); /...
Greater than or equal (>=) - JavaScript
// false console.log("hello" >= 5); // false console.log(5 >= "hello"); // false Number to Number comparison console.log(5 >= 3); // true console.log(3 >= 3); // true console.log(3 >= 5); // false Number to BigInt comparison console.log(5n >= 3); // true console.log(3 >= 3n); // true console.log(3 >= 5n); // false Comparing Boolean, null,
undefined, NaN console.log(true >= false); // true console.log(true >= true); // true console.log(false >= true); // false console.log(true >= 0); // true console.log(true >= 1); // true console.log(null >= 0); // true console.log(1 >= null); // true console.log(
undefined >= 3); // false console.log(3 >=
undefined); // false console.log(3 >= NaN); // false console.log(NaN...
Inequality (!=) - JavaScript
ferent, use the strict inequality operator instead: 3 !== "3"; // true Examples Comparison with no type conversion 1 != 2; // true "hello" != "hola"; // true 1 != 1; // false "hello" != "hello"; // false Comparison with type conversion "1" != 1; // false 1 != "1"; // false 0 != false; // false 0 != null; // true 0 !=
undefined; // true 0 != !!null; // false, look at Logical NOT operator 0 != !!
undefined; // false, look at Logical NOT operator null !=
undefined; // false const number1 = new Number(3); const number2 = new Number(3); number1 != 3; // false number1 != number2; // true Comparison of objects const object1 = {"key": "value"} const object2 = {"key": "value"}; object1 != obje...
Less than or equal (<=) - JavaScript
// true console.log("hello" <= 5); // false console.log(5 <= "hello"); // false Number to Number comparison console.log(5 <= 3); // false console.log(3 <= 3); // true console.log(3 <= 5); // true Number to BigInt comparison console.log(5n <= 3); // false console.log(3 <= 3n); // true console.log(3 <= 5n); // true Comparing Boolean, null,
undefined, NaN console.log(true <= false); // false console.log(true <= true); // true console.log(false <= true); // true console.log(true <= 0); // false console.log(true <= 1); // true console.log(null <= 0); // true console.log(1 <= null); // false console.log(
undefined <= 3); // false console.log(3 <=
undefined); // false console.log(3 <= NaN); // false console.log(N...
Logical AND (&&) - JavaScript
ve-examples and send us a pull request. Syntax expr1 && expr2 Description If expr1 can be converted to true, returns expr2; else, returns expr1. If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called falsy. Examples of expressions that can be converted to false are: null; NaN; 0; empty string ("" or '' or ``);
undefined. Even though the && operator can be used with operands that are not Boolean values, it can still be considered a boolean operator since its return value can always be converted to a boolean primitive. To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator or the Boolean constructor. Short-circuit evaluation The logic...
Logical NOT (!) - JavaScript
ples and send us a pull request. Syntax !expr Description Returns false if its single operand can be converted to true; otherwise, returns true. If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called falsy. Examples of expressions that can be converted to false are: null; NaN; 0; empty string ("" or '' or ``);
undefined. Even though the ! operator can be used with operands that are not Boolean values, it can still be considered a boolean operator since its return value can always be converted to a boolean primitive. To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator or the Boolean constructor. Examples Using NOT The following c...
Logical nullish assignment (??=) - JavaScript
The logical nullish assignment (x ??= y) operator only assigns if x is nullish (null or
undefined). The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax expr1 ??= expr2 Description Short-circuit evaluation The nullish coalescing operator is evaluated left to right, it is tested for possible short-circuit evaluation using the following rule: (some expression that is neither null nor
undefined) ?? expr is short-circuit evaluated to the left-hand side expression if the left-hand side proves to be neither null nor
undefined. Short circuit means that the expr part above is not evaluated, hence any side effects of doi...
Operator precedence - JavaScript
, other short-circuited operators include logical conjunction ("AND"), nullish-coalescing, optional chaining, and the conditional operator. Some more examples follow. a || (b * c); // evaluate `a` first, then produce `a` if `a` is "truthy" a && (b < c); // evaluate `a` first, then produce `a` if `a` is "falsy" a ?? (b || c); // evaluate `a` first, then produce `a` if `a` is not `null` and not `
undefined` a?.b.c; // evaluate `a` first, then produce `
undefined` if `a` is `null` or `
undefined` Examples 3 > 2 && 2 > 1 // returns true 3 > 2 > 1 // Returns false because 3 > 2 is true, then true is converted to 1 // in inequality operators, therefore true > 1 becomes 1 > 1, which // is false. Adding parentheses makes things clear: (3 > 2) > 1. Table The following table is ordered from hi...
await - JavaScript
log(y); // 20 } f3(); Promise rejection If the Promise is rejected, the rejected value is thrown. async function f4() { try { var z = await Promise.reject(30); } catch(e) { console.error(e); // 30 } } f4(); Handling rejected promises Handle rejected Promise without try block. var response = await promisedFunction().catch((err) => { console.error(err); }); // response will be
undefined if the promise is rejected Specifications Specification ECMAScript (ECMA-262)The definition of 'async functions' in that specification. ...
instanceof - JavaScript
Interface works as expected, even if obj is from a different scope. Examples Demonstrating that String and Date are of type Object and exceptional cases The following code uses instanceof to demonstrate that String and Date objects are also of type Object (they are derived from Object). However, objects created with the object literal notation are an exception here: Although the prototype is
undefined, instanceof Object returns true. let simpleStr = 'This is a simple string' let myString = new String() let newStr = new String('String created with constructor') let myDate = new Date() let myObj = {} let myNonObj = Object.create(null) simpleStr instanceof String // returns false, string literal is not an object myString instanceof String // returns true newStr instanceof Stri...
new operator - JavaScript
objects created with that function, rather than by just one instance of the object type. The following code adds a color property with value "original color" to all objects of type Car, and then overwrites that value with the string "black" only in the instance object car1. For more information, see prototype. ...
break - JavaScript
are nested within a loop, or labeled block that the break statements are intended to break out of. function testBreak(x) { var i = 0; while (i < 6) { if (i == 3) { (function() { break; })(); } i += 1; } return i * x; } testBreak(1); // SyntaxError: Illegal break statement block_1: { console.log('1'); ( function() { break block_1; // SyntaxError:
Undefined label 'block_1' })(); } Specifications Specification ECMAScript (ECMA-262)The definition of 'Break statement' in that specification. ...
for...of - JavaScript
s not make sense! for (const o of gen) { console.log(o); // Never called. } Iterating over other iterable objects You can also iterate over an object that explicitly implements the iterable protocol: const iterable = { [Symbol.iterator]() { return { i: 0, next() { if (this.i < 3) { return { value: this.i++, done: false }; } return { value:
undefined, done: true }; } }; } }; for (const value of iterable) { console.log(value); } // 0 // 1 // 2 Difference between for...of and for...in Both for...in and for...of statements iterate over something. The main difference between them is in what they iterate over. The for...in statement iterates over the enumerable properties of an object, in an arbitrary order. The for...of statem...
if...else - JavaScript
tements within a clause, use a block statement ({ ... }) to group those statements. In general, it is a good practice to always use block statements, especially in code involving nested if statements: if (condition) { statements1 } else { statements2 } Do not confuse the primitive Boolean values true and false with truthiness or falsiness of the Boolean object. Any value that is not false,
undefined, null, 0, -0, NaN, or the empty string (""), and any object, including a Boolean object whose value is false, is considered truthy when used as the condition. For example: var b = new Boolean(false); if (b) // this condition is truthy Examples Using if...else if (cipher_char === from_char) { result = result + to_char; x++; } else { result = result + clear_char; } Using else if Note ...