Rectangle 27 114

As others have explained, the "black hole" is because throwing inside a .catch continues the chain with a rejected promise, and you have no more catches, leading to an unterminated chain, which swallows errors (bad!)

do1().then(do2).catch(function(err) {
    //console.log(err.stack); // This is the only way to see the stack
    throw err; // Where does this go?
}).catch(function(err) {
    console.log(err.stack); // It goes here!
});

A catch in the middle of a chain is useful when you want the chain to proceed in spite of a failed step, but a re-throw is useful to continue failing after doing things like logging of information or cleanup steps, perhaps even altering which error is thrown.

To make the error show up as an error in the web console, as you originally intended, I use this trick:

.catch(function(err) { setTimeout(function() { throw err; }); });

Even the line numbers survive, so the link in web console takes me straight to the file and line where the (original) error happened.

Any exception in a function called as a promise fulfillment or rejection handler gets automatically converted to a rejection of the promise you're supposed to return. The promise code that calls your function takes care of this.

A function called by setTimeout on the other hand, always runs from JavaScript stable state, i.e. it runs in a new cycle in the JavaScript event loop. Exceptions there aren't caught by anything, and make it to the web console. Since err holds all the information about the error, including the original stack, file and line number, it still gets reported correctly.

Jib, that's an interesting trick, can you help me understand why that works?

About that trick: you are throwing because you want to log, so why not just log directly? This trick will at a 'random' time throw an uncatchable error.... But the whole idea of exceptions (and the way promises deal with them) is to make it the caller's responsibility to catch the error and deal with it. This code effectively makes it impossible for the caller to deal with the errors. Why not just make a function to handle it for you? function logErrors(e){console.error(e)} then use it like do1().then(do2).catch(logErrors). Answer itself is great btw, +1

@jib I am writing an AWS lambda which contains many promises connected more or less like in this case. To exploit AWS alarms and notifications in case of errors I need to make the lambda crash throwing an error (I guess). Is the trick the only way to obtain this?

@StijndeWitt In my case, I was trying to send error details to my server in window.onerror event handler. Only by doing the setTimeout trick can this be done. Otherwise window.onerror will never hear a thing about the errors happened in Promise.

@hudidit Still, wheter it's console.log or postErrorToServer, you can just do what needs to be done. There is no reason whatever code is in window.onerror cannot be factored out into a separate function and be called from 2 places. It's probably even shorter then the setTimeout line.

javascript - Why can I not throw inside a Promise.catch handler? - Sta...

javascript asynchronous promise throw es6-promise
Rectangle 27 35

In your case, you are rejecting inside do1 by throwing an Error object. Now, the current promise will be in rejected state and the control will be transferred to the next handler, which is then in our case.

Since the then handler doesn't have a rejection handler, the do2 will not be executed at all. You can confirm this by using console.log inside it. Since the current promise doesn't have a rejection handler, it will also be rejected with the rejection value from the previous promise and the control will be transferred to the next handler which is catch.

As catch is a rejection handler, when you do console.log(err.stack); inside it, you are able to see the error stack trace. Now, you are throwing an Error object from it so the promise returned by catch will also be in rejected state.

Since you have not attached any rejection handler to the catch, you are not able to observe the rejection.

You can split the chain and understand this better, like this

var promise = do1().then(do2);

var promise1 = promise.catch(function (err) {
    console.log("Promise", promise);
    throw err;
});

promise1.catch(function (err) {
    console.log("Promise1", promise1);
});
Promise Promise { <rejected> [Error: do1] }
Promise1 Promise { <rejected> [Error: do1] }

Inside the catch handler 1, you are getting the value of promise object as rejected.

Same way, the promise returned by the catch handler 1, is also rejected with the same error with which the promise was rejected and we are observing it in the second catch handler.

Might also be worth adding that .then() handlers are async (stack is unwound before they are executed) so exceptions inside them have to be turned into rejections, otherwise there would be no exception handlers to catch them.

javascript - Why can I not throw inside a Promise.catch handler? - Sta...

javascript asynchronous promise throw es6-promise
Rectangle 27 65

Works in mobile apps (built using JQM) as well.

Works in Chromium as well (version 43 anyway).

How can I get a Javascript stack trace when I throw an exception? - St...

javascript stack-trace
Rectangle 27 11

