Why is this '=' syntax incorrect in this js snippet? - javascript

var hungry = true;
var foodHere = true;
var eat = function() {
if (hungry && foodHere === true) {
return(true);
} else {
return(false);
}`
};
The first line is the correct syntax. For a long time I was just saying hungry && foodHere = true... and I couldn't figure out (and still don't understand) why that is wrong. I understand the difference between = (assignment) and === (equal to). I assigned the variables to be true initially, so aren't I asking in the if statement if that's what they're set to? Why am I setting the variables = to in the var definition, but then when checking them I'm using the === value?

= is only used to assign variables. === or == are used to compare. For a good example, we must look into comparison operators.
Syntax
The syntax of comparison operators is fairly simple, use them to evaluate expressions. The comparasin operators are:
=== //strict equality
== //Parsed or partial equality
> //Greater Than
< //Less than
>= //Greater than or equal to
<= //Less than or equal to
To properly use these, you must know the proper syntax. For example, I can't do something like:
if(true == 1 === true) //do something
as that would invalidate the code, and slow it down by much using ==, which brings me to my next section.
Equality
The two equality operators in JavaScript are == and ===. They do two very different things.
===
The strict equality (===) tests whether two values are exactly equivalent, both in type and value.
==
The Parsed equality (==) tests whether two values are equalivent in value, but parses to try and connect different types.
Inequality
There are 2 main inequality value in JavaScript (!==) they are pretty self explainatory based on the equalities (===, and ==)
here's a chart explaining the three.
1 0 true false null undefined ""
1 === !== == !== !== !== !==
0 !== === !== == == == !==
true == !== === !== !== !== !==
false !== == !== === == == ==
null !== == !== == == == ==
undefined !== == !== == == === !==
"" !== == !== == == !== ===
Adding onto what #jcollum said, = defines a variable value, and if(something === true) simplifies into if(something). Similarly, if(something === false) simplifies into if(!something).
You also need to do comparisons separately. if(7 & 6 < 10) returns false because it is the simplified version of if(7 === true && 6 < 10).

It turns:
hungry && foodHere === true
into
hungry && true
or just
hungry
Using the assignment operator instead of the comparison operator is stopping your logic from working correctly.

Related

Multiple Values after Comparison Operator [duplicate]

I want to write an if/else statement that tests if the value of a text input does NOT equal either one of two different values. Like this (excuse my pseudo-English code):
var test = $("#test").val();
if (test does not equal A or B){
do stuff;
}
else {
do other stuff;
}
How do I write the condition for the if statement on line 2?
Think of ! (negation operator) as "not", || (boolean-or operator) as "or" and && (boolean-and operator) as "and". See Operators and Operator Precedence.
Thus:
if(!(a || b)) {
// means neither a nor b
}
However, using De Morgan's Law, it could be written as:
if(!a && !b) {
// is not a and is not b
}
a and b above can be any expression (such as test == 'B' or whatever it needs to be).
Once again, if test == 'A' and test == 'B', are the expressions, note the expansion of the 1st form:
// if(!(a || b))
if(!((test == 'A') || (test == 'B')))
// or more simply, removing the inner parenthesis as
// || and && have a lower precedence than comparison and negation operators
if(!(test == 'A' || test == 'B'))
// and using DeMorgan's, we can turn this into
// this is the same as substituting into if(!a && !b)
if(!(test == 'A') && !(test == 'B'))
// and this can be simplified as !(x == y) is the same as (x != y)
if(test != 'A' && test != 'B')
ECMA2016 answer, especially good when checking against multiple values:
if (!["A","B", ...].includes(test)) {}
In general it would be something like this:
if(test != "A" && test != "B")
You should probably read up on JavaScript logical operators.
I do that using jQuery
if ( 0 > $.inArray( test, [a,b] ) ) { ... }
For a larger number of values that is checked against often, it may be more efficient to check if the value does not exist in a Set.
const values = new Set(["a", "b"]);
if(!values.has(someValue)){
// do something
} else {
// do something else
}
var test = $("#test").val();
if (test != 'A' && test != 'B'){
do stuff;
}
else {
do other stuff;
}
You used the word "or" in your pseudo code, but based on your first sentence, I think you mean and. There was some confusion about this because that is not how people usually speak.
You want:
var test = $("#test").val();
if (test !== 'A' && test !== 'B'){
do stuff;
}
else {
do other stuff;
}
This can be done with a switch statement as well. The order of the conditional is reversed but this really doesn't make a difference (and it's slightly simpler anyways).
switch(test) {
case A:
case B:
do other stuff;
break;
default:
do stuff;
}

How this expression is evaluated in JavaScript

I know operator priorities for the ones I used in this expression:
if (typeof day === "undefined" || notifiedday !== weekday) //do something
=== 10
|| 5
!== 10
source https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table
I know in C++ during the code execution this expression would work like this:
if (typeof day === "undefined")
{
if(notifiedday !== weekday)
{
//do something
}
}
I am still not sure how this would work in JavaScript during the runtime.
It works the same in JS as it does in C++. Though the example you added to your question is wrong, it should be:
if (typeof day === "undefined"){ // do something }
else if(notifiedday !== weekday){ // do same thing }
What you wrote is equivelant to
if (typeof day === "undefined" && notifiedday !== weekday){ //do something }
Or functionality
if(typeof day === "undefined" || notifiedday !== weekday)
Since or is used, only one of them needs to be true for the expression to be true. So if typeof day === "undefined" is true then notifiedday !== weekday doesn't need to be checked but if typeof day === "undefined" is false then both items need to be checked.
And functionality
if(typeof day === "undefined" && notifiedday !== weekday)
Since and is used, both of them need to be true for the expression to be true. So if typeof day === "undefined" is false then notifiedday !== weekday doesn't need to be checked since and needs both, but if typeof day === "undefined" is true then both items need to be checked.
The comparison is ended when the result is clear.
if (false && true) { } //true won't be evaluated since the left side of the operation gave the final result
if (true || false) { } //false won't be evaluated since the left side of the operation gave the final result
And it works the same for multiples statements
if (false || (false && true)) { } // both falses are evaluated, the true won't be.

Check if a getElementById is empty

I have a if else function in javascript:
if(document.getElementById('lengthFront').value > 4 && document.getElementById('lengthFront').value < 296 && document.getElementById('lengthBack').value > 4 && document.getElementById('lengthBack').value < 296)
{
document.getElementById('param_length').classList.remove('bg-danger');
}
else
{
document.getElementById('param_length').className = "bg-danger";
}
Bu I need an extra check so it won't be executed when lengthFront or lengthBack is empty, I have tried different solutions but I can't find the right way to get it working. All my solutions are pointing to else
I have tried to add:
document.getElementById('lengthFront') == '' && document.getElementById('lengthBack') == '' &&......
document.getElementById('lengthFront') == false && document.getElementById('lengthBack') == false &&......
document.getElementById('lengthFront') == null && document.getElementById('lengthBack') == null &&......
document.getElementById('lengthFront') =!= undefined && document.getElementById('lengthBack') != undefined &&......
Any suggestions
if(document.getElementById('lengthFront') && document.getElementById('lengthFront').value != '')
First condition makes sure that the element exists, second one makes sure it's value is not empty.
For the most concise and readable approach to dealing with DOM elements that may or may not exist and that may not have a valid value if they do exist, might I suggest you leverage two friends: logical AND && which you can use as a faux null coalescing operator, and the 'conditional ternary' operator ?: in such a way that you can check for null and blank string, and then assign a default value (0) or the element value, all in the initial assignment statement. Also, you'll want to avoid multiple redundant getElementByXXX queries by simply assigning the result to a variable (better readability, less typing, performs faster):
var lengthFront = document.getElementById('lengthFront');
var lengthBack = document.getElementById('lengthBack');
var paramLength = document.getElementById('param_length');
lengthFront = (lengthFront && lengthFront.value != '') ? lengthFront .value : 0 ;
lengthBack = (lengthBack && lengthBack.value != '') ? lengthBack .value : 0 ;
if(lengthFront > 4 && lengthFront < 296 && lengthBack > 4 && lengthBack < 296) {
paramLength && paramLength.classList.remove('bg-danger')
} else {
paramLength && (paramLength.className = "bg-danger");
}

Adding the OR operator to a quizz form makes it accept any answers

I'm having a weird problem when trying to create a question form that is validated with Javascript:
If I write my validation like this:
if (typedValue === "myAnswer" && clearedLevels === 1){doStuff}
Everything works. But I want to create several correct answers, so I write:
if (typedValue === "myAnswer"||"secondAnswer" && clearedLevels === 1){doStuff}
..and all of a sudden anything written to the input form is accepted as the answer.
A correct way of writing it is :
if ((typedValue === "myAnswer" || typedValue === "secondAnswer") && clearedLevels === 1) { doStuff() }
You cannot combine the condition (x === y || x === z) as x === y || z and expect the same results.
Any non-empty string in Javascript is true (yes, even the string "false"). Since "secondAnswer isn't empty, it's evaluated as true, and ORed with any other condition will result in true.
You are missing a comparison of typedValue to this literal, and presumably, brackets around the typedValue comparisons, since && has higher precedence than ||:
if ((typedValue === "myAnswer" || typedValue === "secondAnswer") &&
clearedLevels === 1) {
// doStuff
}
extending Akash Pradhan answer you could write
if (typedValue == "myAnswer" || typedValue == "secondAnswer" && clearedLevels == 1) { doStuff() }
but since the && has precedence over the || operator it would evaluate
if (typedValue == "myAnswer" || (typedValue == "secondAnswer" && clearedLevels == 1)) { doStuff() }

what is the difference between != and !== in Javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript === vs == : Does it matter which “equal” operator I use?
Are != and !== are respectively the same as == and ===?
!== and === are strict comparison, and == / != are loose comparison. It's best to use strict comparison.
true == 1 gives you true
true === 1 gives you false
Reason is that == compares only the value (so that 1, '1' is considered as true)
=== compares the value and the type.
Same thing in PHP.
== compares the value of object while === compares the object value and type.
yes it is.
<script>
var str = '1234';
var int = parseInt('1234');
if (int !== str)
{
alert('returns true and alerts');
}
if (int === str)
{
alert('returns false');
}
</script>
http://sandbox.phpcode.eu/g/c801e.php

Categories

Resources