What does an if (number) return? - javascript

I seem to be having a hard time understanding what this does to my code?
const $counters = $('.js-item-counter')
if($counters.length)
{
}
What would this if statement return?
I can tell that the value is 1, but does this make sense?
I am trying to fix some frontend issues, and ran into something like this..

In Javascript, 0 is a falsey value. Anything other than 0 is considered true.
So what your code is doing is, it is making sure that the $counters is present in the DOM because if it were, it would give the length of > 0.
.length property tells you how many elements of the given selector are present in the DOM. If it is 0, then the element isn't present. If it is more than 0, then the element is present and you can act upon it as you wish.

The if statement will return true or false based on the condition.
If $counters.length > 0, it will return true and if block will be executed. Otherwise, it will return false and block won't be executed.

It returns true if the number inside the if statement is greater than or equal to 1 and false if it is 0.

It's a simple test to see if any elements of that class exist. Using length of a jQuery object is the most common jQuery approach to count matches in the collection
If it is anything other than zero it is truthy and zero is falsy
There used to be a size() method but that was deprecated and if you read in it's docs it tells you to use length instead

if the target element is stand for integer that having initial value of 1, then you should do this way
if($counters > 1)
{
//note length is only for checking of element existance
}

length coerced to true for any length other than 0 and false for 0:
console.log(
!!0,
!!1,
!!10
);

Related

Javascript. Give value to variable depending on parameter value

I have been given a Javascript code, and there is a sentence I cannot fully understand:
var isFaculty = (paramArray[0] == "yes"),
isFaculty variable is used afterthat in a equation, where more variables are involved. While the latter are defined along the code, the former is supposed to be defined (i.e. numerical value) by that sentence, as it depends on a parameterArray that the user should introduce (the parameter array is of size 3, anyway). For cell [0], paramArray can have two values, namely "yes" or "no".
I am wondering a possibility, but any help is welcome.
Thanks in advance,
/Jorge.
(paramArray[0] == "yes")
This is like a mini if statement that returns either true or false.
isFaculty is a boolean variable that captures that result.
Once the true or false is caught it can be used as a numeric 1 or 0 that even though is not recommended but could be multiplied by a number to turn it into a 0 if it's false or leave it unchanged if it's true
thanks for your help. The point is that isFaculty variable is involved in a formula as follows:
var xExample = 1/(1+Math.exp(-(-2 + 4*city - 0.11*gender + 0.6*isFaculty + 0.2*city*gender - 0.424885*city*isFaculty - 0.3*citygenderisFaculty)));
consequently, I understand that isFaculty gets value 1 or 0 depending on being true or false?
== is a comparator that will return a boolean value, so the code you have will assign true or false to isFaculty
The var name isXxxx would suggest to me that its value would be boolean.
So what you have is basically:
var isFaculty - for the variable isFaculty
= - assign the value of the following expression
paramArray[0] - take the first value from the array paramArray
== - check if it matches in content but not necessarily type with
"yes" - the string value that you are looking for to assign true
Implicitly this also means that if the content of paramArray[0] does not match with the content of the string value "yes" then the value of isFaculty will be false.
This could be used as a 'flag' later on by using false as 0 and true as 1.

Javascript regex matching on a time

I want to see if the string I have is in the form of HH:MM:SS.
Here is what I have so far:
d = '00:01:01'
d.match(/\d{2}:\d{2}:\d{2}/)
["00:01:02"]
Is there a way to just get a True/False, instead of an array?
Use .test method of Regexp object.
/\d{2}:\d{2}:\d{2}/.test(d)
// true
Perhaps, you can use regex.test(str) but it's also possible using match because on success, match returns an array which is a truthy value and on failure, match returns null which is a falsy value. Check this to understand truthy and falsy.
So, if you use
if(d.match(/\d{2}:\d{2}:\d{2}/)) {
// true
}
else {
// false
}
This will work, check this fiddle as an example and this answer as well (about !!), I've used !! in my example, so you may have doubts.

Undefined error in reading the property of object

