else operator | JS | Chrome extention - javascript

I have this function:
function FizzBuzz(){
if(document.getElementById("textbox") == true){
Fizz();
} else {
Buzz();
}
}
The Fizz() and Buzz() functions place text in textboxes specified by document.getElementById in their own functions.
in it's current configuration, it should to my understanding execute Fizz() if ("textbox") is found on the webpage, otherwise Buzz() should be executed. This does not happen, and it will only execute one of them, no matter if ("textbox") is true or not.
The ("textbox") referenced above only exists on one of the two pages this is designed to work with.
Changing to !== true will invert the effect, the same with == false, as with the current behavior is expected. I have also tried to check for == null and !== null, this results in the same behavior.
I simply do not understand what I'm doing wrong here.

document.getElementById returns either null or element. So, comapring both with == or === with true or false will always return false.
You can directly put document.createElement inside if as a condition.
If you still face the issue, I suggest you to put a break point and see how the code is executed.
Sample code for better understanding - https://codepen.io/Yash__/pen/WNzgYvL?editors=1111
<h1 id="hai">hai</h1>
if(document.getElementById('hai')){
console.log("there");
}else{
console.log("not there")
}

Related

Javascript stops when first if condition fails, need to move it to second condition

I have the following code in which I ask it to check if either one of 2 dataLayer values is "!= false" then run the rest of the code.
However, code breaks as soon as the first condition fails and does not move to check the second condition. So, how can I let both conditions be checked as one of them will always be available in dataLayer?
function init() {
if (dataLayer.condition[1] != false || dataLayer.condition[2] != false) {
Do something
}
}
Below is the screenshot of the error I get when the first condition values are missing on the page.
You can use optional chaining (?.) for this, if your execution context is expected to support it:
if (dataLayer?.condition[1] != false || dataLayer?.condition[2] != false) {
// Do something
}

Why is an if statement triggering without the parameters present being true?

I've just come across a situation in which an if statement is constantly triggering despite the parameters not being true.
function draw(){
if(5<mouseX<10 && 5<mouseY<10){
background(100);
} else (background(200));
}
When running the above program, the background is always value 100, no matter where I move the mouse.
I've boiled this down from an attempt to make a button within a mouseClicked function in a successful attempt to find my fundamental problem of misunderstanding. I'm running it in p5js if that helps.
Your if-statement should be as follows:
if(5<mouseX && mouseX<10 && 5<mouseY && mouseY<10)
The reason behind this behaviour is:
if(5<mouseX<10 && 5<mouseY<10){
background(100);
} else (background(200));
When the javascript engine reads 5<mouseX it returns true then reads true<10 this is also true as here the js engine treats true as 1 and condition 1<10 is always true. This happens with other part of the expression also.
Try using :
if(5<mouseX && mouseX<10 && 5<mouseY && mouseY<10)

Boolean in IF Condition causing Errors in JavaScript

I am developing a webpage with fairly simple JavaScript. My entire JavaScript code is:
function showUnlockPopup(isViolated,instId,unlock_done,unlock_total,period,endDate){
alert(isViolated);
if(isViolated){
if(unlock_done < unlock_total){
showInfoPopup(instId,unlock_done,unlock_total,period);
} else {
showNoUnlocksPopup(instId,unlock_done,unlock_total,period,endDate);
}
} else {
showNotViolatedModal();
}
}
However, irrespective of the value of the 'isViolated' variable, my 'showInfoPopup' function is called.
I have checked the code for the method call too:
<button onClick="showUnlockPopup(isViolated)">Unlock</button>
The alert shows 'true' or 'false' values correctly, but the logic runs for only 'true' irrespective of the value.
I think I am missing something fairly basic here. I tried a lot, but of no use. Kindly help me with the same.
it is because isViolated is returned as a string. so unless the string is null it will be true if it has some contents. You should change your check to isViolated == 'true', make a new variable that is a boolean and assign it depending on isViolated or something third.

If statement in a switch

I am working on a question for a course for learning javascript. I am running into trouble trying to add an if statement inside of a switch. I currently have:
var user = prompt("Are you ready for battle?!").toUpperCase();
switch(user) {
case'YES':
if(YES && NO) {
console.log("Great, let's do it.");
} else {
console.log("Bye");
}
console.log("Great! It will be a long exciting battle.");
break;
case'NO':
console.log("Come back when you are ready.");
break;
case'MAYBE':
console.log("Go away. This is only for the brave");
break;
default:
console.log("You obviously do not belong here. It was a simple yes/no question.")
}
The question is this:
Add some if/else statements to your cases that check to see whether one
condition and another condition are true, as well as whether one condition
or another condition are true. Use && and || at least one time each.
The error I am getting is this: ReferenceError: YES is not defined
What can I put in the if's condition to make this work or how do I define YES?
It would appear that you have two problems working against you here.
First is the issue pointed out in comments that you're treating YES and NO like variables, and they aren't. To avoid robbing you of the opportunity to learn by providing a corrected version of your code, I'll only give relevant examples.
var word = "test";
// If we compare against the string literally, it will have an error
// because it's looking for a variable with that name.
if (word === test) { } // ReferenceError: test is not defined
// we fix this by quoting what we're comparing against
if (word === "test") { } // Code inside the block would be executed :)
// But what about checking the value of "test" by itself?
// A string is "truthy", meaning that it passes the conditional test always.
if ("test") { } // Code would be executed always regardless of the content of var word
// Stringing multiple constants together doesn't make sense
if ("test" && "word") { } // This is equivalent...
if (true && true) { } // ... to this, which doesn't make sense
This brings us to the second problem you're trying to solve. The requirements for your problem specify checking if one condition AND another are true, as well as one condition OR another. The problem is that you only have one conditional to check: the status of the variable user.
It only makes sense to test the condition of something if you don't know what it is. Input received from a user is a perfect example. So I'd recommend that you take more inputs from the user such as name, age, gender, shoe size, or anything else. You can then check conditions as follows:
// You would need to store user input in variables username and age previously...
if (username === "vastlysuperiorman" && age < 13) { console.log("You're awfully young!"); }
// Or to only allow people within an age range...
if (age < 13 || age > 31) { console.log("You must be between 13 and 31 years old to play this game!"); }
Once you have multiple conditions to check, you can check them anywhere--inside a function, inside a case statement, inside another if. It doesn't matter. Just add an if block and test the conditions. :)

Logic behaves as if variable is NULL when it is not

I have a encountered a very strange error. I have:
externalContactsGrid.bind('dataBound', function(e) {
contactId = null;
if (typeof e.sender._data[0] === 'undefined') {
contactId = null;
} else {
contactId = e.sender._data[0].contactId
}
console.log(contactId)
if (contactId === false) {
alert(contactId)
$('#externalContactsGrid .k-grid-content table').html('<tr role="row" class="no-results"><td role="gridcell">No results found</td></tr>');
}
})
At the point of console.log(contactId) contactId is for example 2495, but when it hits the if it does not execute because apperently contactId is false (!). What could be causing this?
The weird thing is. is that the alert doesn't happen but the line after ($('#externalCon....) does.
The function is only executing once as I would see console log twice (i.e. 2495, and then null after it).
You are missing a semi-colon (a few, actually). Also, I think you're using the identity operator when you should be using the equality operator. If you want to compare values, use the equality operator.
http://www.w3schools.com/js/js_comparisons.asp
This seems to only happen when I use Jquery's .html() method. I have instead used .append() and the problem no longer occurs.

Categories

Resources