This question already has answers here:
Why does isNaN(" ") (string with spaces) equal false?
(25 answers)
Closed 8 years ago.
I'm trying to write a simple test for the input of a function to determine if all of the inputs are numbers or not.
function numbers(){
for (var i = 0; i < arguments.length; i++) {
if (isNaN(arguments[i])) return false;
}
return true;
}
However, when I pass in a list of numbers as characters (eg. numbers("1", "2")) I get true instead of the expected false.
isNaN implicitly coerces the argument to Number, and then checks whether this coerced value is NaN.
See http://es5.github.io/#x15.1.2.4
That is, isNaN(foo) is equivalent to isNaN(Number(foo))
Code fix:
if (typeof arguments[i] !== 'number' || isNaN(arguments[i])) return false;
The second part of the condition is because typeof NaN === 'number'.
Your function might be a bit more readable in functional style, using ES5's Array#every method:
//returns whether all arguments are of type Number and not NaN
function numbers() {
return [].every.call(arguments, function(arg) {
return typeof arg === 'number' && !isNaN(arg);
});
}
isNan() will attempt to cast it to a number, and then check. I would use this instead
if(!isNaN(parseFloat(arguments[i])) && isFinite(arguments[i])){
return false;
}
Alternatively, if you're using jQuery, you could use its built-in $.isNumeric() function
Related
This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 2 years ago.
I currently have this JavaScript function lying around within my code:
getCoverPhoto(item) {
if (item != undefined && item.gallery != undefined && item.gallery[0] != undefined)
return item.gallery[0].media;
return "";
}
How can I simplify the if condition above? And if it can't be simplified, can it be written in a better way?
For example with ternary operator:
getCoverPhoto(item) {
return item && item.gallery && item.gallery[0] ? item.gallery[0].media : '';
}
Read further in the documentation:
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as a shortcut for the if statement.
Or with ES6+:
const getCoverPhoto = item => item && item.gallery && item.gallery[0] ? item.gallery[0].media : '';
I hope that helps!
Here is a more simplified version of your code.
getCoverPhoto(item) {
if (item && item.gallery && item.gallery[0])
return item.gallery[0].media;
return "";
}
Use destructing to reduce the conditions. Below code should work for you.
getCoverPhoto(item) {
const { gallery = [] }= item; // this is destructing with default value assignment.
return item.gallery[0] ? item.gallery[0].media : '';
}
This question already has answers here:
How to determine equality for two JavaScript objects?
(82 answers)
Closed 8 years ago.
I was looking at the JavaScript console in Chrome and noticed something strange, even though they appear the same, obj and JSON.parse(JSON.stringify(obj)) are not the same. Why is that?
var obj = {test:'this is a test', another: {omg:'ay dios mio', check:true}};
console.log(obj, JSON.parse(JSON.stringify(obj)));
console.log(obj == JSON.parse(JSON.stringify(obj)));
They look identical but return false when you check equality. Why is that?
They're not equal for the same reason this returns false:
({omg:'ay dios mio', check:true}) == ({omg:'ay dios mio', check:true})
You're not comparing the values inside the object, but the object references. They'll be different.
The objects are testing for REFERENCES.
While primitives are testing for VALUE.
Because the obj does not reference the parsed object in memory. So these are 2 different declarations. If you do this:
var a = [ 10 ],
b = [ 10 ];
Then there are 2 instances of arrays with the same values, but that doesn't make them the same array. So a != b, even though 10 == 10. You can increase the value of a[0] to 15, but that doesn't change the value of b[0] to 15.
Therefore, if you want to compare objects, you have to loop through them and check if the values of the objects are the same.
A function to compare (borrowed from jQuery object equality )
$.fn.equals = function(compareTo) {
if (!compareTo || this.length != compareTo.length) {
return false;
}
for (var i = 0; i < this.length; ++i) {
if (this[i] !== compareTo[i]) {
return false;
}
}
return true;
};
This question already has answers here:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
(48 answers)
Closed 9 years ago.
The code is used to verify an image or cell selection. My question is
What is !== used for in the following function:
function checkSelected() {
var cellList,
selectedCell,
imgList,
selectedImg,
i
cellList = document.getElementById("imgTable")
cellList = cellList.getElementsByTagName("td")
imgList = document.getElementById("b_list")
imgList = imgList.getElementsByTagName("img")
if (cellList[0].style.border.indexOf("7px outset") !== -1) { selectedCell = cellList[0] }
if (selectedCell === undefined || selectedImg === undefined) { return }
selectedCell.style.backgroundImage = "url(" + selectedImg.src + ")"
selectedCell.firstChild.style.visibility = "hidden"
selectedCell.style.border = "1px solid"
selectedImg.style.border = "1px solid"
}
!== is a stricter inequality that does not perform any type coercion on the operands, compared to !=, which does perform type coercion.
So !== will return true if the operands are not equal and/or not of the same type.
In contrast != returns true if the operands are equal. If the operands are not of the same type, JavaScript will try to convert both operands into a form suitable for comparison. If the operands are objects, then JavaScript will compare their references (memory addresses). This is best demonstrated as follows:
"3" != 3; // returns false because JavaScript will perform
// type coercion and compare the values
"3" !== 3; // returns true because the first operand is a
// string whereas the second is an integer. Since
// they are of different types, they are not equal.
For more information, take a look at Comparison Operators on MDN.
It means "not strictly equal to", as opposed to != which means "not equal to".
There are two ways to check for equality: == and ===, which are "equals" and "strictly equals" respectively. To see the exact difference, check out this table.
!= and !== are simply the corresponding negations of those operations. So for example a !== b is the same as !(a === b)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript === vs == : Does it matter which “equal” operator I use?
In some JavaScript if statements I've seen the use of === as opposed to the standard ==.
What is the difference between these? and should I be using either one of them over the other?
e.g.
if (variable == 'string') {
return;
}
compared to:
if (variable === 'string') {
return;
}
=== also checks to be equal by type
For instance 1=="1" is true but 1==="1" is false
The === is a strict comparison (also checks type), whereas the == does a more relaxed comparison.
For instance:
var a = 'test';
if (a == true) {
// this will be true
}
if ( a === true) {
// this will not be true
}
Another example:
var b = '0';
if ( b == 0){
// this will be true
}
if ( b === 0 ){
// this will not be true
}
In particular it is very important when comparing falsy values. In Javascript all the following will be treated as false with relaxed comparison:
* false
* null
* undefined
* empty string ''
* number 0
* NaN
This question already has answers here:
JavaScript check if variable exists (is defined/initialized)
(32 answers)
Closed 6 years ago.
I am trying to test to see whether a Javascript variable is undefined.
You will see that I am not expecting the value of predQuery[preId] to be 'undefined' if I don't first get an alert saying "its unbelievable". But I often do, so I am guessing that my statement
predQuery[preId]=='undefined')
is not matching the undefined elements properly.
if((predQuery.length < preId) || (predQuery[preId]=="") || (predQuery[preId]=='undefined')){
alert("its unbelievable");
alert(predQuery[preId]);
queryPreds[variables] = preId;
queryObjs[variables] = objId;
predQuery[preId] = variables;
}
else {
alert(predQuery[preId]);
var predIndex = predQuery[preId];
queryPreds[predIndex] = preId;
queryObjs[predIndex] = objId;
}
I can add more code if needed.
array[index] == 'undefined' compares the value of the array index to the string "undefined".
You're probably looking for typeof array[index] == 'undefined', which compares the type.
You are checking it the array index contains a string "undefined", you should either use the typeof operator:
typeof predQuery[preId] == 'undefined'
Or use the undefined global property:
predQuery[preId] === undefined
The first way is safer, because the undefined global property is writable, and it can be changed to any other value.
predQuery[preId]=='undefined'
You're testing against the string 'undefined'; you've confused this test with the typeof test which would return a string. You probably mean to be testing against the special value undefined:
predQuery[preId]===undefined
Note the strict-equality operator to avoid the generally-unwanted match null==undefined.
However there are two ways you can get an undefined value: either preId isn't a member of predQuery, or it is a member but has a value set to the special undefined value. Often, you only want to check whether it's present or not; in that case the in operator is more appropriate:
!(preId in predQuery)
There are more (many) ways to Rome:
//=>considering predQuery[preId] is undefined:
predQuery[preId] === undefined; //=> true
undefined === predQuery[preId] //=> true
predQuery[preId] || 'it\'s unbelievable!' //=> it's unbelievable
var isdef = predQuery[preId] ? predQuery[preId] : null //=> isdef = null
cheers!
Check for
if (predQuery[preId] === undefined)
Use the strict equal to operator. See comparison operators
try: typeof(predQuery[preId])=='undefined'
or more generally: typeof(yourArray[yourIndex])=='undefined'
You're comparing "undefined" to undefined, which returns false =)
This code works very well
function isUndefined(array, index) {
return ((String(array[index]) == "undefined") ? "Yes" : "No");
}