Most of the regex solutions here throw errors when the string can't be parsed, and not many of them account for strings like 1330 or 130pm. Even though these formats weren't specified by the OP, I find them critical for parsing dates input by humans.

All of this got me to thinking that using a regular expression might not be the best approach for this.

My solution is a function that not only parses the time, but also allows you to specify an output format and a step (interval) at which to round minutes to. At about 70 lines, it's still lightweight and parses all of the aforementioned formats as well as ones without colons.

And below in case the links break someday:

function parseTime(time, format, step) {

    var hour, minute, stepMinute,
        defaultFormat = 'g:ia',
        pm = time.match(/p/i) !== null,
        num = time.replace(/[^0-9]/g, '');

    // Parse for hour and minute
    switch(num.length) {
        case 4:
            hour = parseInt(num[0] + num[1], 10);
            minute = parseInt(num[2] + num[3], 10);
            break;
        case 3:
            hour = parseInt(num[0], 10);
            minute = parseInt(num[1] + num[2], 10);
            break;
        case 2:
        case 1:
            hour = parseInt(num[0] + (num[1] || ''), 10);
            minute = 0;
            break;
        default:
            return '';
    }

    // Make sure hour is in 24 hour format
    if( pm === true && hour > 0 && hour < 12 ) hour += 12;

    // Force pm for hours between 13:00 and 23:00
    if( hour >= 13 && hour <= 23 ) pm = true;

    // Handle step
    if( step ) {
        // Step to the nearest hour requires 60, not 0
        if( step === 0 ) step = 60;
        // Round to nearest step
        stepMinute = (Math.round(minute / step) * step) % 60;
        // Do we need to round the hour up?
        if( stepMinute === 0 && minute >= 30 ) {
            hour++;
            // Do we need to switch am/pm?
            if( hour === 12 || hour === 24 ) pm = !pm;
        }
        minute = stepMinute;
    }

    // Keep within range
    if( hour <= 0 || hour >= 24 ) hour = 0;
    if( minute < 0 || minute > 59 ) minute = 0;

    // Format output
    return (format || defaultFormat)
        // 12 hour without leading 0
        .replace(/g/g, hour === 0 ? '12' : 'g')
        .replace(/g/g, hour > 12 ? hour - 12 : hour)
        // 24 hour without leading 0
        .replace(/G/g, hour)
        // 12 hour with leading 0
        .replace(/h/g, hour.toString().length > 1 ? (hour > 12 ? hour - 12 : hour) : '0' + (hour > 12 ? hour - 12 : hour))
        // 24 hour with leading 0
        .replace(/H/g, hour.toString().length > 1 ? hour : '0' + hour)
        // minutes with leading zero
        .replace(/i/g, minute.toString().length > 1 ? minute : '0' + minute)
        // simulate seconds
        .replace(/s/g, '00')
        // lowercase am/pm
        .replace(/a/g, pm ? 'pm' : 'am')
        // lowercase am/pm
        .replace(/A/g, pm ? 'PM' : 'AM');

}

I had to mark this up. It's the only really useful answer when size matters. Most of the time I use momentjs but that's enormous compared to this solution.

Bug report: "12am" parses the same as "12pm"

"12am" parses to 12:00 (ie, noon) instead of 00:00 (ie, midnight). Same problem for any time between midnight and 12:59am.

I needed that, and so went ahead and fixed that with a dirty hack: codepen.io/anon/pen/EjrVqq there should be a better solution, but I couldn't put my finger on it yet.

datetime - What is the best way to parse a time into a Date object fro...

javascript datetime parsing date time
Rectangle 27 13

Quoting from the post:

No more support for IE 6/7/8: Remember that this can also affect IE9 and even IE10 if they are used in their Compatibility View modes that emulate older versions. To prevent these newer IE versions from slipping back into prehistoric modes, we suggest you always use an X-UA-Compatible tag or HTTP header. If you can use the HTTP header it is slightly better for performance because it avoids a potential browser parser restart.

Reduced size: The final 2.0.0 file is 12 percent smaller than the 1.9.1 file, thanks to the elimination of patches that were only needed for IE 6, 7, and 8. We had hoped to remove even more code and increase performance, but older Android/WebKit 2.x browsers are now the weakest link. Were carefully watching Android 2.x market share to determine when we can cross it off the support list, and dont expect it to take very long.

Keep jQuery 1.9 (Edit 2015-11-17: jQuery 1.11.3 is the current 1.x version of jQuery.) if IE 6/7/8 are a concern.

