If statement is not working properly - javascript

I'm trying to change the condition in which data is written to a table. I noticed a strange result when trying to change this: it seems WriteToTable function would runno matter what if condition I subjected it to. To test this I did the following:
var TestThis=0;
if (TestThis=1000){
WriteToTable(iPlaceDisplayNum, place.name, place.rating, xScoreFinal, iProspect, place.url, place.formatted_phone_number);
alert ('This alert should not be displaying.');
}
The function will still execute and the alert will be still be displayed when the script runs. I'm not sure why?
Here's the rest of the function, the problem is towards the bottom:
function printme(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
if (typeof place.reviews !== 'undefined') {
var xScore = 0;
var xGlobal = 0;
for (var i = 0; i < place.reviews.length; i++) {
reviews = place.reviews[i];
for (var x = 0; x < reviews.aspects.length; x++) {
aspectr = reviews.aspects[x];
xScore += aspectr.rating;
xGlobal++;
}
}
var xScoreFinal = (xScore / xGlobal);
}
if (typeof xScoreFinal !== 'undefined') {
iPlaceDisplayNum++;
var iProspect;
if (xScoreFinal < 2.3) {
iProspect = 'Yes';
}
//Not sure what's going on here
var TestThis=0;
if (TestThis=1000){
WriteToTable(iPlaceDisplayNum, place.name, place.rating, xScoreFinal, iProspect, place.url, place.formatted_phone_number);
alert ('This alert should not be displaying.');
}
}
}
}

You are assigning a value to your variable in your if condition check. Your TestThis variable is being assigned value 1000, which will be true after being converted to boolean by JavaScript. That's why your function is being always executed. You can read more about the automatic type conversion here.
Now to fix your code, change this -
if (TestThis=1000)
to this -
if (TestThis == 1000)
or if you don't want automatic type conversion -
if (TestThis === 1000)
Sometimes people like to reverse the values in the comparison, in the following way -
if (1000 === TestThis)
This is called a Yoda Condition (yeah, named after the Grand Jedi Master Yoda) . The benefit is that in case someone mistakenly puts only a single equal, it will result in an error as you cannot assign anything to a constant. I have never used it personally though (and probably never will because I find it rather unconventional).

