How do you implement a guard clause in JavaScript? - javascript

I want to guard my functions against null-ish values and only continue if there is "defined" value.
After looking around the solutions suggested to double equal to undefined: if (something == undefined). The problem with this solution is that you can declare an undefined variable.
So my current solution is to check for null if(something == null) which implicetly checks for undefined. And if I want to catch addionalty falsy values I check if(something).
See tests here: http://jsfiddle.net/AV47T/2/
Now am I missing something here?
Matthias

The standard JS guard is:
if (!x) {
// throw error
}
!x will catch any undefined, null, false, 0, or empty string.
If you want to check if a value is valid, then you can do this:
if (Boolean(x)) {
// great success
}
In this piece, the block is executed if x is anything but undefined, null, false, 0, or empty string.

The only safe way that I know of to guard against really undefined variables (meaning having variable name that were never defined anywhere) is check the typeof:
if (typeof _someUndefinedVarName == "undefined") {
alert("undefined");
return;
}
Anything else (including if (!_someUndefinedVarName)) will fail.
Basic example: http://jsfiddle.net/yahavbr/Cg23P/
Remove the first block and you'll get:
_someUndefinedVarName is not defined

Only recently discovered using '&&' as a guard operator in JS. No more If statements!
var data = {
person: {
age: 22,
name: null
}
};
var name = data.person.name && doSomethingWithName(data.person.name);

Ternary to the rescue !
(i) =>
i == 0 ? 1 :
i == 1 ? 2 :
i == 2 ? 3 :
null

Related

Why is (null==undefined) true in JavaScript? [duplicate]

