When declaring variables what's the best practice?
My manager asked me to change a declaration from null to an empty string and I don't really see why?
Edit: This is for JavaScript
I've seen so many methods; but I am looking for a simple style I can adopt in my code to keep it consistent:
if (PostCodeInformation !== null PostCodeInformation !== undefined){
}
Videos
They closed my question on SO because it's not reproducible, but that's exactly why I posted, because code isn't behaving as it should.
Anyway, I 'm receiving a JSON result from a web service. It looks something like this:
{ "data": [{ "id": "123ABC", "name" : "Test 1" }, { "id": "", "name" : "Test 2" }] }I 'm looping through the data array and need to determine if an id exists or not:
for( const item of data ) {
if( item.id !== null && item.id.trim().length > 0 ) {
doSomething();
} else {
doSomethingElse();
}
}My problem is that doSomething() fires for the first item ("123ABC") but also fires for the second where the id is empty.
I've tried spitting out the values for the second item:
console.log("NULL ", item.id === null);
console.log("EMPTY ", item.id.trim().length === 0);and results are
NULL false EMPTY false
so I'm wondering if there's something strange about the id value.
Please consider the following:
var myFruits = ['Banana', 'Apple', 'Strawberry'];// SOME CODING// SOME CODINGmyFruits = undefined; // Is this better?myFruits = null; // or is this better?
Further question, what is the distinction between the two? Is there any cases where only null is used or undefined is used? Thanks.
Hi, all, I often do stuff like this in my code, to check for a variable being not null and not undefined.
// check if value is not null and not undefined
if (value) {
...
}However, I'm now thinking this can leads to bugs, because of 0, "", false and NaN also being falsy.
What is a better way to check a variable is not null and not undefined? I could use this I think, wondering if there is something shorter than this:
if (typeof value !== 'undefined' || value !== null) {
...
}we had an argue about this on our team, I wonder what approach should we consider? what is the better?
We have a user interface like this:
interface User {
name:string;
family?:string;
age:number;family name is optional, so our backend developer sends us this json data for those users that didnt filled the family:
{name: "john",
family:"",
age:18
}and in another object's case they sends null for the optional props...
We have been confused with this not having a solid convention from the backend team! what approach is the better? I think the right way is just removing optional property from the json data instead of setting it to null or "" empty string, I mean just dont add that!
My company uses files that are essentially merged XML files into one. I wrote a pretty basic parser and node object that contains the tag name, text, and child node objects. Recently I ran into an error where the file couldn't be found, and my function that searches for child nodes returned null (as it should). But it caused a runtime error, so I'm trying to figure out the best way to address issue. Should I return an empty object so that the code doesn't crash, or should I continue returning null and wrap it in a try/catch?
let u;
let n = null;
let e = '';
console.log(`u: ${u}`) // undefined
console.log(`n: ${n}`) // null
console.log(`n: ${typeof n}`) // Object type
console.log(`e: ${e}`) //
// console.log('x: ' + x) //Reference error
e = 44;
console.log(`e: ${e}`)
u = 44;
console.log(`u: ${u}`)
n = 44;
console.log(`u: ${u}`)Why does this have to be so confusing compared to other languages? T-SQL either has an empty value or null.
What would be the purpose of using these in a real world scenario and what is really the difference between undefined vs the reference error of not defined?
I get that you get a reference error because it wasnt "technically defined" inside a let x but why can't javascript dynamically make up for this and why does it use pretty much the same language of undefined for the variables of x and u?
So I'm usually more of a server side developer, but lately I've been working with more of the client code at work. I understand what undefined and null are in JavaScript, but I find myself always checking for both of them. In fact, when checking if a String property exists, I end up writing this:
if(value !== undefined && value !== null && value !== '')
I figure there is a better way than this, and it's probably because I'm not 100% clear of when to check for what. So if someone could help fill me in here on the rules of when to check for undefined vs null, that would be great.
TL;DR: Use value != null. It checks for both null and undefined in one step.
In my mind, there are different levels of checking whether something exists:
0) 'property' in object - Returns true if the property exists at all, even if it's undefined or null.
-
object.property !== undefined- Returns true if the property exists and is not undefined. Null values still pass. -
object.property != null- Return true if the property exists and is not undefined or null. Empty strings and 0's still pass. -
!!object.property- Returns true if the property exists and is "truthy", so even 0 and empty strings are considered false.
From my experience, level 2 is usually the sweet spot. Oftentimes, things like empty strings or 0 will be valid values, so level 3 is too strict. On the other hand, levels 0 and 1 are usually too loose (you don't want nulls or undefineds in your program). Notice that level 1 uses strict equality (!==), while level 2 uses loose equality (!=).
I would just say
if (value) {
// do stuff
}
because
'' || false
// false
null || false
// false
undefined || false
//false
Edit:
Based on this statement
I end up writing this: if(value !== undefined && value !== null && value !== '')
I initially assumed that what OP was really looking for was a better way to ask "is there a value?", but...
if someone could help fill me in here on the rules of when to check for undefined vs null, that would be great.
If you're looking to see if something is "truthy":
if (foo.bar) {
alert(foo.bar)
}
This won't alert if value is '', 0, false, null, or undefined
If you want to make sure something is a String so you can use string methods:
if (typeof foo.bar === 'string') {
alert(foo.bar.charAt(0))
}
This won't alert unless value is of type 'string'.
So.. "when to check for undefined vs null"? I would just say, whenever you know that you specifically need to check for them. If you know that you want to do something different when a value is null vs when a value is undefined, then you can check for the difference. But if you're just looking for "truthy" then you don't need to.
You can just check if the variable has a truthy value or not. That means
if (value) {
// do something..
}
will evaluate to true if value is not:
- null
- undefined
- NaN
- empty string ("")
- 0
- false
The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.
Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance
if (typeof foo !== 'undefined') {
// foo could get resolved and it's defined
}
If you can be sure that a variable is declared at least, you should directly check if it has a truthy value like shown above.
This question has two interpretations:
Check if the variable has a value
Check if the variable has a truthy valueThe following answers both.
In JavaScript, a value could be nullish or not nullish, and a value could be falsy or truthy.
Nullish values are a proper subset of falsy values:
โญโ nullish โโโโโโโฎ โญโ not nullish โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โโโโโโโโโโโโโฌโโโโโโโฌโโโโโโโโฌโโโโฌโโโโโฌโโโโโโฌโโโโโโโฌโโโโฌโโโโโโโโโโฌโโโโโโ
โ undefined โ null โ false โ 0 โ "" โ ... โ true โ 1 โ "hello" โ ... โ
โโโโโโโโโโโโโดโโโโโโโดโโโโโโโโดโโโโดโโโโโดโโโโโโดโโโโโโโดโโโโดโโโโโโโโโโดโโโโโโ
โฐโ falsy โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ โฐโ truthy โโโโโโโโโโโโโโโโฏ
Check if value is nullish (undefined or null)
Use one of the following depending on your coding style:
if (value == null) { /* value is nullish */ }
if (value === undefined || value === null) { /* value is nullish */ }
if (value == undefined) { /* value is nullish */ }
if ((value ?? null) === null) { /* value is nullish */ }
Notes:
- The
==operator works because it has a special case for null vs undefined comparison - The
===operator is more readable (opinion based), eqeqeq friendly and allows checking for undefined and null separately - The first and third examples work identically, however the third one is rarely seen in production code
- The fourth example uses nullish coalescing operator to change nullish values to
nullfor straight forward comparison
Check if value is not nullish
if (value != null) { /* value is not nullish, although it could be falsy */ }
if (value !== undefined && value !== null) { /* value is not nullish, although it could be falsy */ }
if (value != undefined) { /* value is not nullish, although it could be falsy */ }
if ((value ?? null) !== null) { /* value is not nullish, although it could be falsy */ }
Check if value is falsy
Use the ! operator:
if (!value) { /* value is falsy */ }
Check if value is truthy
if (value) { /* value is truthy */ }
Data validation
The nullish, falsy and truthy checks cannot be used for data validation on their own. For example, 0 (falsy) is valid age of a person and -1 (truthy) is not. Additional logic needs to be added on case-by-case basis. Some examples:
/*
* check if value is greater than/equal to 0
* note that we cannot use truthy check here because 0 must be allowed
*/
[null, -1, 0, 1].forEach(num => {
if (num != null && num >= 0) {
console.log("%o is not nullish and greater than/equal to 0", num);
} else {
console.log("%o is bad", num);
}
});
/*
* check if value is not empty-or-whitespace string
*/
[null, "", " ", "hello"].forEach(str => {
if (str && /\S/.test(str)) {
console.log("%o is truthy and has non-whitespace characters", str);
} else {
console.log("%o is bad", str);
}
});
/*
* check if value is not an empty array
* check for truthy before checking the length property
*/
[null, [], [1]].forEach(arr => {
if (arr && arr.length) {
console.log("%o is truthy and has one or more items", arr);
} else {
console.log("%o is bad", arr);
}
});
/*
* check if value is not an empty array
* using optional chaining operator to make sure that the value is not nullish
*/
[null, [], [1]].forEach(arr => {
if (arr?.length) {
console.log("%o is not nullish and has one or more items", arr);
} else {
console.log("%o is bad", arr);
}
});
In programming, truthiness or falsiness is that quality of those boolean expressions which don't resolve to an actual boolean value, but which nevertheless get interpreted as a boolean result.
In the case of C, any expression that evaluates to zero is interpreted to be false. In Javascript, the expression value in
if(value) {
}
will evaluate to true if value is not:
null
undefined
NaN
empty string ("")
0
false
See Also
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
The set of "truthy" and "falsey" values in JavaScript comes from the ToBoolean abstract operation defined in the ECMAScript spec, which is used when coercing a value to a boolean:
+--------------------------------------------------------------------------+
| Argument Type | Result |
|---------------+----------------------------------------------------------|
| Undefined | false |
|---------------+----------------------------------------------------------|
| Null | false |
|---------------+----------------------------------------------------------|
| Boolean | The result equals the input argument (no conversion). |
|---------------+----------------------------------------------------------|
| Number | The result is false if the argument is +0, โ0, or NaN; |
| | otherwise the result is true. |
|---------------+----------------------------------------------------------|
| String | The result is false if the argument is the empty String |
| | (its length is zero); otherwise the result is true. |
|---------------+----------------------------------------------------------|
| Object | true |
+--------------------------------------------------------------------------+
From this table, we can see that null and undefined are both coerced to false in a boolean context. However, your fields.length === 0 does not map generally onto a false value. If fields.length is a string, then it will be treated as false (because a zero-length string is false), but if it is an object (including an array) it will coerce to true.
If fields should be a string, then !fields is a sufficient predicate. If fields is an array, your best check might be:
if (!fields || fields.length === 0)
in my project, an object will take properties and values based on fetched data, if that's not empty something will be done.
so I guess this solution to my problem isn't a javascript way of slowing a problem. why?
I wrongly assumed that (as name suggest) _.isEmpty checks if variable is somehow empty, like undefined, null, empty string, array etc. But I just noticed that _.isEmpty(123) will return true, same as _.isEmpty(true) or _.isEmpty(false).
Documentation explains why:
A value is considered empty unless it is an arguments object, array, string, or jQuery-like collection with a length greater than 0 or an object with own enumerable properties.
Hi everyone, hope you're doing well!
I'm working on an Angular project and I have doubt about the response of an API send me.
To simplify, I receive a simple object like this:
{ a: 1, b: 2 }
As I expected a "c" inside this object, I got an undefined error.
So I asked the BE guy to send me the "c" value, even if it hasnt a value, send me as a null, so:
{ a: 1, b: 2, c: null }
I prefer this way because I don't have to wonder if the property doesn't exist inside the object, but rather have it ALWAYS, even tho it's null or another value.
Also helps me defining the interface, so I can say that a property is a number, for example, or null.
Also, I dont have weird situation where I have receive an array of this objects and some have the "c" property and other dont.
Has this approach any downside?
Thanks for your time :)
-
Undefined: The variable exists, but it has not yet been give a value, and thus it has a default value of undefined.
-
Null: The variable exists only as a reference. It does not yield any value.
Follow-up: Why is it useful to distinguish between null and undefined in javascript?
This does not completely cover all cases.
Undefined doesn't necessarily mean that a variable exists but hasn't been given a value yet. It's also possible to explicitly give a variable the value of "undefined", and it is sometimes returned when trying to look up an object member that doesn't exist. E.g. when looking up myObj.thisDoesntExist.
Variables that are set to null do return a value: the value being null.
They need to both be taken into account because they behave slightly differently. For example, if you have a function with default arguments, the default argument will be used if you pass undefined (or no argument at all) - but if you pass null, then your null will be used.
Not... exactly.
undefined means that either the value of the variable has not yet been defined, OR you've explicitly given the variable the value of undefined.
null is essentially an empty value that's separate from more generic (specific?) empty values, like empty string or zero or empty array. It's the equivalent of saying "this box (variable) that can hold a value currently is empty".
Finally, not defined (not really a value, but worth mentioning) is a special error-case when you try to access a variable before initializing it. For example, if you load an empty page and type in the console console.log(derp), you'll get a message that says "Uncaught ReferenceError: derp is not defined". This final value is a little strange, since it's almost the same as undefined, but won't allow you to access the variable in any format; It doesn't exist yet.
typeof null === 'object'; // true
The rationale I've heard is that it's too late to fix this one becaus an update to a null type would break a lot of old programs.
Ok, so why don't we allow this as a default, but then add the null type if a version check indicates ES2020 or later? I think that could be implement with a top of file statement similar to strict mode.
Only answer I can think of is that everyone is used to it, so it isn't a priority.
There's no isEmpty() method, you have to check for the type and the length:
if (typeof test === 'string' && test.length === 0){
...
The type check is needed in order to avoid runtime errors when test is undefined or null.
Ignoring whitespace strings, you could use this to check for null, empty and undefined:
var obj = {};
(!!obj.str) // Returns false
obj.str = "";
(!!obj.str) // Returns false
obj.str = null;
(!!obj.str) // Returns false
It is concise and it works for undefined properties, although it's not the most readable.