Let's say that I have an object reference as follows in coffeescript:
object.param.foo.bar
and I want to validate that bar exists? How do I do that?
I believe that object.param.foo?.bar tests for the existence of foo, returning undefined if it does not exist, but that object.param.foo.bar? converts the entire expression into a boolean test.
What I want is something that returns object.param.foo.bar if it exists and undefined if it does not.
I think you're looking for the expression
object.param?.foo?.bar
which assumes that object exists, and will return undefined if either the .param, .foo, or .bar properties don't exist. You can omit ?s if you know they do exist.
I'm not sure I understand your question (how does object.param.foo?.bar not do what you want? you haven't told us.).
But if you want to perform null checks the whole way (in case object, object.param or object.param.bar is null), you can use:
bar = object?.param?.foo?.bar
This will produce undefined if anything along this chain is null or undefined, and the value of object.param.foo.bar if it exists.
Related
I sometimes have to write code in JavaScript that handles both null and undefined the same way. For example, a function that removes from an array every item that is either null or undefined. How should I name the function?
removeNullAndUndefined is very long. removeNull is short but imprecise. Ideally I want to name it removeX, where X has the meaning "null or undefined".
Does anyone know a good word for X?
Yes: Nullish. For instance, in the current Stage 3 Nullish Coalescing Operator proposal.
So: removeNullish or similar.
When I need to check for null or undefined I often name such function either isNil or isNothing e.g.
const isNil = thing => thing === null || thing === undefined;
If you must adopt a naming convention I'd opt for what's quite common to see in functional programming, namely the Maybe monad which comes with a subtype to represent nothing: Nothing or None.
If you look at monetjs:
The Maybe type is the most common way of representing nothingness (or the null type) with making the possibilities of NullPointer issues disappear.
Maybe is effectively abstract and has two concrete subtypes: Some (also Just) and None (also Nothing).
Under the hood, it uses a isNothing function for checking for null or undefined
In ramda.js, such function is called isNil:
Checks if the input value is null or undefined
(Lodash has a similar method with the exact same name.)
I was wondering if it is safe to assume that in JavaScript a variable will always have a "constructor" property if its value is not "null" or "undefined".
I ran into a situation where I had to check if a variable is defined and that if it is an array and if so check if its length is > 0:
if(variable && variable.constructor === Array && variable.length > 0) {
...loop through the array
}
Am I right to assume that variable will always have a constructor if it is not "undefined" or "null"?
Your if statement won't throw because you've made that assumption, because anything that passes your first check will support your second, even if there is no constructor property (you'll just get undefined), and in fact even if it's not an object (it'll get temporarily promoted). So in that sense yes, you can happily do what you're doing — unless you could be dealing with an array from another window, in which case the === Array will fail (as dandavis pointed out) because different windows have different instances of the Array constructor.
Note that this is not the same as every object having a constructor property. It's just that if the object doesn't, you'll get undefined, rather than an error. (You can get an object with no constructor property by creating an object with no prototype: var obj = Object.create(null); or by using an object whose prototype is null as the object's prototype.)
However, somewhat tangentially, I wouldn't use that mechanism to check whether something is an array. In any modern environment, I'd use Array.isArray; and I'd shim/polyfill it on older environments. This also has the happy effect of working with arrays from other windows.
undefined or null do not have constructors and will error if you try to get it. Just try it out on Ctrl+Shift+I, and play around with it. Though, I doubt your if statement would cause much trouble, and it'd most likely error on pratical use.
You do NOT need to check length or anything, only see if it exists (or if you want specifically array, you could check that aswell).
Common practice when checking whether a variable is undefined in JavaScript is as follows:
var isUndefined=(typeof variableName==="undefined");
I've recently come across the use of two exclamation symbols to determine the same logic:
var isUndefined=!!variableName;
Is it safe to use these methods interchangeably?Are both equally compatible across browsers?
Is there any reason why one shouldn't use the "!!" method? (It seems more concise and easy to read)
Is it safe to use these methods interchangeably?
No. Details below, but they're not interchangeable even if you remove one of the ! from your second example (with two of them, it will be true for undefined, which isn't what you seem to want from the name of the variable you're assigning to). But that's not the only issue.
Are both equally compatible across browsers?
Yes. Each of them works reliably across browsers. But see above: They reliably don't do the same thing.
Is there any reason why one shouldn't use the "!!" method?
Yes, ! (again, not !!) gives the same result for 0, NaN, null, "", and false as it does for undefined.
Details:
When you do
var isUndefined = typeof variableName==="undefined";
(the () are unnecessary), you're doing a very specific test for undefined. It will only be true for undefined.
In contrast, when you do
var isUndefined = !variableName;
you're not testing for undefined, you're testing for any falsey value. The falsey values are the ones I listed earlier (0, NaN, null, "", false, and undefined). The result will be true for any of them.
Now, if you're expecting (for instance) to get a non-null object reference or undefined, the ! test is just fine. But if you really need to know whether something is undefined, specifically, you want the typeof test.
Also, as Felix Kling pointed out in a comment on the question, the ! test will throw a ReferenceError if the variable isn't defined at all (as opposed to being defined but having the value undefined), because it tries to read the value of the variable. The typeof test is safe if you're not sure whether the variable exists at all, because it doesn't try to read its value.
I have an object that with properties, 1 of those properties prop2 will only be initialised later and added to this object when its ready.
I want to show it as a property of the object purely for human readability so that when I look at the code later I will know that it exists and will/can be used.
So my question is what is:
What is the correct way to initialise an empty property of an object
in JavaScript
myObject = {
prop1: 'somevalue',
prop2: '' <---- ''|null|undefined|false|0|{} what is correct
}
I am assuming it depends on the type that will be used, and I realise that anything actually works, I am interested in the best practice way.
Fiddler: http://jsfiddle.net/gamelodge/DWCEa/
I usually use null for this purpose. It is distinct from undefined (does not exist) and satisfies the requirement that the variable exists but has no value.
The usual way is to use null.
undefined would work as well, but a) it's longer b) it's not a keyword c) too many people use typeof to test for property existence. It also has a little different notion.
As you said, depending on the expected type you might as well use any other appropriate value. Empty objects or strings are less convential, especially since objects have lots of construction overhead. Do not use them if you don't plan to use (extend) them later.
Hi I'm very new to JS.
Lets say I have an object named test which doesn't have a property missing. But I try to access the same:
test.missing //getting undefined as output
Now I'm trying to access the missing properties ( like this test.missing.404 ) which will give me a TypeError. But my book says we can get rid of this TypeError by like this:
test.missing && test.missing.404
Now my big question is how one can do a && against the undefined type and TypeError type. Couldn't able to guess what Js is doing here.
Thanks in advance.
undefined in js is treated as false and if something has value it is treated as true, so:
//if test.missing is NOT undefined and test.missing.404 is also NOT undefined
if (test.missing && test.missing.404)
First of you should know that JS like many other programming languages uses short circuit technique during comparison. So in this case if the first condition is false then there is no need to check the next condition(s). This is due to the fact that 0 && X will always result 0 .
With that said, test.missing && test.missing.404 can be perceive as "if the test object has missing property and the (test object's) missing property has 404 property" then proceed. Which the JS intepreter will completely ignore the check for 404 property on missing property if the test object has no missing property in the first place.
So the point is the above code is not && comparison of undefined and TypeError but rather check for missing property first and 404 property if first property exists. I hope this makes sense ad explains it well enough.