JavaScript allows you to assign a value in a conditional, so this TestThis=1000 results to 1000 and in a conditional statement positive numbers (actually anything not 0) result to an evaluation to true.
To make it a conditional, you should do TestThis===1000 (and you should almost always use the === over the == as the === forces an actual comparison of the two and doesn't try to convert one part of the conditional to equal the other.)
You can also do 1000 === TestThis (or conversly 1000 == TestThis) Some people say this is bad coding, because it's difficult to read. I'll leave that up to you to decide, but this absolutely won't allow you to accidentally assign a value in the conditional because you can't assign a value to 1000.

In the if statement, you're setting TestThis to 1000, rather than comparing it to 1000. The = operator returns the value that was set, which evaluates to true because it is not undefined, 0, or null. You simply need to use the == operator.
if(TestThis == 1000)

if (TestThis == 1000)
Change like this.
For comparing equality in if you must have ==

Change:
if (TestThis=1000)
To:
if (TestThis==1000)
You're actually assigning to TestThis which will return true and execute the conditional block.

Related

javascript if else for beginners

I am very new to Javascript, so I am having a hard time figuring out this easy exercise and what I'm doing this wrong. Any help would be greatly appreciated!
You are given two numeric variables: var n = 25; var result = 0;
Their values may change when you submit.
DO NOT EDIT CODE ABOVE THIS LINE.
=================================
Your Challenge:
Using if and else, make decisions based on the values
of n and result with the following rules:
1. When n is even,
set the value of result to result's current value
plus 10.
2. When n is odd,
set the value of result to result's current value
minus the value of n.
3. Do not declare new variables.
4. Be sure your solution works for all values of n and result.
if (n%2 == 0) {result+10;} else {result-n;}
Your problem isn't if/else, the problem is you never set result to the new value. result+10 just results in the value without storing that value anywhere. (In many programming langauges, that would be a syntax error, but JavaScript allows what it calls ExpressionStatement where any expression can be a statement.)
Either use the compound assignment operators (+= and -=), or write a verbose assignment (result = ...).
Side note: It's easier to debug and edit code when statements are on their own lines, suggest:
if (condition) {
trueStuffHere
} else {
falseStuffHere
}
...or any of the several variations on that theme where trueStuffHere and falseStuffHere are on lines of their own.
You may set the result?
if (n%2 == 0) {
result = result + 10;
} else {
result = result - n;
}
Or if you're a bit better:
if (n % 2 == 0) {
result += 10;
} else {
result -=n;
}

javascript passing the result of a boolean comparison confusion

I've been working through some text book to learn web development and i've become confused on an example. The example creates a meter element and fills it with some attributes. There is then some javascript to check for browser support for the tag. The part where i'm confused is after the first expression returns either true or false for the support, shouldn't there be a check for if true or false was returned on the following if statement? also as an aside, when the create element builds the element does is give it default values, or grab values from an existing meter in the html.
The check for support is as follows.
var noMeterSupport = function(){
return(document.createElement('meter').max === undefined);
}
the next part that builds the meter if the support isn't found is below. This is where i become confused as it seems to take either value and continue without checking if it was true or false.
if (noMeterSupport()) {
var fakeMeter, fill, label, labelText, max, meter, value;
value = meter.attr("value");
meter = $("#pledge_goal");
max = meter.attr("max");
labelText = "$" + meter.val();
fakeMeter = $("<div></div>");
fakeMeter.addClass("meter");
label = $("<span>" + labelText + "</span>");
label.addClass("label");
fill = $("<div></div>");
fill.addClass("fill");
fill.css("width",(value / max * 100) + "%");
fill.append("<div style='clear:both;'><br></div>");
fakeMeter.append(fill);
fakeMeter.append(label);
meter.replaceWith(fakeMeter);
}
The body of the if is only executed if noMeterSupport() returns true. The condition in an if statement requires something "truthy", i.e. something that can be interpreted as true or false. Since the function returns a boolean value, that is sufficient. (See first Google hit for truthiness javascript, which is a good explanation.)
EDIT: Forgot about your second question. When a new element is created with document.createElement, it does indeed get default values. In your example, the default value of max for a <meter> is 1.
if (noMeterSupport()) { checks the return value. It means exactly the same as this:
var supported = noMeterSupport();
if(supported) {
I hope that I understand your question correctly and will try to answer it.
So you would expect something like this:
if (noMeterSupport() == true)
Actually, this is equivalent to this:
if (noMeterSupport())
And if you want to check false:
if (noMeterSupport() == false)
This is equivalent to:
if (!noMeterSupport())
This statement will make the function either return true or false:
return(document.createElement('meter').max === undefined)
basically it would be synonymous with writing:
if(document.createElement('meter').max === undefined) {
return true;
} else {
return false;
}
That makes the value of noMeterSupport() either true or false.
var noMeterSupport = function(){
return(document.createElement('meter').max === undefined);
}
noMeterSupport returns the result of the comparison document.createElement('meter').max === undefined.
The comparison will be either true or false, ok?
So, now, when you do
if (noMeterSupport()) { /*then do something*/}
is like saying
if (/*the result of noMeterSupport() is true*/) {/*then do something*/}
So, this if statement will only run if noMeterSupport returns true
var noMeterSupport = function(){
return(document.createElement('meter').max === undefined);
}
This section of code is not actually doing the check, it is defining a function called noMeterSupport.
The code is not actually run until the function is called. It is called by adding () to the function name.
noMeterSupport()
Your if() statement is where it is being called as it the brackets.
You expect a boolean condition inside the if statement:
if(<boolean_condition>)
{
...
}
The noMeterSupport() is actually returning true or false, so the
if(noMeterSupport())
is converted to if(true) or if(false)
depending on the result of the document.createElement('meter').max === undefined evaluation.
You are receiving a boolean condition and the if statement works fine.
As a beginner, there's two points to quickly learn in programming :
The comparison operators == and === not only do the comparison, but returns in fact the result of this comparison (you can place it in var to test)
var bool = 1 === 2;
console.log(bool); // will print false
The test if(boolean === true) is equivalent to if(boolean), and the test if(boolean === false) is equivalent to if(!boolean)

If-statement fail in javascript

For several hours now am I trying to make a simple game, but one if-statement is failing:
function checkDiagonaal() {
if (document.getElementById("11").src.indexOf("o.png") &&
document.getElementById("22").src.indexOf("x.png") &&
document.getElementById("33").src.indexOf("o.png"))
{
winnaar = true;
}
}
The condition is not true, yet the variable winnaar is set on true. I don't see what I am doing wrong. Very probably just a little mistake.
I also tried this code:
if(document.getElementById("11").src === "images/o.png")
but this returns false (even when the condition is true). I would like to know why?
Use ...indexOf(...) >= 0 in such conditions.
indexOf returns -1 when the value is not found, -1 is truthy
From the MDN(great resource!):
"The indexOf() method returns the index within the calling String
object of the first occurrence of the specified value [...] returns -1
if the value is not found."
When statements get big they become a bit unreadable, it might be fine now, but if you need to add more checks, I would suggest a different approach:
function checkDiagonaal() {
var ids = [11,22,33];
var strs = ['o.png','x.png','o.png'];
var winnar = ids.every(function(id,i) {
return document.getElementById(id).src.indexOf(strs[i]) > -1;
});
}

keep add the value without overwrite the function

function checkData() {
var temp = 0;
var totalMarks = countMark(temp);
if (totalMarks != 100)
window.alert("Marks must total 100");
}
function countMark(mark) {
var totalMark = 0;
totalMark += parseInt(mark)
return totalMark;
}
function doAdd() {
var taskid = document.getElementById("taskid").value;
var taskname = document.getElementById("taskname").value;
var taskmark = document.getElementById("taskmark").value;
if (taskid.length === 0)
window.alert("Task Id cannot be empty!");
if (taskname.length === 0)
window.alert("Task name cannot be empty!");
if (taskmark.length === 0)
window.alert("Task Mark cannot be empty!");
else if (!markpattern.test(taskmark))
window.alert("Invalid data in mark field");
var marks = parseInt(document.getElementById("taskmark"));
if (marks < 0 || marks > 100)
window.alert("Marks out of range. Please re-enter");
countMark(marks);
}
My question is when i keep call the doAdd() function. my marks will keep adding . want to do like passing reference like in C++ . my function countMark(...) will keep adding .
after that, when my form submitted, my form will call the function checkData()
If my totalmark is not 100 . will prompt out the alert and error.
but my code is not working . I guess that my countMark function wrong somewhere
If I understand you correctly, you're looking for the equivalent of a static variable - something that gets initialized the first time the function is called, and keeps it's value for subsequent calls.
Take a look at this related question: https://stackoverflow.com/a/1535650/2444111
The top answer (by CMS) is talking about class-based static variables, which are not quite the same thing.
The second answer (by Pascal MARTIN) is what you're looking for. It takes advantage of the fact that JS functions are also objects, and stores the variable as a property of the function object. This is a better solution than using a global variable (or a property of window, which is what a global actually is)
There are several issues in your code and it's really hard to say what your intention was. But I will address what I found.
In the following piece of code you are requesting a DOM Element and try to parse it as an Integer. The result of that type convertion is always NaN. Maybe wanted to get the value attribute of your element, like you did before. (Also, don't request the same element multiple times. Request it once, save the result in a variable and use that variable from that on).
var marks = parseInt(document.getElementById("taskmark"));
if (marks < 0 || marks > 100)
window.alert("Marks out of range. Please re-enter");
countMark(marks);
Your function countMark is pretty useless, because it will always return whatever Number you pass to it (see comments in your code).
function countMark(mark) {
var totalMark = 0; //create a new variable with value 0
totalMark += parseInt(mark) //add "mark" to that variable
return totalMark; //return that variable => 0 + mark = mark (and if mark = NaN => 0 + mark = NaN)
}
Maybe you wanted to make totalMark a global variable, than you would need to define it outside of your function:
var totalMark = 0;
function countMark(mark) {
totalMark += parseInt(mark);
return totalMark;
}
Last but not least, lets analyse your function checkData:
function checkData() {
var temp = 0; //create a local variable with value 0
var totalMarks = countMark(temp); //pass 0 to countMark => return 0 => totalMarks = 0
if (totalMarks != 100) //always true since totalMarks is always 0
window.alert("Marks must total 100"); //will always alert
}

Why does this JQuery only work if I console.log a bad variable? [duplicate]

This question already has answers here:
Why does this append only work if I console log a bad variable
(2 answers)
Closed 9 years ago.
I am relatively new with jquery, and am trying to change an up and down arrow on a js accordion on each click, unfortunately, I have run into an error where it only works if I console.log a bad variable. Does anyone have any guidance as to what I might be doing wrong when I onclick="embiggen(1)" for example if its accordion id one?
There are some other issues surrounding the html, but specifically why is this only working if I console.log;?
function arrowup(id){
$('#downarrow'+id).remove();
$('#dropdown'+id).append('</a>');
$('#dropdown'+id).append('<i id="uparrow'+ id +'" class="icon-1 icon-chevron-up">');
}
function arrowdown(id){
$('#uparrow'+id).remove();
$('#dropdown'+id).append('</a>');
$('#dropdown'+id).append('<i id="downarrow'+ id +'" class="icon-1 icon-chevron-down">');
}
//Switches the arrows
function embiggen(id){
var up = $('#uparrow'+id).length;
if (up == 1){
arrowdown(id);
console.log(i see you);
}
var down = $('#downarrow'+id).length;
if (down == 1){
arrowup(id);
}
}
The bad console.log() makes it "work" because the error breaks the script execution before entering the second if statement.
Fixing the real issue
down == 1 is always true. You should use an else statement:
if ($('#uparrow'+id).length){
arrowdown(id);
} else if ($('#downarrow'+id).length){
arrowup(id);
}
Understanding it
down == 1 is always true independently of up == 1. Here's your logic explained in pseudo-code in both scenarios:
var up = 1, down = 0;
if (up) { down = 1; up = 0; } //enters this block, down now is 1
if (down) { down = 0; up = 1; } //enters this block as down == 1
var up = 0, down = 1;
if (up) { down = 1; up = 0; } //doesn't enter this block
if (down) { down = 0; up = 1; } //enters this block as down == 1
You just have put an else in there so the execution flow does not enter the second if statement in case the first one succeeds.
if (up) {}
else if (down) {}
Truthy/Falsy values
To explain why I'm using .length isolated inside the conditional statement: in JavaScript, the number 0 is a falsy value and 1 is truthy, hence these can be used directly inside the if statement and it will be interpreted based on the internal ToBoolean algorithm logic. Obviously you can == 1 if you feel like, that's more clear though slightly redundant.
A possibly simpler way around
Going a little off-topic, but your goal can most likely be achieved in an easier way. I may be oversimplifying your logic, but depending on your intents you may just toggle between those two classes:
function embiggen(id) {
$('#arrow'+id).toggleClass('icon-chevron-up icon-chevron-down');
}
Then, you'd no longer have to create a new #downarrow/#uparrow element each time the function is called. If said arrow has JS behavior attached, you can check which logic to execute through an if statement using hasClass().
It works because when an error occurs, JavaScript skips the rest of your function body.
The problem in your case is that the function arrowdown() creates #downarrow+id, making the next condition truthy and calling the function arrowup().
You either need an alternative branch, using Fabricio's answer, or return immediately after making changes to the DOM that would otherwise change the state:
function embiggen(id) {
if ($('#uparrow'+id).length) {
return arrowdown(id);
}
if ($('#downarrow'+id).length) {
return arrowup(id);
}
// ehm, something else happened?
}

Categories

Resources