i've got the following situation.
In my script I have extracted all strings, that are publicated to the webpage, into an object like this.
var strings = {
one: "One",
two: "Two",
three: "Three",
}
Please don't ask why I want to do this, it's just a test case.
Now I want to push one of these strings, for example, into an alert(). this would look like this:
alert(strings.one);
So far so good, but I want to check if strings or strings.one exist and when it doesn't return an empty string.
What is a slick way to do this, without using the classic if(strings.one == undefined)?
EDIT
I've found a solution according to your answers and comments.
alert((window.strings) ? strings.one || "nope" : "nope");
This catches all cases i want to prevent:
I forgot to declare strings
strings.one doesn't exists
I hope this fits to "slick way"?!
You can use ||, which returns the first operand if it's truthy and the second otherwise:
alert(strings.one || "");
This will also catch other falsy values, but that probably won't be an issue for you.
You can use the ternary operator or u can do this if you want and empty string if string.one does not exist.
alert(string.one || '');
Related
let's say that we have an javascript object like below:
let obj = {name: 'firstName'};
which is a better way to test whether a property exists on an object and is equal to something:
1)
if (obj.address === 'someAddress')
or
2)
if (!!obj.address && obj.address === 'someAddress')
Can someone explain which is better/safer and why?
You asked "safer" and "better". "Better" is subjective as long as you don't define what qualities you're looking for, so I'll ignore that part.
Accessing a property that doesn't exist is valid in JavaScript, and simply returns undefined. So the second way is equivalent to:
const address = obj.address
if (!!address && address === 'someAddress') {
...
}
Now you can see that that's plain silly, because the second condition implies the first. In other words, there is no way that address === 'someAddress' can be true and !!address can be false, so there is no need to do the first check at all.
So the second approach is not safer than the first. Both have the same observable effect.
Nitpicker's corner: if you were checking for some falsy value like 0 or "" instead of the truthy string 'someAddress', then the second approach would not even work, because both conditions can never be true at the same time.
Also, if address is a property with an evil getter that may return a different value each time it's called, all bets are off. The first version could actually be safer because it only gets the value once, but presumably the value would be used inside the if block so the code is still broken.
1 is shorter :D and it works :D
Better is:
if (obj?.address === 'someAddress')
it checks both conditions
I would like to compare two strings and decide if they are not equal. I have the code below, but it seems that it is not returning what I want, is this correct?
if ((current.request.requested_for != reviewer) && (current.request.requested_for != approver)) {
return 'Yes';
}
return 'No';
}
Here reviewer and approver, are some strings that I have declared in lines prior to the if conditions. Basically, my question here is to know if I should use != to check if 2 strings are not equal.
Thanks
Assuming that you have strings in the variables reviewer, approver and the object current.request.requested_for, you can just compare two strings with === which compares type and value. If you compare with ==, you are just comparing the value, there are more reasons about == is returning true for '2' == 2, visit this.
So, your code could be more declarative and simpler
(...)
const SEARCH = [reviewer, approver];
return SEARCH.includes(current.request.requested_for)
(...)
If your are not using latest javascript do not worry, you could achieve the same with an array declaration and the indexOf() method. They are the former way of the code.
I wonder if there is a nice way to get the descriptions of a Symbol.
For example,
var s = Symbol(5);
The default implementation of the toString will simply print
Symbol(5)
I would like to find a way to extract the actual description i.e. 5
Symbol.description returns description of the symbol.
Simply do s.description in your case.
There is no neat way to do this. However, if you have registered a symbol in the global registry, you can use Symbol.keyFor():
var s = Symbol.for(5);
console.log(Symbol.keyFor(s));
String(symbol).slice(7, -1) || null
This works because String(symbol) explicitly coerce the symbol into a string e.g. Symbol('test') gets coerced into "Symbol(test)".
Doing a splicing on the from 7 to -1 does a splicing between the two brackets, thus capturing the description test
Note: that this may not work for object descriptions (e.g. Symbol({test})) as objects gets coerced into "[object Object]"
symbol-description package on npm
Returns description of provided symbol:
const symDesc = require('symbol-description')
symDesc(Symbol('foo')) // foo
It was published by me just now after reading this answer here.
when comparing string to see if it is empty, is there any difference between:
if($string==NULL){
//do work
}
and
if($string==""){
/do work
}
Just wondering beacuse I want to know which one is more effective in detecting blank input.
You're kind of asking several vaguely-related questions here. PHP and JavaScript aren't the same language, and you're referencing different operators in the question title and body. In any event:
PHP:
'' == null true
'' === null false
JavaScript:
'' == null false
'' === null false
You might want to consider these tests for general "did I get something in this string variable":
PHP:
if(!empty($string)) {
// do work
}
JavaScript:
if($string) {
// do work
}
Yes, there is a difference. Checking if $string==Null will actually check to see if the variable has been initialized at all, and $string=="" looks to see that the string actually exists, but that it just holds a 0-length string
To test in PHP:
<?php echo var_dump("" === NULL); ?>
To test in JavaScript:
console.log("" === null)
Both produce false, so you can't do that in either language.
Even if it worked, it is not obvious what you mean by comparing with null; this isn't C where it's constantly used for missing values. If you're going to get a string as input, comparing to the empty string is more clear.
I`am using empty() function in PHP. It is not depends on type of the variable. However, when comparing with "==" (not "==="!), NULL becomes empty string ("") when comparing to string.
does “”===null?
No.
Behold the power of testing... for javascript anyway.
alert("" === null);
In JavaScript, the answer is no. An empty string does not equal null, though both are falsey values.
Check the manual, "" is not identical to null because the former is a string and the latter is null, and === checks for equal types as well as equal values.
Take a look at this: http://php.net/manual/en/language.operators.comparison.php
Is this the notation to use for Not Equal To in JS, in jquery code
!== OR !=
None of them work
Here is the code I am using
var val = $('#xxx').val();
if (val!='') {
alert("jello");
}
Thanks
Jean
Equality testing in JQuery works no different from "standard" JavaScript.
!= means "not equal to", but !== makes sure that both values have the same type as well. As an example, 1 == '1' is true but not 1 === '1', because the LHS value is a number and the RHS value is a string.
Given your example, we cannot really tell you a lot about what is going on. We need a real example.
.val() is used to retrieve or set values from input in forms mostly, is that what you want to do? If not maybe you mean using .text() or .html().
If that is indeed what you want to do maybe you have your selector wrong and its returning null to you, and null does not equal '', or maybe you actually have data there, like whitespaces. :)
May be you have whitespace in your #xxx node, that why both !== and != failing, you could try following to test non whitespace characters
var val = $('#xxx').val();
if (/\S/.test(val)){
alert('jello');
}
Note: I assume jQuery's .val() won't return null because of this line in jQuery source
return (elem.value || "").replace(/\r/g, "");
If not, you need to do like this
if (val && /\S/.test(val)){
alert('jello');
}
It's both, but the latter is strict on type, see here:
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators
It is working with jquery and normal java script.
You should check (alert/debug) your val variable for its value and null.
You should also check $('#xxx').length whether you are getting elements or not otherwise you will get, hence your if condition will be false.