How to check empty in variable in Google Apps Script [duplicate] - javascript

This question already has answers here:
How do I check for an empty/undefined/null string in JavaScript?
(52 answers)
Google Spreadheets Scripts: check if cell is empty
(3 answers)
Closed 1 year ago.
I have a variable that can be either empty, number or text. I like to find only empty one. But the following codes using .length returned null for 0 number, though it returned 1 for "0" string . .toString.length even didn't work. Any suggestion? Thank you!
function test() {
// criteria can be either empty, number or text. How can I check whether the critieria is empty?
// In the example below, critiera_2.length returned null, not 1.
criteria_1 = "";
Logger.log(criteria_1.length);
criteria_2 = 0;
Logger.log(criteria_2.length);
criteria_3 = "0";
Logger.log(criteria_3.length);
criteria_4 = "X";
Logger.log(criteria_4.length);
criteria_1 = "";
Logger.log(criteria_1.toString.length);
criteria_2 = 0;
Logger.log(criteria_2.toString.length);
criteria_3 = "0";
Logger.log(criteria_3.toString.length);
criteria_4 = "X";
Logger.log(criteria_4.toString.length);
}

criteria_1 = "";
console.log(criteria_1.toString() == ''); // output: true
const test = x => console.log(x.toString()==='');
test(""); // true
test(0); // false
test("0"); // false
test("X"); // false
It's turned out that you don't even need toString() it could be just x===''

To check for an empty string, a simple approach would be to use === operator
if (criteria_1 === "") {
//...
}

Related

