If else conditions in Javascript - javascript

I have topdatedata value as 222
I have these 3 conditions specified
if((topDateData<250)&&(topDateData>25))
{
alert('one');
}
else if((topDateData>300)&&(topDateData<300))
{
alert('Two');
}
else
{
alert('Three');
}
My questions is why is it getting the value as alert(3) and not alert(one)??

When explicitly setting the value to 222, I see 'one' get alerted: http://jsfiddle.net/Wvjfa/
You should debug your actual value ( alert(topDateData); if you like) and see if it really is what you think it is.
Beyond that, Matt Ball is right, your second condition is borked. Also lonesomeday and Kerry are right about your variable case not matching between your question and the posted code.

Javascript is case sensitive, is topdatedata = 222 or topDateData = 222?

it's much safer just to set one value - as you're second criteria looks dodgy
var topDateData = 222;
if(topDateData > 300)
{
alert('two');
}
else if(topDateData > 250)
{
alert('');
}
else if(topDateData > 25)
{
alert('One');
}
else
{
alert('Three');
}
start with the one that's hardest to satisfy (in this example the highest) and then work your way down. It's much easier to follow. Other than that it should work, as per the other comments on here

My guess is that you have a string.
var trueBool = '222' < '250'; //true
var falseBool = '222' > '25'; //false
To debug if topDateData is a String or not, do the following:
alert(topDateData + 1);//outputs '2221' if a string, and '223' if a number
Here's a fiddle showing the difference.
UPDATE:
I've tested alert(('222' < 250) && ('222' > 25)); and that outputs true. However, I'm not sure all JavaScript compilers will be smart enough to convert the string to a number first. You should run the same test and see if true is the output on your browser.

It looks like your topDateData variable contains a string value "222" instead of an integer.
You could try to cast to an integer this way:
topDateData = parseInt(topDateData);
...

Related

How to convert number to bool in JS?

I trying to convert number to boolean,
but my if condition always run the else block statements.
if ( !($(document).find($('.formSectionWrapper').length)) ) {
console.log('IF')
} else {
console.log('ElSE')
}
when length is 0 it runs else and when it is greater than 0 it run else block again!
What is my mistake?
Just change
if(!($(document).find($('.formSectionWrapper').length)))
to
if(!($(document).find($('.formSectionWrapper')).length))
Note the parenthesis.
In Javascript 0 is falsy and positive numbers are truithy
so you can just check on the number.
To answer your question:
Your logic looks wrong because of your ! you are inverting the logic which is likely confusing you.
According to jQuery Doc find, you find an element not the length.
Description: Get the descendants of each element in the current set of
matched elements, filtered by a selector, jQuery object, or element.
Then you apply the if...else statement on the length.
So here is how your code shall look like
const formSectionWrapper = $('.formSectionWrapper');
//const formSectionWrapper = $(document).find('.formSectionWrapper');
if ( !formSectionWrapper.length ) {
console.log('IF')
} else {
console.log('ElSE')
}

After Effects: Javascript - Undefined value used in the expression(Could be out of range array subscript)

I'm not a programmer by any means. I'm an animator trying to use JS expressions in After Effects. I'm getting an "Undefined value used in expression" error on line 1 where I define a variable.I already showed it to my friend on discord who is a cs major, and he had no clue what was wrong with it.
Here's just a paste of the code if you need it:
var count = 1;
if (framesToTime(time) % 12 == 0) {
count = count + 1
if (count % 2 == 0){
thisProperty = 95
} else {
thisProperty = 20
};
} ;
Ok I don't know why the hell this fixed it, but I changed the name of the variable from "count" to just "x" and it works now. Go figure
Try it.
var count = 1;
if (framesToTime(time) % 12 == 0) {
count = count + 1;
if (count % 2 == 0){
thisProperty = 95;
} else {
thisProperty = 20;
}
}
thisProperty;
In your code, thisProperty has become an ordinary variable. If you write its name at the end of the code, then its value will be assigned to the property.
In AE, if there is nothing inside an if statement or the if statement contains malformed/error code you will receive this error. Put a temp value inside the curly braces or something to process and ensure nothing inside will throw an error.
I also received this error with this:
pastTime = timeToFrames(time)-1;
curPos = transform.xPosition;
pastPos = transform.xPosition.valueAtTime(framesToTime(pastTime));
if (curPos-pastPos[0] != 0) {
// Here is the problem in my case. added a value here 99 to fix until finished testing.
}
else {
effect("Angle Control")("Angle")
}
if/else statements are strict
The syntax for if/else statements is strict in the JavaScript engine
and need to be written for standardized JavaScript.
https://helpx.adobe.com/after-effects/using/expression-language-reference.html*
I got this error because there was a missing semicolon.