How do I check a variable if it's null or undefined and what is the difference between the null and undefined?
What is the difference between == and === (it's hard to search Google for "===" )?
How do I check a variable if it's null or undefined...
Is the variable null:
if (a === null)
// or
if (a == null) // but see note below
...but note the latter will also be true if a is undefined.
Is it undefined:
if (typeof a === "undefined")
// or
if (a === undefined)
// or
if (a == undefined) // but see note below
...but again, note that the last one is vague; it will also be true if a is null.
Now, despite the above, the usual way to check for those is to use the fact that they're falsey:
if (!a) {
// `a` is falsey, which includes `undefined` and `null`
// (and `""`, and `0`, and `NaN`, and [of course] `false`)
}
This is defined by ToBoolean in the spec.
...and what is the difference between the null and undefined?
They're both values usually used to indicate the absence of something. undefined is the more generic one, used as the default value of variables until they're assigned some other value, as the value of function arguments that weren't provided when the function was called, and as the value you get when you ask an object for a property it doesn't have. But it can also be explicitly used in all of those situations. (There's a difference between an object not having a property, and having the property with the value undefined; there's a difference between calling a function with the value undefined for an argument, and leaving that argument off entirely.)
null is slightly more specific than undefined: It's a blank object reference. JavaScript is loosely typed, of course, but not all of the things JavaScript interacts with are loosely typed. If an API like the DOM in browsers needs an object reference that's blank, we use null, not undefined. And similarly, the DOM's getElementById operation returns an object reference — either a valid one (if it found the DOM element), or null (if it didn't).
Interestingly (or not), they're their own types. Which is to say, null is the only value in the Null type, and undefined is the only value in the Undefined type.
What is the difference between "==" and "==="
The only difference between them is that == will do type coercion to try to get the values to match, and === won't. So for instance "1" == 1 is true, because "1" coerces to 1. But "1" === 1 is false, because the types don't match. ("1" !== 1 is true.) The first (real) step of === is "Are the types of the operands the same?" and if the answer is "no", the result is false. If the types are the same, it does exactly what == does.
Type coercion uses quite complex rules and can have surprising results (for instance, "" == 0 is true).
More in the spec:
Abstract Equality Comparison (==, also called "loose" equality)
Strict Equality Comparison (===)
The difference is subtle.
In JavaScript an undefined variable is a variable that as never been declared, or never assigned a value. Let's say you declare var a; for instance, then a will be undefined, because it was never assigned any value.
But if you then assign a = null; then a will now be null. In JavaScript null is an object (try typeof null in a JavaScript console if you don't believe me), which means that null is a value (in fact even undefined is a value).
Example:
var a;
typeof a; # => "undefined"
a = null;
typeof null; # => "object"
This can prove useful in function arguments. You may want to have a default value, but consider null to be acceptable. In which case you may do:
function doSomething(first, second, optional) {
if (typeof optional === "undefined") {
optional = "three";
}
// do something
}
If you omit the optional parameter doSomething(1, 2) thenoptional will be the "three" string but if you pass doSomething(1, 2, null) then optional will be null.
As for the equal == and strictly equal === comparators, the first one is weakly type, while strictly equal also checks for the type of values. That means that 0 == "0" will return true; while 0 === "0" will return false, because a number is not a string.
You may use those operators to check between undefined an null. For example:
null === null # => true
undefined === undefined # => true
undefined === null # => false
undefined == null # => true
The last case is interesting, because it allows you to check if a variable is either undefined or null and nothing else:
function test(val) {
return val == null;
}
test(null); # => true
test(undefined); # => true
The spec is the place to go for full answers to these questions. Here's a summary:
For a variable x, you can:
check whether it's null by direct comparison using ===. Example: x === null
check whether it's undefined by either of two basic methods: direct comparison with undefined or typeof. For various reasons, I prefer typeof x === "undefined".
check whether it's one of null and undefined by using == and relying on the slightly arcane type coercion rules that mean x == null does exactly what you want.
The basic difference between == and === is that if the operands are of different types, === will always return false while == will convert one or both operands into the same type using rules that lead to some slightly unintuitive behaviour. If the operands are of the same type (e.g. both are strings, such as in the typeof comparison above), == and === will behave exactly the same.
More reading:
Angus Croll's Truth, Equality and JavaScript
Andrea Giammarchi's JavaScript Coercion Demystified
comp.lang.javascript FAQs: JavaScript Type-Conversion
How do I check a variable if it's null or undefined
just check if a variable has a valid value like this :
if(variable)
it will return true if variable does't contain :
null
undefined
0
false
"" (an empty string)
NaN
undefined
It means the variable is not yet intialized .
Example :
var x;
if(x){ //you can check like this
//code.
}
equals(==)
It only check value is equals not datatype .
Example :
var x = true;
var y = new Boolean(true);
x == y ; //returns true
Because it checks only value .
Strict Equals(===)
Checks the value and datatype should be same .
Example :
var x = true;
var y = new Boolean(true);
x===y; //returns false.
Because it checks the datatype x is a primitive type and y is a boolean object .
Ad 1. null is not an identifier for a property of the global object, like undefined can be
let x; // undefined
let y=null; // null
let z=3; // has value
// 'w' // is undeclared
if(!x) console.log('x is null or undefined');
if(!y) console.log('y is null or undefined');
if(!z) console.log('z is null or undefined');
try { if(w) 0 } catch(e) { console.log('w is undeclared') }
// typeof not throw exception for undelared variabels
if(typeof w === 'undefined') console.log('w is undefined');
Ad 2. The === check values and types. The == dont require same types and made implicit conversion before comparison (using .valueOf() and .toString()). Here you have all (src):
if
== (its negation !=)
=== (its negation !==)
If your (logical) check is for a negation (!) and you want to capture both JS null and undefined (as different Browsers will give you different results) you would use the less restrictive comparison:
e.g.:
var ItemID = Item.get_id();
if (ItemID != null)
{
//do stuff
}
This will capture both null and undefined
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null, blank, undefined, zero you can test
if(!(!(data)))
{
//If data has valid value
alert("data "+data);
}
else
{
//If data has null, blank, undefined, zero etc.
alert("data is "+data);
}
}

