How can I test whether a variable has a value in JavaScript? - javascript

I want to test whether a JavaScript variable has a value.
var splitarr = mystring.split( " " );
aparam = splitarr [0]
anotherparam = splitarr [1]
//.... etc
However the string might not have enough entries so later I want to test it.
if ( anotherparm /* contains a value */ )
How do I do this?

if (typeof anotherparm == "undefined")

An empty string evaluates to FALSE in JavaScript so you can just do:
if (anotherparam) {...}

In general it's sort of a gray area... what do you mean by "has a value"? The values null and undefined are legitimate values you can assign to a variable...
The String function split() always returns an array so use the length property of the result to figure out which indices are present. Indices out of range will have the value undefined.
But technically (outside the context of String.split()) you could do this:
js>z = ['a','b','c',undefined,null,1,2,3]
a,b,c,,,1,2,3
js>typeof z[3]
undefined
js>z[3] === undefined
true
js>z[3] === null
false
js>typeof z[4]
object
js>z[4] === undefined
false
js>z[4] === null
true

you can check the number of charactors in a string by:
var string_length = anotherparm.length;

One trick is to use the or operator to define a value if the variable does not exist. Don't use this if you're looking for boolean "true" or "false"
var splitarr = mystring.split( " " );
aparam = splitarr [0]||''
anotherparam = splitarr [1]||''
This prevents throwing an error if the variable doesn't exist and allows you to set it to a default value, or whatever you choose.

So many answers above, and you would know how to check for value of variable so I won't repeat it.
But, the logic that you are trying to write, may be better written with different approach, i.e. by rather looking at the length of the split array than assigning to a variable the array's content and then checking.
i.e. if(splitarr.length < 2) then obviously anotherparam is surely 'not containing value'.
So, instead of doing,
if(anotherparam /* contains a value */ )
{
//dostuff
}
you can do,
if(splitarr.length >= 2)
{
//dostuff
}

Related

!! used in node ? will this check undefined in node and array length and empty Object in what all cases can this be used for

i came across this code recently in node. but i cant find a good understanding on where to use this.
I want data to be not undefined, not 0 and not empty array.
if(!!data){
do something ...
}
It proves working fine for empty array value = 0, etc can someone explain in detail about this.
if ( typeof data !== 'undefined'){ do something }
if ( data !== null ){ do something }
I have tried to implement this and it failed when i send an undefined variable.
the feature can be used to full extend if it can be shared to everyone.
this is just pure js. Double NOT operator "!!". So the first ! coerce the value to a boolean and inverse it, then the second ! reverses it to the original boolean equivalent. So basically converts nonboolean to boolean
Array length will not be considered. Empty arrays will be avoided. Empty String will be checked. Any value 0 will be considered false and other integers will be considered true. Lets look at all these examples and figure out the usage.
let a = 0 ;
console.log(!!a) //false
a = "";
console.log(!!a) //false
a = " ";
console.log(!!a) // true since a has a space value
console.log(!!a.trim())//false
a = undefined
console.log(!!a) //false
a= {}
console.log(a) // true Use Object.keys(a).length > 0 to check empty object or
// use _.isEmpty(a) for checking empty object
a = { name:"Rahul"}
console.log(a) // true
a = []
console.log(a) // true Use array.length > 0 to check empty array
a = [1,2,3]
console.log(a) // true

How to use a loop to test if a variable exists

I'm trying to construct the variable name and then test if it exists using a while loop but I think I'm creating it when I test for it so keep getting 'true' and the loop goes infinite.
var1 = "value1"
var2 = "value2"
var3 = "value3"
var i = 3
Logger.log(('value'+i)==true)
var i = 4
Logger.log(('value'+i)==true)
/*
var i = 1;
while (("value"+i) != null) {
Logger.log("value"+i)
i++;
}
*/
When I build the loop I want value4 to not exist and stop the loop but it doesn't. Because I've just created it's string I suppose, so how should I be formatting the test? First question here and I have searched but the 'construction' part seems to complicate things. Thanks.
Firstly, I'll clarify a misconception,
I want value4 to not exist and stop the loop but it doesn't. Because I've just created it's string I suppose
'value'+i doesn't create a variable. It represents the string 'value3'. In JS, strings are truthy, so you logger will print true.
Now to the question, how to check if variable exists.
The cleanest way of doing this would be to use a dictionary represented by a simple js object.
let definedVariablesDictionary = {};
definedVariablesDictionary.var1 = 'value1';
let isVarialbeDefined = variable => definedVariablesDictionary[variable] !== undefined;
console.log(isVarialbeDefined('var1')); // true
console.log(isVarialbeDefined('var2')); // false
Variable names are not strings, so your attempt to construct a string that matches the name of a variable won't evaluate that string as code.
If you want to do this, you should create an object with properties that store values, like a variable would. Then you can pass a string of the property name into the object, to retrieve the value of the property.
Also, you shouldn't check to see if the value is null as null is a valid value that a variable or property could have been set to. That check wouldn't tell you explicitly if the property was defined or not, it would only tell you if the value of the property was null. Instead, checking for the existence of the property can be done by just passing the property name into the object. If it exists, then the result is "truthy" and your if statement would proceed into the true branch. If the property doesn't exist, the return value is falsy and you'd proceed into the false branch.
let myObject = {
value1:"test1",
value2:"test2",
value3:"test3"
};
for(var i = 0; i < Object.keys(myObject).length +1; i++){
// Property names can be passed as strings using bracket notation
if(myObject["value" + i]){
console.log("value" + i + " exists and has a value of: " + myObject["value" + i]);
} else {
console.log("value" + i + " is not defined");
}
}

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 an array item is set in JS