Comparing two regex in Javascript and getting weird results

Can someone please explain this strange behavior in Javascript? When I do comparisons using the match() method I don't get the expected result.
var mat_1 = "wpawn";
var mat_2 = "wRook";
//compare both; do they have the same first letter?
alert(mat_1.match(/^\w/) + " seems equal to " + mat_2.match(/^\w/));
if (mat_1.match(/^\w/) === mat_2.match(/^\w/)) {
alert("They are really equal")
}
//another approach
if (mat_1[0] === mat_2[0]) {
alert("Yes! Equals")
}
match produces an array. You should really use an array comparison function, but for the sake of simple demonstration, try this - the first match value is selected and compared. All 3 alerts are triggered:
var mat_1 = "wpawn";
var mat_2 = "wRook";
//compare both; do they have the same first letter?
alert(mat_1.match(/^\w/)+" seems equal to "+mat_2.match(/^\w/));
if(mat_1.match(/^\w/)[0] === mat_2.match(/^\w/)[0]){alert("They are really equal")}
//another approach
if(mat_1[0] === mat_2[0]){alert("Yes! Equals")}
Match returns an array of matches:
String.prototype.match(pattern: Regex): Array<string>
Your first evaluation will always fail as you are comparing two arrays.
This is the correct way for what you are trying to achieve.
'myWord'.match(/^\w/)[0] == 'mIsTeRy'.match(/^\w/)[0]
Although if you wanna truly use the regex to check the first letter, I wouldn't recommend it. Too much overhead for something too trivial (just my two cents).
Have fun coding! :)
in the following lines of code you are checking the variables mat_1 and mat_2 for whether both the words starts with 'w', btw match() returns an array
if (mat_1.match(/^\w/) === mat_2.match(/^\w/)) {
alert("They are really equal")
}
you can try something like
if (["w"] === ["w"]) {
console.log("seems equal");
} else {
console.log("not equal");
}
for array comparison you can check this post
what you have to do here is
if (["w"][0] === ["w"][0]) { // match for the elements in the array
console.log("seems equal");
} else {
console.log("not equal");
}

javascript function not working as expected