Sometimes, you have to look to the source of the code to determine the issue. Thanks!

THANK YOU! I was bashing my head against the wall trying to figure out why my application wasn't working in IE8 (yes, we still have users running XP, unfortunately). It was because I was using the version of jQuery installed by NuGet in Visual Studio 2012.

javascript - IE8 is throwing error with jQuery - Stack Overflow

javascript jquery internet-explorer-8
Rectangle 27 5

As you had found out, your code execute the function which throws the error & should doesn't get a chance to catch it.

To allow proper assertion, you need to wrap the function call in an anonymous function.

should(function ()  {MyClass.methodThatShouldThrow();} ).throw('what were you thinking, batman?')
undefined is not a function
throw
throws

And if you are using es2015, then it will more compact with arrow function for the anon function

javascript - Checking for a throw new Error with should.js and Mocha -...

javascript node.js mocha should.js
Rectangle 27 2

Put your JavaScript in the below of the body. It throws error because your JavaScript first works when your DOM doesn't ready.

And it is a good practice to load all scripts at the end of the body

<html>
<body>
<input id="inp" type='file'>
<p id="b64"></p>
<img id="img">

<script type="text/javascript">
function EL(id) { return document.getElementById(id); } // Get el by ID helper function

function readFile() {
  if (this.files && this.files[0]) {
    var FR= new FileReader();
    FR.onload = function(e) {
      EL("img").src       = e.target.result;
      EL("b64").innerHTML = e.target.result;
    };       
    FR.readAsDataURL( this.files[0] );
  }
}

EL("inp").addEventListener("change", readFile, false);
</script>

</body>
</html>

thanks it was working.. How to extract the encrypt value and store it in variable

@user3548039 open a new question and put the code there

jquery - javascript:Uncaught TypeError: Cannot read property 'addEvent...

javascript jquery html
Rectangle 27 7

You can access the stack (stacktrace in Opera) properties of an Error instance even if you threw it. The thing is, you need to make sure you use throw new Error(string) (don't forget the new instead of throw string.

try {
    0++;
} catch (e) {
    var myStackTrace = e.stack || e.stacktrace || "";
}

@NV: It seems stacktrace isn't on user-created errors so you should do this instead: try { 0++ } catch(e) { myStackTrace=e.stack || e.stacktrace }

How can I get a Javascript stack trace when I throw an exception? - St...

javascript stack-trace
Rectangle 27 296

There is no assert in JavaScript (yet; there's talk of adding one, but it's at an early stage). Perhaps you're using some library that provides one. The usual meaning is to throw an error if the expression passed into the function is false; this is part of the general concept of assertion checking. Usually assertions (as they're called) are used only in "testing" or "debug" builds and stripped out of production code.

Suppose you had a function that was supposed to always accept a string. You'd want to know if someone called that function with something that wasn't a string. So you might do:

assert(typeof argumentName === "string");

...where assert would throw an error if the condition were false.

A very simple version would look like this:

Better yet, make use of the Error object if the JavaScript engine supports it (really old ones might not), which has the advantage of collecting a stack trace and such:

function assert(condition, message) {
    if (!condition) {
        message = message || "Assertion failed";
        if (typeof Error !== "undefined") {
            throw new Error(message);
        }
        throw message; // Fallback
    }
}