Access a variable based on other variable value in Javascript [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 4 months ago.
This post was edited and submitted for review 4 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I have a bunch of variables having boolean values. I wish to have another variable that stores the name of the boolean variable changed last. So, next time when a new boolean variable value is changed, I want to toggle the previous boolean variable.
Any idea/suggestion to achieve the above would be highly appreciated.
Eg. it would be something like this incorrect code-
isDemo1=false; isDemo2=false; isDemo3=true; isDemo4=false; isDemo5=false;
lastChangedBooleanVariable = this.isDemo3;
handleBooleanVaiables(currentChangedBooleanVariable: string)
{
// somehow toggle this.isDemo3 variable value
this.lastChangedBooleanVariable = currentChangedBooleanVariable;
// let's say currentChangedBooleanVariable = isDemo4
// somehow toggle this.isDemo4 value
}
Everytime that you need to do some weird code, rethink your approach, it will probably wrong.
You can instead use Arrays:
isDemo = [false, false, true, false, false];
lastChangedBooleanVariable = 3;
handleBooleanVaiables(currentChangedBooleanVariable: int) {
this.lastChangedBooleanVariable = currentChangedBooleanVariable;
isDemo[currentChangedBooleanVariable - 1] = !isDemo[currentChangedBooleanVariable - 1]
}
Sounds very much like what you're trying to do is functionally equivalent to:
let demo = 3;
Then set the value of this variable to any value from 1 to 5.
Instead of if (isDemo2), test if (demo == 2).
The "last changed variable" is always simply the current value demo holds, and that's probably obsolete information with this approach.
ES6 has a feature on Arrays called fill which can be pretty handy here. Essentially, you just set all the values to false before you activate a new version.
let demos = new Array(5).fill(false);
function activateDemo(demo) {
demos = new Array(5).fill(false);
demos[demo] = true;
}
activateDemo(4);
let demos = new Array(5).fill(false);
function activateDemo(demo) {
const humanIndex = demo > 0 ? demo - 1 : 0; // to make it into human counting form, if you want.
demos = new Array(5).fill(false);
demos[humanIndex] = true;
}
activateDemo(4);
console.log("4", demos);
activateDemo(3);
console.log("3", demos);
var keys = {
"isDemo1":false, "isDemo2":false, "isDemo3":false, "isDemo4":false, "isDemo5":false;
};
var lastChangedBooleanVariable: string = "isDemo3";
const nameOf = (f) => (f).toString().replace(/[ |\(\)=>]/g,'');
function getName(varName:string){
return varName.substring(
varName.indexOf(".") + 1,
varName.lastIndexOf(";")
);
}
function handleBooleanVaiables(currentChangedBooleanVariable: string)
{
console.log(keys[lastChangedBooleanVariable]);
keys[lastChangedBooleanVariable] = !keys[lastChangedBooleanVariable];
keys[currentChangedBooleanVariable] = ! keys[currentChangedBooleanVariable];
lastChangedBooleanVariable = currentChangedBooleanVariable;
// let's say currentChangedBooleanVariable = isDemo4
// somehow toggle this.isDemo4 value
}
function printValues(){
console.log(keys);
}
var varName = getName(nameOf(()=>keys.isDemo1));
handleBooleanVaiables(varName);
printValues();
varName = getName(nameOf(()=>keys.isDemo4));
handleBooleanVaiables(varName);
printValues();
here's fiddle: https://jsfiddle.net/hjv540tk/

I don't want the else part in tertiary operator [duplicate]

This question already has answers here:
Ternary operators in JavaScript without an "else"
(13 answers)
Closed 1 year ago.
function clear_error(id){
(document.getElementById(id) != undefined) ? (document.getElementById(id).innerHTML = "") : console.log('span is not created yet');
}
I have to check that a span element has been created/defined for my error or not, if it is created then remove the inner text for the new error if not then do nothing, as i have made an error function of it in the specified class.
A ternary isn't the best tool here. Typically the conditional operator (? :) is used when you want to evaluate a condition and obtain a new value based on whether the condition is true/false. You can could && to short-circuit:
function clear_error(id) {
const elem = document.getElementById(id); // store the element to avoid re-querying the DOM
elem && elem.innerHTML = "";
}
but that to me doesn't read very well, so a standard if-statement would work better in my opinion:
function clear_error(id){
const elem = document.getElementById(id); // store the element to avoid re-querying the DOM
if(elem) {
elem.innerHTML = "";
}
}
Just use null :
(document.getElementById('jj') != undefined) ? (document.getElementById(id).innerHTML = "") : null

Problem with string: "undefined", unable to check this case [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I'm getting coordinates via an API that works most of the time
(giving me a String with a double, example : "53.2") but sometimes i see in the javascript console that I receive 'undefined' instead of let's say 53.2.
I tried to check if what i receive is undefined but it doesn't work and I keep getting this type of error sometimes:
"java.lang.NumberFormatException: For input string: "undefined" "
Could you help me please? I'd like to know if I have to check with another condition, maybe null or something else..
EDIT: My main concern is more to know when i get undefined value in the Java servlet and less to make the Javascript work better. Thank you!
//JAVA CODE IN THE SERVLET
String fromlong = request.getParameter("fromlong"); //COORDINATES
String fromlat = request.getParameter("fromlat");
String tolong = request.getParameter("tolong");
String tolat = request.getParameter("tolat");
if(fromlat == "undefined") {
fromlat = "50.0";
}
if(fromlong == "undefined") {
fromlong = "50.0";
}
if(tolat == "undefined") {
tolat = "50.0";
}
if(fromlat == "undefined") {
tolong = "50.0";
}
//Then there is a function that uses these values
and that's the javascript code where i get the values with an api then send them with a hidden input (this works when the api sends me a correct value most of the time then i'd like to check if what i got in the servlet is correct before using it)
getCoordinates1(from);
function getCoordinates1(database){
$.ajax({
url: 'http://api.positionstack.com/v1/forward',
data: {
access_key: 'MYKEY',
query: database,
limit: 1
}
}).done(function(data) {
var mylatitude = data.data[0].latitude;
var mylongitude = data.data[0].longitude;
document.getElementById('fromlat').value = mylatitude;
document.getElementById('fromlong').value = mylongitude;
console.log(data.data[0].latitude);
console.log(data.data[0].longitude);
});
}
and at the end of the page i send this with an hidden input
<input type="hidden" id="fromlat" name="fromlat" value="" />
You have to compare strings with .equals()
You are comparing them with "==".
If you do like you did, you are comparing the object reference, not the actual value of the string.
Which evaluates as false every time since it is not the same object.
if (fromLat.equals("undefined")) { ...
Edit:
You also have a logical error in your code:
if (fromlat == "undefined") {
tolong = "50.0";
}
should be:
if (tolong.equals("undefined")) {
tolong = "50.0";
}

Json returns as undefined, replace undefined with text [duplicate]

This question already has answers here:
Javascript: use either a variable, or if it's undefined, a default string
(7 answers)
Closed 4 years ago.
first time dealing with json, so not really sure..
when a user online the api returns with
user example
live true
viewers 22
passwordProtected false
banned false
but when im offline "viewers" gets removed.
so data.viewers comes back as undefined, how can i change it to e.g offline?
script:
<script>
$.getJSON('https://example.com/api/example', function(data) {
var text = `${data.viewers}`
$(".mypanel").html(text);
});
</script>
You can use the hasOwnProperty function.
var text = "offline";
if(data.hasOwnProperty('viewers'){
text = data.viewers;
}
You could check for undefined like so:
var text = "offline";
if (data.length && data.viewers !== undefined) {
var text = data.viewers;
}
or with a ternary operator:
var text = (data.viewers !== undefined) ? data.viewers : "offline";
Ps. no need for the interpolation when saving a variable. ie `${data.viewers}`
This is used when adding variables to a string value like html.

How to determine whether some string is in the list or not [duplicate]

This question already has answers here:
How to find if an array contains a specific string in JavaScript/jQuery?
(7 answers)
Closed 4 years ago.
var name_list = ['Annie','John','Lyam','Mary']
var text_be_checked_1 = 'Annie'
do_some_stuff(name_list, text_be_checked_1) // true
var text_be_checked_2 = 'Ann'
do_some_stuff(name_list, text_be_checked_2) // false
var text_be_checked_3 = '1Annie'
do_some_stuff(name_list, text_be_checked_3) // true
var text_be_checked_4 = 'An2nie'
do_some_stuff(name_list, text_be_checked_4) // false
var text_be_checked_5 = 'Anni_John'
do_some_stuff(name_list, text_be_checked_5) // true
What I want is that determining whether text has full match with name in name_list like above.
I read this, but this is not exactly what I need.
How can I do this?
I don't care about where the solution came from. javascript or jQuery are all okay.
Would you solve this please?
EDIT:
Thank you everyone, There are many answers and I tested them.
But I thought that I have to add more explanation of my question.
You have to check this:
var name_list = ['Annie','John','Lyam','Mary']
var text_be_checked_3 = '1Annie'
do_some_stuff(name_list, text_be_checked_3) // true
As your answers, from here
Mango can return true, but 1Mango, Mango_to returns false.
This is point, What I want is that 1Mango and Mango_to are also return true.
If this explanation is not enough, please comment me.
function do_some_stuff(list, str) {
return list.indexOf(str) !== -1
}
It is really that simple.
Array.indexOf() returns -1 if the item you are checking is not in the array. So by comparing the returned value to -1, you get a true if the item is in the list, and a false if it is not in the list.
You can achieve it by simply doing:
if (name_list.includes(text_to_be_checked) ) {}
Take your time to check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
Hope it helps.
A functional approach:
name_list.filter(word => word == text_be_checked_1).length >= 1
name_list.some(name => name=== 'Mike') would return false
name_list.some(name => name=== 'Annie') would return true in your case.
The array method some returns true or false based on a condition. You can use it.
Check Below Code as per your need it works :
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
var name_list = ['Annie','John','Lyam','Mary'];
var output=inArray('Annie', name_list);
console.log(output);
This is what you're actually looking for i guess,
var name_list = ['Annie','John','Lyam','Mary']
var text_be_checked_1 = 'Annie'
if($.inArray(text_be_checked_1, name_list) !== -1){
console.log('value exist');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope this will helpful to you!
Greetings!

Categories

Resources