I have the following code in an external javascript file. I am getting an error on this line below: guessNum = inGuess.parseInt();
firebug tells me the parseInt is not a function. I thought all things in js were basically objects (at least that is what I remember reading in W3School). I am sure this is something simple, I am just stuck. Any suggestions are welcome. Thanks
function inputNum()
{
/* initialize variables */
var inGuess = "";
var loopCt;
var guessResult = "";
var correctNum = 26;
var guessNum = 0;
for (loopCt=1;loopCt<11;loopCt++)
{
inGuess = prompt("Please enter your guess(enter -1 to exit) Do not press Enter","0");
if (inGuess == "-1") { break; }
if (inGuess==null || inGuess=="")
{
alert("Blanks are not allowed. To exit enter '-1'.");
}
else
{
guessNum = inGuess.parseInt();
if (inGuess == "26")
{
alert("Congratulations, you guess correctly!");
guessResult="Correct!";
}
else
if (guessNum < correctNum)
{
guessResult="Too low";
}
else
{
guessResult="Too high";
}
document.getElementById('emp'+loopCt).innerHTML=inGuess;
document.getElementById('ct'+loopCt).innerHTML=guessResult;
}
}
}
parseInt is a global function. You are trying to access it off of a string object, where it doesn't exist.
guessNum = parseInt(inGuess, 10); // Tell it what base to use. Protect against 08 being interpretued as octal.
That would be the correct way to handle this.
parseInt Mozilla Developer Network Docs
Footnote - parseInt can return NaN which when compared with typeof actually returns number
parseInt is a method on window, not on a string. You want
guessNum = parseInt(inGuess, 10);
The second argument insures that your code will treat the first argument as a base-10 number, meaning it will correctly parse "010" as 10 and reject "0x10" instead of parsing it as 16.
I thought all things in js were basically objects
They are objects, but that doesn't mean that all objects have the same set of methods defined on them.
If you do want to use it like that for whatever exotic reason, you can define prototype on the String object:
String.prototype.parseInt = function() {
return parseInt(this,10);
}
var inGuess = "26";
alert(inGuess.parseInt());
Your syntax isn't quite right... From the console:
> x = parseInt("2", 10)
2
Also, something to keep in mind, which come from the docs...
If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.
parseInt() Documentation
inGuess is a string and string does not have parseInt function. parseInt is a global function.
do this:
guessNum = parseInt(inGuess);

Integer validation not working as expected

Thanks to some of the answers on this site, I built a function to validate an integer inside a prompt in javascript. I found out how to use isNaN and the result of % in order to meet my needs, but there must be something wrong, because is still not working: This function for validation needs to accept only integers, and as extra bonus, it will also accept a special keyword used for a different purpose later on in the program.
So, previously I had defined:
var value = prompt("Type an integer");
So after that, I made a call for the validation function, and that included three conditions: The validation warning would jump if:
1) The string is not a number
2) The string % 1 is not 0 (means is not an integer)
3) The string is not the special keyword ("extra") which is also valid as input.
The function needs to loop and keep showing the prompt until a valid data is written.
while (isNaN(value) == true && value % 1 != 0 && value != "extra") {
alert("Please, type an integer");
var value = prompt("Type an integer");
}
What am I doing wrong? Thank you so much for any ideas. I know the integer validation has been asked many times here, and here I got a few ideas, but I might be missing something...
You might be complicating things too much... A quick regular expression will do the trick.
while (!/^(\d+|extra)$/i.test(value)) {
...
}
You typed only one equal at
isNaN(value) = true
jsFiddle example
var int = 10;
var str = "10";
var isInt = function(value) {
return (str === 'extra' || !isNaN(parseInt(value, 16)) || /^\d+$/.test(value));
};
var isIntStrict = function(value) {
return (isInt(value) && typeof value !== 'string');
}
console.log('false', isInt('kirk'));
console.log('true', isInt(int));
console.log('true', isInt(str));
console.log('true', 'strict - int', isIntStrict(int));
console.log('false','strict - string', isIntStrict(str));
console.log('false','strict - string', isIntStrict('0x04'));
console.log('true','strict - string', isIntStrict(0x04));
I assume that for your purposes #elclanrs' answer is all you need here, and is the simplest and most straightforward, but just for completeness and dubious laughs, I'm pretty sure that the following would also do what you're looking for:
function isAnIntOrExtra(v) {
if (parseInt(+v) === +v && v !== '') {
return parseInt(+v);
}
else if (v === 'extra') {
return v;
}
else {
return false;
}
}
Fiddle here
These should all pass and return an integer in decimal notation:
'387' returns 387
'-4' returns -4
'0' returns 0
'2.4e3' returns 2400
'0xf4' returns 244
while these should all fail:
'4.5' returns false
'2.4e-3' returns false
'0xgc' returns false
'' returns false
'seven' returns false
And the magic-word 'extra' returns 'extra'
Of course, it'll "fail" miserably with values like '1,345', and will probably roll right over octal notation, treating it as though it were decimal notation (depending on the JavaScript engine?), but it could be tweaked to handle those situations as well, but really, you're better off with the regex.

Categories