Even IE8 has Error (although it doesn't have the stack property, but modern engines [including modern IE] do).

...getting uppity about types in JS? I'd argue that's one of the worst reasons to assert.

@cHao: There are valid use cases. It was just the first example that came to mind. The example isn't the point. The concept of assertions is the point.

something that I've added to my code inside the if(!condition) is setting var throwError=true; then debugger; then wrap the throw section in an if(throwError). That way, if I have the debugger open, it'll break, and if I so desire I can set throwError to false and then examine all the scopes while stepping out.

@Rick if you use Chrome DevTools, you can simply enable "Pause on Uncaught Exceptions" in the Sources tab and it will automatically break at the throw. That way you don't need the debugger; statement. See developer.chrome.com/devtools/docs/ for more.

function (condition, message) {         if (condition) return;                  message = message || 'Assertion failed';         throw typeof Error !== 'undefined' ? new Error(message) : message; // Very old browsers lacks Error     }

What is “assert” in JavaScript? - Stack Overflow

javascript assert
Rectangle 27 291

There is no assert in JavaScript (yet; there's talk of adding one, but it's at an early stage). Perhaps you're using some library that provides one. The usual meaning is to throw an error if the expression passed into the function is false; this is part of the general concept of assertion checking. Usually assertions (as they're called) are used only in "testing" or "debug" builds and stripped out of production code.

Suppose you had a function that was supposed to always accept a string. You'd want to know if someone called that function with something that wasn't a string. So you might do:

assert(typeof argumentName === "string");

...where assert would throw an error if the condition were false.

A very simple version would look like this:

Better yet, make use of the Error object if the JavaScript engine supports it (really old ones might not), which has the advantage of collecting a stack trace and such:

function assert(condition, message) {
    if (!condition) {
        message = message || "Assertion failed";
        if (typeof Error !== "undefined") {
            throw new Error(message);
        }
        throw message; // Fallback
    }
}

Even IE8 has Error (although it doesn't have the stack property, but modern engines [including modern IE] do).

...getting uppity about types in JS? I'd argue that's one of the worst reasons to assert.

@cHao: There are valid use cases. It was just the first example that came to mind. The example isn't the point. The concept of assertions is the point.

something that I've added to my code inside the if(!condition) is setting var throwError=true; then debugger; then wrap the throw section in an if(throwError). That way, if I have the debugger open, it'll break, and if I so desire I can set throwError to false and then examine all the scopes while stepping out.

@Rick if you use Chrome DevTools, you can simply enable "Pause on Uncaught Exceptions" in the Sources tab and it will automatically break at the throw. That way you don't need the debugger; statement. See developer.chrome.com/devtools/docs/ for more.

function (condition, message) {         if (condition) return;                  message = message || 'Assertion failed';         throw typeof Error !== 'undefined' ? new Error(message) : message; // Very old browsers lacks Error     }

What is “assert” in JavaScript? - Stack Overflow

javascript assert
Rectangle 27 9

You may need to throw something, but it does not have to be an error.

Most promise implementations have method catch accepting the first argument as error type (but not all, and not ES6 promise), it would be helpful under this situation:

function BreakSignal() { }

getPromise()
    .then(function () {
        throw new BreakSignal();
    })
    .then(function () {
        // Something to skip.
    })
    .catch(BreakSignal, function () { })
    .then(function () {
        // Continue with other works.
    });

I add the ability to break in the recent implementation of my own promise library. And if you were using ThenFail (as you would probably not), you can write something like this:

getPromise()
    .then(function () {
        Promise.break;
    })
    .then(function () {
        // Something to skip.
    })
    .enclose()
    .then(function () {
        // Continue with other works.
    });

javascript - how to break promise chain - Stack Overflow

javascript selenium-webdriver promise selenium-chromedriver
Rectangle 27 69

Extending builtin types like Array and Error and such has never been supported in Babel. It is perfectly valid in a real ES6 environment, but there are requirements to make it work that are very difficult to transpile in a way that is compatible with older browsers. It "worked" in Babel 5 in that it didn't throw an error, but objects instantiated from the extended subclass did not work like they were supposed to, for example:

class MyError extends Error {}

var e1 = new MyError();
var e2 = new Error();

console.log('e1', 'stack' in e1);
console.log('e2', 'stack' in e2);

results in

e1 false
e2 true

While it did not error out, the subclass does not properly get a 'stack' like errors are supposed to. Similarly, if you were to extend Array it might behave somewhat like an array, and have array methods, but it did not behave fully like an array.

The Babel 5 documentation specifically called this out as an edge-case of classes to be aware of.

In Babel 6, classes were changed to be more spec-compliant in how subclassing is handled, and a side-effect of that is that now the above code will still not work, but it will not work in a different way than before. This has been covered in https://phabricator.babeljs.io/T3083, but I'll elaborate here on a potential solution.

To return Babel 5 subclassing behavior (which remember, is still not right or recommended), you can wrap the builtin constructor in your own temporary class, e.g.

function ExtendableBuiltin(cls){
    function ExtendableBuiltin(){
        cls.apply(this, arguments);
    }
    ExtendableBuiltin.prototype = Object.create(cls.prototype);
    Object.setPrototypeOf(ExtendableBuiltin, cls);

    return ExtendableBuiltin;
}
class MyError extends ExtendableBuiltin(Error) {}

In your specific case however, you have said that you are on Node 5.x. Node 5 has support for native ES6 classes without transpiling. I'd recommend you use those by dropping the es2015 preset and instead using node5 so you get native classes, among other things. In that context,

class MyError extends Error {}

For people not on Node 4/5, or recent Chrome only, you may want to consider using something like https://www.npmjs.com/package/error. You can also explore https://www.npmjs.com/package/babel-plugin-transform-builtin-extend. The approximate option from that is the same behavior from Babel 5. Beware that the non-approximate behavior is definitely edge-casey and may not work in 100% of cases.

Aha thanks. So what is the recommended way of creating new exception classes then??

After all, the MDN recommends prototypal inheritance of Error to create new exception classes. AFAICT, this should correspond to subclassing in ES6, unless I'm overlooking something. I also found this article on ES6 class semantics that has an example exactly of sublassing Error.

Is it fixed yet? Or will it ever be fixed? They put Wontfix tag on this issue in phabricator, this is kind of disappointing because I thought I should expect this feature to work, at least if Babel did it right and according to the specification.

var CustomError = function(message){   Error.call(this, message)   this.message = message  }

javascript - Why doesn't instanceof work on instances of Error subclas...

javascript node.js ecmascript-6 babeljs
Rectangle 27 171

The slow and reliable in operator and hasOwnProperty method

How do I check if a particular key exists in a JavaScript object or array? If a key doesn't exist and I try to access it, will it return false? Or throw an error?

Accessing directly a missing property using (associative) array style or object style will return an undefined constant.

As people have already mentioned here, you could have an object with a property associated with an "undefined" constant.

var bizzareObj = {valid_key:  undefined};

In that case, you will have to use hasOwnProperty or in operator to know if the key is really there. But, but at what price?

in operator and hasOwnProperty are "methods" that use Property Descriptor mechanism in Javascript (similar to Java reflection in the Java language).

The Property Descriptor type is used to explain the manipulation and reification of named property attributes. Values of the Property Descriptor type are records composed of named fields where each fields name is an attribute name and its value is a corresponding attribute value as specified in 8.6.1. In addition, any field may be present or absent.

On the other hand, calling an object method or key will use Javascript [[Get]] mechanism. That is far way faster!

var result = "Impression" in array;

The result was

12,931,832 0.21% ops/sec      92% slower
var result = array.hasOwnProperty("Impression")
16,021,758 0.45% ops/sec     91% slower
var result = array["Impression"] === undefined
168,270,439 0.13 ops/sec     0.02% slower
var result = array.Impression  === undefined;

The result was

168,303,172 0.20%     fastest
null
undefined

null is the primitive value that represents the intentional absence of any object value, or in short terms, the confirmed lack of value. On the other hand, undefined is unknown value (not defined). If there is a property that will be used later with a proper value consider use null reference instead of undefined because in the initial moment the property is confirmed to lack a value.

var a = {1: null}; 
console.log(a[1] === undefined); // output: false. I know the value at position 1 of a[] is absent and this was by design, i.e.:  the value is defined. 
console.log(a[0] === undefined); // output: true. I cannot say anything about a[0] value. In this case, the key 0 was not in a[].

Avoid objects with undefined values. Check directly whenever possible and use null to initialize property values. Otherwise, use the slow in operator or hasOwnProperty() method.

Are all of these methods acceptable in all commonly used browsers, e.g. IE8+?

+1 for benchmarking. Thank you, this is exactly the information I was hoping to find. Definitely a strong argument to write code that never assigns or expects a key to contain the value undefined.

I was curious how Underscore.js's has() compared, so I added it to the jsperf (version 11). Turns out it's in the slow group along with in and hasOwnProperty().

One reason I would set undefined to a hash value is that I actually wanted to delete that property key from the hash, but delete hash[key] is much slower than hash[key] = undefined. Of course in this case it makes no sense for me to need the in operator, but it acts as a counterexample to we should always avoid setting value to undefined.

arrays - Checking if a key exists in a JavaScript object? - Stack Over...

javascript arrays object
Rectangle 27 170

The slow and reliable in operator and hasOwnProperty method

How do I check if a particular key exists in a JavaScript object or array? If a key doesn't exist and I try to access it, will it return false? Or throw an error?

Accessing directly a missing property using (associative) array style or object style will return an undefined constant.

As people have already mentioned here, you could have an object with a property associated with an "undefined" constant.

var bizzareObj = {valid_key:  undefined};

In that case, you will have to use hasOwnProperty or in operator to know if the key is really there. But, but at what price?

in operator and hasOwnProperty are "methods" that use Property Descriptor mechanism in Javascript (similar to Java reflection in the Java language).

The Property Descriptor type is used to explain the manipulation and reification of named property attributes. Values of the Property Descriptor type are records composed of named fields where each fields name is an attribute name and its value is a corresponding attribute value as specified in 8.6.1. In addition, any field may be present or absent.

On the other hand, calling an object method or key will use Javascript [[Get]] mechanism. That is far way faster!

var result = "Impression" in array;

The result was

12,931,832 0.21% ops/sec      92% slower
var result = array.hasOwnProperty("Impression")
16,021,758 0.45% ops/sec     91% slower
var result = array["Impression"] === undefined
168,270,439 0.13 ops/sec     0.02% slower
var result = array.Impression  === undefined;

The result was

168,303,172 0.20%     fastest
null
undefined

null is the primitive value that represents the intentional absence of any object value, or in short terms, the confirmed lack of value. On the other hand, undefined is unknown value (not defined). If there is a property that will be used later with a proper value consider use null reference instead of undefined because in the initial moment the property is confirmed to lack a value.

var a = {1: null}; 
console.log(a[1] === undefined); // output: false. I know the value at position 1 of a[] is absent and this was by design, i.e.:  the value is defined. 
console.log(a[0] === undefined); // output: true. I cannot say anything about a[0] value. In this case, the key 0 was not in a[].

Avoid objects with undefined values. Check directly whenever possible and use null to initialize property values. Otherwise, use the slow in operator or hasOwnProperty() method.

Are all of these methods acceptable in all commonly used browsers, e.g. IE8+?

+1 for benchmarking. Thank you, this is exactly the information I was hoping to find. Definitely a strong argument to write code that never assigns or expects a key to contain the value undefined.

I was curious how Underscore.js's has() compared, so I added it to the jsperf (version 11). Turns out it's in the slow group along with in and hasOwnProperty().

One reason I would set undefined to a hash value is that I actually wanted to delete that property key from the hash, but delete hash[key] is much slower than hash[key] = undefined. Of course in this case it makes no sense for me to need the in operator, but it acts as a counterexample to we should always avoid setting value to undefined.

arrays - Checking if a key exists in a JavaScript object? - Stack Over...

javascript arrays object
Rectangle 27 170

The slow and reliable in operator and hasOwnProperty method

How do I check if a particular key exists in a JavaScript object or array? If a key doesn't exist and I try to access it, will it return false? Or throw an error?

Accessing directly a missing property using (associative) array style or object style will return an undefined constant.

As people have already mentioned here, you could have an object with a property associated with an "undefined" constant.

var bizzareObj = {valid_key:  undefined};

In that case, you will have to use hasOwnProperty or in operator to know if the key is really there. But, but at what price?

in operator and hasOwnProperty are "methods" that use Property Descriptor mechanism in Javascript (similar to Java reflection in the Java language).

The Property Descriptor type is used to explain the manipulation and reification of named property attributes. Values of the Property Descriptor type are records composed of named fields where each fields name is an attribute name and its value is a corresponding attribute value as specified in 8.6.1. In addition, any field may be present or absent.

On the other hand, calling an object method or key will use Javascript [[Get]] mechanism. That is far way faster!

var result = "Impression" in array;

The result was

12,931,832 0.21% ops/sec      92% slower
var result = array.hasOwnProperty("Impression")
16,021,758 0.45% ops/sec     91% slower
var result = array["Impression"] === undefined
168,270,439 0.13 ops/sec     0.02% slower
var result = array.Impression  === undefined;

The result was

168,303,172 0.20%     fastest
null
undefined

null is the primitive value that represents the intentional absence of any object value, or in short terms, the confirmed lack of value. On the other hand, undefined is unknown value (not defined). If there is a property that will be used later with a proper value consider use null reference instead of undefined because in the initial moment the property is confirmed to lack a value.

var a = {1: null}; 
console.log(a[1] === undefined); // output: false. I know the value at position 1 of a[] is absent and this was by design, i.e.:  the value is defined. 
console.log(a[0] === undefined); // output: true. I cannot say anything about a[0] value. In this case, the key 0 was not in a[].

Avoid objects with undefined values. Check directly whenever possible and use null to initialize property values. Otherwise, use the slow in operator or hasOwnProperty() method.

Are all of these methods acceptable in all commonly used browsers, e.g. IE8+?

+1 for benchmarking. Thank you, this is exactly the information I was hoping to find. Definitely a strong argument to write code that never assigns or expects a key to contain the value undefined.

I was curious how Underscore.js's has() compared, so I added it to the jsperf (version 11). Turns out it's in the slow group along with in and hasOwnProperty().

One reason I would set undefined to a hash value is that I actually wanted to delete that property key from the hash, but delete hash[key] is much slower than hash[key] = undefined. Of course in this case it makes no sense for me to need the in operator, but it acts as a counterexample to we should always avoid setting value to undefined.

arrays - Checking if a key exists in a JavaScript object? - Stack Over...

javascript arrays object
Rectangle 27 170

The slow and reliable in operator and hasOwnProperty method

How do I check if a particular key exists in a JavaScript object or array? If a key doesn't exist and I try to access it, will it return false? Or throw an error?

Accessing directly a missing property using (associative) array style or object style will return an undefined constant.

As people have already mentioned here, you could have an object with a property associated with an "undefined" constant.

var bizzareObj = {valid_key:  undefined};

In that case, you will have to use hasOwnProperty or in operator to know if the key is really there. But, but at what price?

in operator and hasOwnProperty are "methods" that use Property Descriptor mechanism in Javascript (similar to Java reflection in the Java language).

The Property Descriptor type is used to explain the manipulation and reification of named property attributes. Values of the Property Descriptor type are records composed of named fields where each fields name is an attribute name and its value is a corresponding attribute value as specified in 8.6.1. In addition, any field may be present or absent.

On the other hand, calling an object method or key will use Javascript [[Get]] mechanism. That is far way faster!

var result = "Impression" in array;

The result was

12,931,832 0.21% ops/sec      92% slower
var result = array.hasOwnProperty("Impression")
16,021,758 0.45% ops/sec     91% slower
var result = array["Impression"] === undefined
168,270,439 0.13 ops/sec     0.02% slower
var result = array.Impression  === undefined;

The result was

168,303,172 0.20%     fastest
null
undefined

null is the primitive value that represents the intentional absence of any object value, or in short terms, the confirmed lack of value. On the other hand, undefined is unknown value (not defined). If there is a property that will be used later with a proper value consider use null reference instead of undefined because in the initial moment the property is confirmed to lack a value.

var a = {1: null}; 
console.log(a[1] === undefined); // output: false. I know the value at position 1 of a[] is absent and this was by design, i.e.:  the value is defined. 
console.log(a[0] === undefined); // output: true. I cannot say anything about a[0] value. In this case, the key 0 was not in a[].

Avoid objects with undefined values. Check directly whenever possible and use null to initialize property values. Otherwise, use the slow in operator or hasOwnProperty() method.

Are all of these methods acceptable in all commonly used browsers, e.g. IE8+?

+1 for benchmarking. Thank you, this is exactly the information I was hoping to find. Definitely a strong argument to write code that never assigns or expects a key to contain the value undefined.

I was curious how Underscore.js's has() compared, so I added it to the jsperf (version 11). Turns out it's in the slow group along with in and hasOwnProperty().

One reason I would set undefined to a hash value is that I actually wanted to delete that property key from the hash, but delete hash[key] is much slower than hash[key] = undefined. Of course in this case it makes no sense for me to need the in operator, but it acts as a counterexample to we should always avoid setting value to undefined.

arrays - Checking if a key exists in a JavaScript object? - Stack Over...

javascript arrays object
Rectangle 27 170

The slow and reliable in operator and hasOwnProperty method

How do I check if a particular key exists in a JavaScript object or array? If a key doesn't exist and I try to access it, will it return false? Or throw an error?

Accessing directly a missing property using (associative) array style or object style will return an undefined constant.

As people have already mentioned here, you could have an object with a property associated with an "undefined" constant.

var bizzareObj = {valid_key:  undefined};

In that case, you will have to use hasOwnProperty or in operator to know if the key is really there. But, but at what price?

in operator and hasOwnProperty are "methods" that use Property Descriptor mechanism in Javascript (similar to Java reflection in the Java language).

The Property Descriptor type is used to explain the manipulation and reification of named property attributes. Values of the Property Descriptor type are records composed of named fields where each fields name is an attribute name and its value is a corresponding attribute value as specified in 8.6.1. In addition, any field may be present or absent.

On the other hand, calling an object method or key will use Javascript [[Get]] mechanism. That is far way faster!

var result = "Impression" in array;

The result was

12,931,832 0.21% ops/sec      92% slower
var result = array.hasOwnProperty("Impression")
16,021,758 0.45% ops/sec     91% slower
var result = array["Impression"] === undefined
168,270,439 0.13 ops/sec     0.02% slower
var result = array.Impression  === undefined;

The result was

168,303,172 0.20%     fastest
null
undefined

null is the primitive value that represents the intentional absence of any object value, or in short terms, the confirmed lack of value. On the other hand, undefined is unknown value (not defined). If there is a property that will be used later with a proper value consider use null reference instead of undefined because in the initial moment the property is confirmed to lack a value.

var a = {1: null}; 
console.log(a[1] === undefined); // output: false. I know the value at position 1 of a[] is absent and this was by design, i.e.:  the value is defined. 
console.log(a[0] === undefined); // output: true. I cannot say anything about a[0] value. In this case, the key 0 was not in a[].

Avoid objects with undefined values. Check directly whenever possible and use null to initialize property values. Otherwise, use the slow in operator or hasOwnProperty() method.

Are all of these methods acceptable in all commonly used browsers, e.g. IE8+?

+1 for benchmarking. Thank you, this is exactly the information I was hoping to find. Definitely a strong argument to write code that never assigns or expects a key to contain the value undefined.

I was curious how Underscore.js's has() compared, so I added it to the jsperf (version 11). Turns out it's in the slow group along with in and hasOwnProperty().

One reason I would set undefined to a hash value is that I actually wanted to delete that property key from the hash, but delete hash[key] is much slower than hash[key] = undefined. Of course in this case it makes no sense for me to need the in operator, but it acts as a counterexample to we should always avoid setting value to undefined.

arrays - Checking if a key exists in a JavaScript object? - Stack Over...

javascript arrays object
Rectangle 27 14

If you would like to use Dean Edward's suggestion and throw the StopIteration error to break out of the loop without having to catch the error, you can use the following the function (originally from here):

// Use a closure to prevent the global namespace from be polluted.
(function() {
  // Define StopIteration as part of the global scope if it
  // isn't already defined.
  if(typeof StopIteration == "undefined") {
    StopIteration = new Error("StopIteration");
  }

  // The original version of Array.prototype.forEach.
  var oldForEach = Array.prototype.forEach;

  // If forEach actually exists, define forEach so you can
  // break out of it by throwing StopIteration.  Allow
  // other errors will be thrown as normal.
  if(oldForEach) {
    Array.prototype.forEach = function() {
      try {
        oldForEach.apply(this, [].slice.call(arguments, 0));
      }
      catch(e) {
        if(e !== StopIteration) {
          throw e;
        }
      }
    };
  }
})();

The above code will give you the ability to run code such as the following without having to do your own try-catch clauses:

// Show the contents until you get to "2".
[0,1,2,3,4].forEach(function(val) {
  if(val == 2)
    throw StopIteration;
  alert(val);
});

One important thing to remember is that this will only update the Array.prototype.forEach function if it already exists. If it doesn't exist already, it will not modify the it.

javascript - How to short circuit Array.forEach like calling break? - ...

javascript arrays
Rectangle 27 9

Most likely you want if (window.x). This check is safe even if x hasn't been declared (var x;) - browser doesn't throw an error.

if (window.history) {
    history.call_some_function();
}

window is an object which holds all global variables as its members, and it is legal to try to access a non-existing member. If x hasn't been declared or hasn't been set then window.x returns undefined. undefined leads to false when if() evaluates it.

But what if you run in Node? typeof history != 'undefined' actually works in both systems.

javascript - Detecting an undefined object property - Stack Overflow

javascript object undefined
Rectangle 27 9

Most likely you want if (window.x). This check is safe even if x hasn't been declared (var x;) - browser doesn't throw an error.

if (window.history) {
    history.call_some_function();
}

window is an object which holds all global variables as its members, and it is legal to try to access a non-existing member. If x hasn't been declared or hasn't been set then window.x returns undefined. undefined leads to false when if() evaluates it.

But what if you run in Node? typeof history != 'undefined' actually works in both systems.

javascript - Detecting an undefined object property - Stack Overflow

javascript object undefined