I've got an array
var assoc_pagine = new Array();
assoc_pagine["home"]=0;
assoc_pagine["about"]=1;
assoc_pagine["work"]=2;
I tried
if (assoc_pagine[var] != "undefined") {
but it doesn't seem to work
I'm using jquery, I don't know if it can help
Thanks
Use the in keyword to test if a attribute is defined in a object
if (assoc_var in assoc_pagine)
OR
if ("home" in assoc_pagine)
There are quite a few issues here.
Firstly, is var supposed to a variable has the value "home", "work" or "about"? Or did you mean to inspect actual property called "var"?
If var is supposed to be a variable that has a string value, please note that var is a reserved word in JavaScript and you will need to use another name, such as assoc_var.
var assoc_var = "home";
assoc_pagine[assoc_var] // equals 0 in your example
If you meant to inspect the property called "var", then you simple need to put it inside of quotes.
assoc_pagine["var"]
Then, undefined is not the same as "undefined". You will need typeof to get the string representation of the objects type.
This is a breakdown of all the steps.
var assoc_var = "home";
var value = assoc_pagine[assoc_var]; // 0
var typeofValue = typeof value; // "number"
So to fix your problem
if (typeof assoc_pagine[assoc_var] != "undefined")
update: As other answers have indicated, using a array is not the best sollution for this problem. Consider using a Object instead.
var assoc_pagine = new Object();
assoc_pagine["home"]=0;
assoc_pagine["about"]=1;
assoc_pagine["work"]=2;
var assoc_pagine = new Array();
assoc_pagine["home"]=0;
Don't use an Array for this. Arrays are for numerically-indexed lists. Just use a plain Object ({}).
What you are thinking of with the 'undefined' string is probably this:
if (typeof assoc_pagine[key]!=='undefined')
This is (more or less) the same as saying
if (assoc_pagine[key]!==undefined)
However, either way this is a bit ugly. You're dereferencing a key that may not exist (which would be an error in any more sensible language), and relying on JavaScript's weird hack of giving you the special undefined value for non-existent properties.
This also doesn't quite tell you if the property really wasn't there, or if it was there but explicitly set to the undefined value.
This is a more explicit, readable and IMO all-round better approach:
if (key in assoc_pagine)
var is a statement... so it's a reserved word... So just call it another way.
And that's a better way of doing it (=== is better than ==)
if(typeof array[name] !== 'undefined') {
alert("Has var");
} else {
alert("Doesn't have var");
}
This is not an Array.
Better declare it like this:
var assoc_pagine = {};
assoc_pagine["home"]=0;
assoc_pagine["about"]=1;
assoc_pagine["work"]=2;
or
var assoc_pagine = {
home:0,
about:1,
work:2
};
To check if an object contains some label you simply do something like this:
if('work' in assoc_pagine){
// do your thing
};
This worked for me
if (assoc_pagine[var] != undefined) {
instead this
if (assoc_pagine[var] != "undefined") {
TLDR; The best I can come up with is this: (Depending on your use case, there are a number of ways to optimize this function.)
function arrayIndexExists(array, index){
if ( typeof index !== 'number' && index === parseInt(index).toString()) {
index = parseInt(index);
} else {
return false;//to avoid checking typeof again
}
return typeof index === 'number' && index % 1===0 && index >= 0 && array.hasOwnKey(index);
}
The other answer's examples get close and will work for some (probably most) purposes, but are technically quite incorrect for reasons I explain below.
Javascript arrays only use 'numerical' keys. When you set an "associative key" on an array, you are actually setting a property on that array object, not an element of that array. For example, this means that the "associative key" will not be iterated over when using Array.forEach() and will not be included when calculating Array.length. (The exception for this is strings like '0' will resolve to an element of the array, but strings like ' 0' won't.)
Additionally, checking array element or object property that doesn't exist does evaluate as undefined, but that doesn't actually tell you that the array element or object property hasn't been set yet. For example, undefined is also the result you get by calling a function that doesn't terminate with a return statement. This could lead to some strange errors and difficulty debugging code.
This can be confusing, but can be explored very easily using your browser's javascript console. (I used chrome, each comment indicates the evaluated value of the line before it.);
var foo = new Array();
foo;
//[]
foo.length;
//0
foo['bar'] = 'bar';
//"bar"
foo;
//[]
foo.length;
//0
foo.bar;
//"bar"
This shows that associative keys are not used to access elements in the array, but for properties of the object.
foo[0] = 0;
//0
foo;
//[0]
foo.length;
//1
foo[2] = undefined
//undefined
typeof foo[2]
//"undefined"
foo.length
//3
This shows that checking typeof doesn't allow you to see if an element has been set.
var foo = new Array();
//undefined
foo;
//[]
foo[0] = 0;
//0
foo['0']
//0
foo[' 0']
//undefined
This shows the exception I mentioned above and why you can't just use parseInt();
If you want to use associative arrays, you are better off using simple objects as other answers have recommended.
if (assoc_pagine.indexOf('home') > -1) {
// we have home element in the assoc_pagine array
}
Mozilla indexOf
function isset(key){
ret = false;
array_example.forEach(function(entry) {
if( entry == key ){
ret = true;
}
});
return ret;
}
alert( isset("key_search") );
The most effective way:
if (array.indexOf(element) > -1) {
alert('Bingooo')
}
W3Schools

Categories

Resources