What is Simpler Way to Write Code That Sums Up Length of Strings including nulls and undefineds in JavaScript

I want to add some defensive coding to the following check. I have 3 strings and I want to know if any of them have anything in them (for my purposes, null or undefined means they do not have anything in them).
if (twitterUrl.length + facebookUrl.length + linkedInUrl.length > 0) {
This works, but feels like very bulky. I use TypeScript and not sure if there is anything there that can help me with this.
if ((twitterUrl ? twitterUrl.length : 0) +
(facebookUrl ? facebookUrl.length : 0) +
(linkedInUrl ? linkedInUrl.length : 0) > 0) {
You can use the fact that empty strings are falsy¹. If you know they'll be strings or null or undefined and you don't need to worry about strings with just whitespace in them (" " is truthy¹), then:
if (twitterUrl || facebookUrl || linkedInUrl) {
If you need to worry about trimming, then a helper function is probably in order:
function present(s) {
return s && (typeof s !== "string" || s.trim());
}
and
if (present(twitterUrl) || present(facebookUrl) || present(linkedInUrl)) {
or
if ([twitterUrl, facebookUrl, linkedInUrl].some(present)) {
¹ falsy and truthy: When you use a value in a condition (like an if), JavaScript will implicitly coerce the value to a boolean. A value that coerces to false is falsy; one that coerces to true is truthy. The falsy values are "", null, undefined, 0, NaN, and of course, false. All other values (including " ") are truthy.
You could define a function as the following one:
function getLength(s){
if(typeof s !== "string") return 0;
return s.length;
}
and then use it like below:
if (getLength(twitterUrl) > 0 || getLenght(facebookUrr) > 0 || getLength(linkedInUrl){
// code
}
Essentially, getLength check if the value you pass when you call the function is a string and if so it returns its length. Otherwise, it returns 0. So in order to achieve that you want, (I want to know if any of them have anything in them), you have to check one by one the strings you have, if the first string has a length greater than zero, there isn't any need to continue the check for the other two strings. Otherwise you call the function on the second string and so on and so forth.
Try like this, normal if statement also works
const socialLinks = [twitterUrl, facebookUrl, linkedInUrl];
const hasSomething = socialLinks.some(social => social);
Here is falsy value like null, undefined, '' and etc., https://developer.mozilla.org/en-US/docs/Glossary/Falsy
if social are empty string('') or null or undefined then it's return false. We omitted return keyword because arrow function has implicit return behaviour.
This is a solution using some(), which checks whether at least one element in the array passes the test implemented by the provided function.
var twitterUrl, facebookUrl, linkedInUrl;
linkedInUrl = 'nonEmpty';
result = [twitterUrl, facebookUrl, linkedInUrl].some(arrVal => arrVal);
console.log(result);

How to check if a value is not null and not empty string in JS

Is there any check if a value is not null and not empty string in Javascript? I'm using the following one:
var data; //get its value from db
if(data != null && data != '') {
// do something
}
But I'm wondering if there is another better solution. Thanks.
If you truly want to confirm that a variable is not null and not an empty string specifically, you would write:
if(data !== null && data !== '') {
// do something
}
Notice that I changed your code to check for type equality (!==|===).
If, however you just want to make sure, that a code will run only for "reasonable" values, then you can, as others have stated already, write:
if (data) {
// do something
}
Since, in javascript, both null values, and empty strings, equals to false (i.e. null == false).
The difference between those 2 parts of code is that, for the first one, every value that is not specifically null or an empty string, will enter the if. But, on the second one, every true-ish value will enter the if: false, 0, null, undefined and empty strings, would not.
Instead of using
if(data !== null && data !== '' && data!==undefined) {
// do something
}
You can use below simple code
if(Boolean(value)){
// do something
}
Values that are intuitively “empty”, like 0, an empty string, null, undefined, and NaN, become false
Other values become true
Both null and an empty string are falsy values in JS. Therefore,
if (data) { ... }
is completely sufficient.
A note on the side though: I would avoid having a variable in my code that could manifest in different types. If the data will eventually be a string, then I would initially define my variable with an empty string, so you can do this:
if (data !== '') { ... }
without the null (or any weird stuff like data = "0") getting in the way.
if (data?.trim().length > 0) {
//use data
}
the ?. optional chaining operator will short-circuit and return undefined if data is nullish (null or undefined) which will evaluate to false in the if expression.
I often test for truthy value and also for empty spaces in the string:
if(!(!data || data.trim().length === 0)) {
// do something here
}
If you have a string consisting of one or more empty spaces it will evaluate to true.
Simple solution to check if string is undefined or null or "":-
const value = null;
if(!value) {
console.log('value is either null, undefined or empty string');
}
Both null and empty could be validated as follows:
<script>
function getName(){
var myname = document.getElementById("Name").value;
if(myname != '' && myname != null){
alert("My name is "+myname);
}else{
alert("Please Enter Your Name");
}
}
try it----------
function myFun(){
var inputVal=document.getElementById("inputId").value;
if(inputVal){
document.getElementById("result").innerHTML="<span style='color:green'>The value is "+inputVal+'</span>';
}
else{
document.getElementById("result").innerHTML="<span style='color:red'>Something error happen! the input May be empty.</span>";
}
}
<input type="text" id="inputId">
<input type="button" onclick="myFun()" value="View Result">
<h1 id="result"></h1>
I got so fed up with checking for null and empty strings specifically, that I now usually just write and call a small function to do it for me.
/**
* Test if the given value equals null or the empty string.
*
* #param {string} value
**/
const isEmpty = (value) => value === null || value === '';
// Test:
isEmpty(''); // true
isEmpty(null); // true
isEmpty(1); // false
isEmpty(0); // false
isEmpty(undefined); // false
When we code empty in essence could mean any one of the following given the circumstances;
0 as in number value
0.0 as in float value
'0' as in string value
'0.0' as in string value
null as in Null value, as per chance it could also capture undefined or it may not
undefined as in undefined value
false as in false truthy value, as per chance 0 also as truthy but what if we want to capture false as it is
'' empty sting value with no white space or tab
' ' string with white space or tab only
In real life situation as OP stated we may wish to test them all or at times we may only wish to test for limited set of conditions.
Generally if(!a){return true;} serves its purpose most of the time however it will not cover wider set of conditions.
Another hack that has made its round is return (!value || value == undefined || value == "" || value.length == 0);
But what if we need control on whole process?
There is no simple whiplash solution in native core JavaScript it has to be adopted. Considering we drop support for legacy IE11 (to be honest even windows has so should we) below solution born out of frustration works in all modern browsers;
function empty (a,b=[])
{if(!Array.isArray(b)) return;
var conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
if(conditions.includes(a)|| (typeof a === 'string' && conditions.includes(a.toString().trim())))
{return true;};
return false;};`
Logic behind the solution is function has two parameters a and b, a is value we need to check, b is a array with set conditions we need to exclude from predefined conditions as listed above. Default value of b is set to an empty array [].
First run of function is to check if b is an array or not, if not then early exit the function.
next step is to compute array difference from [null,'0','0.0',false,undefined,''] and from array b. if b is an empty array predefined conditions will stand else it will remove matching values.
conditions = [predefined set] - [to be excluded set]
filter function does exactly that make use of it.
Now that we have conditions in array set all we need to do is check if value is in conditions array.
includes function does exactly that no need to write nasty loops of your own let JS engine do the heavy lifting.
Gotcha
if we are to convert a into string for comparison then 0 and 0.0 would run fine however Null and Undefined would through error blocking whole script. We need edge case solution. Below simple || covers the edge case if first condition is not satisfied. Running another early check through include makes early exit if not met.
if(conditions.includes(a)|| (['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim())))
trim() function will cover for wider white spaces and tabs only value and will only come into play in edge case scenario.
Play ground
function empty (a,b=[]){
if(!Array.isArray(b)) return;
conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
if(conditions.includes(a)||
(['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim()))){
return true;
}
return false;
}
console.log('1 '+empty());
console.log('2 '+empty(''));
console.log('3 '+empty(' '));
console.log('4 '+empty(0));
console.log('5 '+empty('0'));
console.log('6 '+empty(0.0));
console.log('7 '+empty('0.0'));
console.log('8 '+empty(false));
console.log('9 '+empty(null));
console.log('10 '+empty(null,[null]));
console.log('11 dont check 0 as number '+empty(0,['0']));
console.log('12 dont check 0 as string '+empty('0',['0']));
console.log('13 as number for false as value'+empty(false,[false]));
Lets make it complex - what if our value to compare is array its self and can be as deeply nested it can be. what if we are to check if any value in array is empty, it can be an edge business case.
function empty (a,b=[]){
if(!Array.isArray(b)) return;
conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
if(Array.isArray(a) && a.length > 0){
for (i = 0; i < a.length; i++) { if (empty(a[i],b))return true;}
}
if(conditions.includes(a)||
(['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim()))){
return true;
}
return false;
}
console.log('checking for all values '+empty([1,[0]]));
console.log('excluding for 0 from condition '+empty([1,[0]], ['0']));
it simple and wider use case function that I have adopted in my framework;
Gives control over as to what exactly is the definition of empty in a given situation
Gives control over to redefine conditions of empty
Can compare for almost for every thing from string, number, float, truthy, null, undefined and deep arrays
Solution is drawn keeping in mind the resuability and flexibility. All other answers are suited in case if simple one or two cases are to be dealt with. However, there is always a case when definition of empty changes while coding above snippets make work flawlessly in that case.
function validateAttrs(arg1, arg2, arg3,arg4){
var args = Object.values(arguments);
return (args.filter(x=> x===null || !x)).length<=0
}
console.log(validateAttrs('1',2, 3, 4));
console.log(validateAttrs('1',2, 3, null));
console.log(validateAttrs('1',undefined, 3, 4));
console.log(validateAttrs('1',2, '', 4));
console.log(validateAttrs('1',2, 3, null));

typeError is null when variable defined as null

code have to do 3 things
get json output of user.
get user status on-line or off-line (if data.stream === null) user is off-line
create user with nickname and status.
push that user into array. lastData array
1st problem i get TypeError data.sream is null even if i define null as in examples. some people say`ed that i can just ignore that, but i want to ask professionals
-- Pritam Banerjee answer this question thank you
2nd problem is that user is not pushed into array. only same user is pushed few times in array.
Code is here Fiddle
sorry if question is not good but i dont know where else to ask.
var mynull = null;
if (typeof mynull === null) { // have to be if(mynull == null)
// my code
}
else
//my code
// building prototype name & status
function userStatus(name, status) {
this.name = name;
this.status = status;
} // prototype
var showUserList = ["OgamingSC2", "habathcx", "RobotCaleb", "noobs2ninjas"]
var lastData = []; // where to push users
for (var i = 0; i < showUserList.length; i++) {
var user = showUserList[i]; // get username from array
var useris = showUserList[i] // --//--
useris = new userStatus(user, 'Chanel is Offline');
lastData.push(useris);
console.log(lastData[i].name + '' + lastData[i].status);
}
Some things you must know about the typeof operator:
It always returns a string. Never compare the returned value to a non-string using ===.
It's horribly broken because it doesn't always not return the Type of the value.
For example, typeof null returns the string 'object'.
The proper way to compare mynull with null is mynull === null.
You can also use mynull == null to detect if it's either null or undefined.
null is an important primitive type in JavaScript. It is essentially a special value that indicates that there is no value! Initializing your variables to null when you don't know yet what their actual value will be later on is a very good best-practice in JavaScript, because if you wind up getting an error (like the one you are getting now (TypeError data.sream is null), it tells you that you never actually supplied a useful value to the variable.
When it comes to testing for null, you have a few options, but something that is important to remember is that JavaScript is loosely typed and values can and do change their type simply based on the way you use them. null is what's known as a "falsey" value, that is, if you convert it to a Boolean, it converts to false. Other "Falsey" values include: 0, undefined, "" and false. Just about every non-empty, non-zero, non-undefined value is "truthy" and will convert to true if forced into a Boolean.
So, if you really just want to know if your variable is still null or does it have meaningful data, you can leverage this loose typing like the following because the value of myNull will be converted to a Boolean so that the if statement can be evaluated.
Ask yourself if you really care if your variable has the exact value of null or do you just need to know if your variable has data that you can use? An explicit test for null may not really even be needed.
var myNull = null;
var myNull2 = null;
// We're only going to give one of the variables a value
myNull2 = "something";
if(myNull){
// myNull is NOT null
console.log("myNull is NOT null and has a value of: " + myNull);
} else {
// myNull is null
console.log("myNull IS null and has a value of: " + myNull);
}
if(myNull2){
// myNull2 is NOT null
console.log("myNull2 is NOT null and has a value of: " + myNull2);
} else {
// myNul2l is null
console.log("myNul2l IS null and has a value of: " + myNull2);
}
This will not work as:
typeof null === 'object';
So it will always return an object and hence your code will not work.
Rather you can try:
if (myNull == null){
// your code here.
}
Also can try as suggested by Scott, but the if else would be the other way round:
if (myNull){}

Check if variable is not undefined because it's === true or has a value assigned

Sometimes I see that it is common to do this on javascript in order to check if a variable is not undefined because it has a value assigned:
if(variable) {
/* not undefined, do something */
}
However, I was asking to myself how can I check if variable is not undefined in the following situation:
Live Demo: http://jsfiddle.net/Vp8tN/1/
$(function() {
var person = create('John');
var isMarried = person.isMarried;
console.log('isMarried: ' + isMarried);
if(isMarried) {
console.log('Do something!');
}
});
function create(name) {
var person = {};
person.name = name;
person.isMarried = getRandom();
return person;
};
function getRandom() {
var arr = [true, 'No', undefined];
var rand = arr[Math.floor(Math.random() * arr.length)];
return rand;
};
In this case isMarried variable can be true, 'No', or undefined.
So, my questions are...
1) How can I check if isMarried variable is NOT undefined because it is === true (equals true) or because it has a value assigned? (this last one happens when isMarried === 'No').
2) Is it possible to check this without using an extra if statement or condition?
3) What's the better approach for checking this?
In both cases described above (at number 1) I got inside the if statement. Check the output from browser console:
isMarried: true
Do something!
isMarried: undefined
isMarried: No
Do something!
PS. I am using jQuery just for testing, this question is NOT related to that framework! Thanks.
You have three options for a single equality test:
Strict Equality. if (person.isMarried === true) or if (person.isMarried !== undefined). Check if a variable is explicitly equal to something (with no type conversions allowed).
Loose equality. if (person.isMarried == true) with type conversions allowed.
Any truthy/falsey value. if (person.isMarried). This will be satified if person.isMarried contains ANY truthy value. Even "no" would be a truthy value.
If you're trying to tell the difference between "no", false and undefined, you will likely have to use more than one comparison as those are all separate values of separate types.
If you only want to know if the variable has any value (e.g. is not undefined), then you can use the strict equality check and compare to the actual undefined value:
if (person.isMarried !== undefined) {
// there is some value in person.isMarried though it could be anything
// other than the undefined value
}
isMarried !== undefined
Yes, see #1.
1
See this post.
https://stackoverflow.com/a/3390426/1313439
EDIT: For reasons that jfriend00 pointed out in the comments to his answer, isMarried !== undefined is probably preferable to typeof isMarried !== 'undefined'.

Categories

Resources