Please help to solve the undefined error coming in my console while running the below code
Please see this JSbin also http://jsbin.com/ONOwujA/1/edit
data = [
{key:"home",value:"hk1"},
{key:"home",value:"hk2"},
{key:"home",value:"hk3"},
{key:"home",value:"hk4"},
{key:"product",value:"pk1"},
{key:"product",value:"pk2"},
{key:"product",value:"pk3"},
{key:"product",value:"pk4"},
{key:"service",value:"sk1"},
{key:"service",value:"sk2"},
{key:"service",value:"sk3"},
{key:"service",value:"sk4"}
];
myFilteredKey=[];
for(i=0;i<=data.length;i++){
if(myFilteredKey.indexOf(data[i].key)!=-1){
myFilteredKey.push(data[i].key);
console.log(data[i].key);
}
}
Use i < data.length. If the length is 3, the maximum index is 2.
Another problem with your code is that no element will be added to myFilteredKey. Since the array is already empty, no element will satisfy the condition myFilteredKey.indexOf(data[i].key)!=-1. Maybe you want to use === -1 instead, i.e. check whether the element is not in the array rather than whether it's in the array.

Javascript for loop new condition

plz check the code below:
for(i=0; i-DIL; i++)//see the condition here i-DIL .Is this correct?
{
}
is the second condition above in for loop correct?if so ,what does that mean?
actual code is:
javascript:R=0;
x1=.1; y1=.05;
x2=.25; y2=.24;
x3=1.6; y3=.24;
x4=300; y4=200;
x5=300; y5=200;
DI=document.getElementsByTagName("img");
DIL=DI.length;
function A(){for(i=0; i-DIL; i++)//see the condition here i-DIL .Is this correct?
{
DIS=DI[ i ].style;
DIS.position='absolute';
DIS.left=(Math.sin(R*x1+i*x2+x3)*x4+x5)+"px";
DIS.top=(Math.cos(R*y1+i*y2+y3)*y4+y5)+"px"}
R++
}
setInterval('A()',5); void(0);
Also can anyone help me describing the reason for placing void(0) at the end of the script?
And U can see that repeatedly image position is set over and over .How can i overcome that
Whether or not it's "correct" depends on what exactly you want the for loop to do. However, it is valid code, and hinges on the fact that 0 in JavaScript is "falsey", while other numbers are "truthy".
Essentially, when i and DIL are equal, i - DIL equals 0, which for the purposes of the for loop condition is evaluated as false, and it stops iterating. Given that DIL is the length of a collection, it's an interesting (but technically valid) method of iterating over the entire collection.
It's equivalent to (though I'd say less readable than):
for(i=0; i < DIL; i++)
it means execute code below till i-DIL != 0. ie here in your code it will work till i reaches DIL.
A for loops usually takes:
for(variable definition; condition; increment) {}
So, you need a condition. However, because Javascripts has loose content types, you don't have to use a comparison for it to be true or false.
10 - 1 // = 9 equals true
10 - 9 // = 1 equals true
10 - 10 // = 0 equals false
"legit string" // equals true
NULL // equals false
However, I do suggest to make an actual comparison just to avoid nasty browsers to break your condition.
for(var i = 0; i - DIL > 0; i++) {}

How to know that a particular element is present or not?

How to know that a particular input type is present or not in a div?
If I use
$("#inputId").val()
And there is no element present on this, then js gives an error.
So how could I know that the input element named inputId is present or not?
Reply me ASAP
You could check if
$('#inputId').length > 0
i.e. if the current selector matched any elements.
But if $('#inputId').length == 0 then $('#inputId').val() will be undefined. This is different from the scenario where the input exists, because val() would always yield a string, that is or isn't null.
Now, you would produce an error only if you're trying to do stuff with the value, that may or may not be undefined. For instance, the following would not work if #inputId does not exist in the DOM:
if($('#inputId').val().length > 0) { ... }
... since you'd be trying to access undefined.length. However, you could still do
if(!!$('#inputId').val()) {
// this code will only be executed if #inputId exists, and has a value that
// is not an empty string
}
If you're writing form validation, it might be more useful to do
if($('#inputId').val() !== '') {
// this code will be executed if #inputId has a value, or if it does not
// exist in the DOM at all
}
The former condition checks that the result of .val() resolves to true, which is not the case for an empty string or for undefined. (It is also not the case for null, NaN, false or 0, but .val() will never yield any of those results)
The latter checks that the result of .val() is not exactly an empty string, which is true for an actual value, as well as for undefined.
You can use the length property, which will tell you the number of elements in the current selector.
if ($("#inputId").length > 0)
{
// code that depends on inputId being present can go in here
}
if ($("#inputId").length) { }
No need to be verbose, checking whether length === 0 or greater than 0: length value itself is automatically casted as a boolean inside an if statement
Without jQuery:
var input = document.getElementById('inputId');
if (input) {
// the input exists
alert(input.value);
} else {
// the input doesn't exist
alert('Ooops! An input with id "inputId" doesn\'t exist.');
}

Categories

Resources