I do a val++ at the end of each txt file is loaded and then run doSome() when val is equal to num.
$('#holder').load('item[i].txt',function(){
val++;
if(val==num){
doSome();
}
}
How to I write this shorthand?
val++;
if(val==num){
doSome();
}
val++ already is (basically) shorthand for val = val + 1;
You can use && to replace the if:
val == num && doSome();
(MDN: && Shortcut operation)
Resulting in:
$('#holder').load('item[i].txt',function(){
val++;
val == num && doSome();
}
Personally, I prefer having the increment and the condition on separate lines, for readability purposes.
Another suggestion: The brackets for an if statement ({}) are optional, if the if statement is only used for 1 line of code:
if(condition) {
doSomething();
}
Can be shortened a bit like:
if(condition)
doSomething();
Use pre-increment operator
if (++val === num) {
//code here
}
This will first increment val by one and then compare the updated value with num variable.
Pre-increment could be used where value of variable is incremented first and then returned whereas in Post-increment, value of variable is returned first and then incremented.
if (++val == num) {
doSome();
}
So... maybe this? :) ++val ^ num || doSome();
^ (XOR) is a bitwise operator. It returns 0 if two operands are the same number. For example 2^2 = 0.
So you can firstly pre-increment val this way: ++val. Then you can do XOR operation on num, and when they are equal - it will return 0, which is considered as false in logic statements in js. And then, when left side of || operator is false, it will execute right part of this statement - doSome().
Btw, one interesting thing: for example, if disable code optimisation, in C++ it is much efficient to assign 0 to variable in this way: a ^= a rather than a = 0.
Related
I am super new at Javascript. I'm trying to write a script that logs numbers in order, and then at the end tells me if the final number is even or odd.
What I have is:
var i = 0;
do {
i++;
console.log(i)
}
while (i <= 9);
if(i % 2 = 1) {
console.log("odd")
}
else {
console.log("even")
}
Before I added the if/else, it worked. Now I keep getting the error: invalid left-hand side in assignment
What am I doing wrong? And to really display my ignorance, what is the left-hand side in the assignment?
Thanks!
Firstly, you will want to use the double equal (==) or the triple equal (===), when checking your remainder, since the single equal (=) is used to assign values to variables.
Difference between == and ===:
=== is more strict than == since === checks the value AND type whereas the == only checks the values.
Example:
if(1 == '1') // true
if(1 === '1') //false : their types are different.
Secondly, you will likely want to wrap your if statement inside of your do-while loop to get an output of even or odd after logging each number.
Here is the final result:
var i = 0;
do {
i++;
console.log(i);
if(i % 2 === 1) {
console.log("odd");
} else {
console.log("even");
}
} while (i <= 9);
When it says invalid left-hand side, it means that you are trying to assign a value to something on the left side. You have used -
if(i % 2 = 1)
However, = is an assignment operator, which basically assigns a value to a variable on the left. What you need is == which is a comparison operator since you are trying to compare two values.
This should be your code -
if(i % 2 == 1)
Instead of = it should be == in the if condition.
you need to change if condition from if(i % 2 = 1)
to
if(i % 2 ==1)
if(i % 2 == 1) {
console.log("odd")
}else {
console.log("even")
}
Because == is for equality comparison while = is for assigning of value.
So the problem in you code is , you are using an assignment operator "=" in your if condition, instead use "==" (comparision operator).
You can find more information on comparision operators in Javascript here :
https://www.w3schools.com/js/js_comparisons.asp
I need to compare two numeric values for equality in Javascript. The values may be NaN as well.
I've come up with this code:
if (val1 == val2 || isNaN(val1) && isNaN(val2)) ...
which is working fine, but it looks bloated to me. I would like to make it more concise. Any ideas?
if(val1 == val2 || (isNaN(val1) && isNaN(val2)))
Nothing to improve. Just add the parentheses to make it clear to everyone.
Avoid isNaN. Its behaviour is misleading:
isNaN(undefined) // true
_.isNaN (from Underscore.js) is an elegant function which behaves as expected:
// Is the given value `NaN`?
//
// `NaN` is the only value for which `===` is not reflexive.
_.isNaN = function(obj) {
return obj !== obj;
};
_.isNaN(undefined) // false
_.isNaN(0/0) // true
Try using Object.is(), it determines whether two values are the same value. Two values are the same if one of the following holds:
both undefined
both null
both true or both false
both strings of the same length with the same characters in the same order
both the same object
both numbers and
both +0
both -0
both NaN
or both non-zero and both not NaN and both have the same value
e.g. Object.is(NaN, NaN) => true
Refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
if ( val1 === val2 )
If either one or both are NaN it will evaluate to false.
Also, NaN !== NaN
As long as you know these two variables are numeric, you can try:
if (val1 + '' == val2 + '')
It turns the two values into strings. A funny answer, but it should work. :)
NaN is never equal to itself no matter the comparison method, so the only more concise solution for your problem that I can think of would be to create a function call with a descriptive name for doing this rather special comparison and use that comparison function in your code instead.
That would also have the advantage of localizing changes to the algorithm the day you decide that undefined should be equal to undefined too.
And what's about the function Number.isNaN() ? I believe this must be used whenever is possible.
> NaN === NaN
false
> Number.isNaN
ƒ isNaN() { [native code] }
> Number.isNaN() === Number.isNaN()
true
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
For Numeric cases the solution is fine but to extend it to work for other data-types as well my suggestion would be as follows:
if(val1 === val2 || (val1 !== val1 && val2 !== val2))
Reason being global isNaN is erroneous. It will give you wrong results in scenarios like
isNaN(undefined); // true
isNaN({}); // true
isNaN("lorem ipsum"); // true
I have posted a comprehensive answer here which covers the NaN comparison for equality as well.
How to test if a JavaScript variable is NaN
Why not an if statement like this?
if (isNaN(x) == true){
alert("This is not a number.");
}
Equality comparison with NaN always results in False.
We can go for the javascript function isNaN() for checking equality with NaN.
Example:
1. isNaN(123) //false
2. var array = [3, NaN];
for(var i = 0 ; i< array.length; i++){
if(isNaN(array[i])){
console.log("True ---- Values of " + i);
} else {
console.log("false ---- Values of " + i);
}
}
Results:
false ---- Values of 0
True ---- Values of 1
Found another way using Array.prototype.includes MDN link. Apparently, [NaN].includes(NaN) returns true for NaN.
function IsActuallyNaN(obj) {
return [obj].includes(NaN);
}
Or we can go with davidchambers' solution which is much simpler.
function IsActuallyNaN2(obj) {
return obj !== obj;
}
I have a simple code:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#continue").click(function() {
var value = jQuery('#continue').attr('value')
alert (value);
if (value='next'){
jQuery('#msg_title').html('blablabla');
jQuery('#msg').html('blablabla'');
jQuery('#continue').attr('value','removeConfig');
value = jQuery('#continue').attr('value');
}
else if (value='removeConfig') {
jQuery('#msg_title').html('It Works!');
}
else {
alert ('Something wrong')
}
return false;
});
});
</script>
It works well in firs if phase, changes button's value (as I see from alert), but doesn't make else if and else statements.
Your comparison operator is wrong: if (value='next') should be if (value == 'next'){ or if (value === 'next'){.
Note the extra = signs.
You need ==
(value='next'){
should be:
(value == 'next'){
You are testing if ('next') { which is always true. Only string the evaluates to false is empty string, ""
Use ==, not =. A single = is an assignment operator, which means it's assigning "next" to value, then testing if value is false, not if value equals next
You need double equals signs as singles will return true in this case:
if (value =="next")
Single = is an assignment operator and double == is a comparison operator. Since you were using an assignment operator and setting the variable to a non falsy value the first if statement resolved to true.
In JavaScript is there a way to get the "value" of a statement in the same way that function() { return eval("if (true) { 1 }"); } returns "1";
function() { return if (true) { 1 } } and all similar permutations I've tried are not valid syntax.
Is eval just blessed with special powers to determine the "last" value of a statement in an expression?
Use case is a REPL that evaluates arbitrary expressions and returns the result. eval works, but I want to wrap it in function.
function(expr) { return eval(expr); }
But that really doesn't do anything more than what eval does, so I'm guessing you must want to do things with the return value of eval before returning it?
E.g.:
function custom_eval(expr)
{
var result = eval(expr);
if ((typeof result))=="string")
{
alert("The expression returned a string value of: " + result);
}
if ((typeof result))=="number")
{
alert("The expression returned a number with value: " + result);
}
//and so on and so forth...
return result;
}
var bob = custom_eval("x=\"bob\";x");
alert(bob);
(More on the typeof operator)
To evaluate arbitrary javascript code in javascript you have three options
eval. This is usually considered as "dangerous", but since javascript is executed on the client's computer, they can only harm themselves (unless you provide clients with a way to share their codes).
Function constructor. The same concerns apply.
write a javascript interpreter. This is definitely tricky for "arbitrary" code.
You can use || to get the first value that isn't null/undefined/0:
var t = 1 || 'b' || 3 || 'd'; // assigns 1
var t = 0 || null || undefined || 'd'; // assigns d
You can use && to get the last value, if no short-circuiting null/undefined/0 is found first:
var t = 1 && 'b' && 3 && 'd'; // assigns d
var t = 0 && null && undefined && 'd'; // assigns 0
I'm trying to implement XOR in javascript in the following way:
// XOR validation
if ((isEmptyString(firstStr) && !isEmptyString(secondStr)) ||
(!isEmptyString(firstStr) && isEmptyString(secondStr))
{
alert(SOME_VALIDATION_MSG);
return;
}
Is there a better way to do this in javascript?
Thanks.
As others have pointed out, logical XOR is the same as not-equal for booleans, so you can do this:
// XOR validation
if( isEmptyString(firstStr) != isEmptyString(secondStr) )
{
alert(SOME_VALIDATION_MSG);
return;
}
I pretend that you are looking for a logical XOR, as javascript already has a bitwise one (^) :)
I usually use a simple ternary operator (one of the rare times I use one):
if ((isEmptyString(firstStr) ? !isEmptyString(secondStr)
: isEmptyString(secondStr))) {
alert(SOME_VALIDATION_MSG);
return;
}
Edit:
working on the #Jeff Meatball Yang solution
if ((!isEmptyString(firstStr) ^ !isEmptyString(secondStr))) {
alert(SOME_VALIDATION_MSG);
return;
}
you negate the values in order to transform them in booleans and then apply the bitwise xor operator. Maybe it is not so maintainable as the first solution (or maybe I'm too accustomed to the first one)
You are doing an XOR of boolean values which is easy to model into a bitwise XOR (which Javascript has):
var a = isEmptyString(firstStr) ? 1 : 0;
var b = isEmptyString(secondStr) ? 1 : 0;
if(a ^ b) { ... }
http://www.howtocreate.co.uk/xor.html
You could use the bitwise XOR operator (^) directly:
if (isEmptyString(firstStr) ^ isEmptyString(secondStr)) {
// ...
}
It will work for your example since the boolean true and false values are converted into 1 and 0 because the bitwise operators work with 32-bit integers.
That expression will return also either 0 or 1, and that value will be coerced back to Boolean by the if statement.
You should be aware of the type coercion that occurs with the above approach, if you are looking for good performance, I wouldn't recommend you to work with the bitwise operators, you could also make a simple function to do it using only Boolean logical operators:
function xor(x, y) {
return (x || y) && !(x && y);
}
if (xor(isEmptyString(firstStr), isEmptyString(secondStr))) {
// ...
}
Easier one method:
if ((x+y) % 2) {
//statement
}
assuming of course that both variables are true booleans, that is, 1 or 0.
If x === y you'll get an even number, so XOR will be 0.
And if x !== y then you'll get an odd number, so XOR will be 1 :)
A second option, if you notice that x != y evaluates as a XOR, then all you must do is
if (x != y) {
//statement
}
Which will just evaluate, again, as a XOR. (I like this much better)
Of course, a nice idea would be to implement this into a function, but it's your choice only.
Hope any of the two methods help someone! I mark this answer as community wiki, so it can be improved.
Checkout this explanation of different implementations of XOR in javascript.
Just to summarize a few of them right here:
if( ( isEmptyString(firstStr) || isEmptyString(secondStr)) && !( isEmptyString(firstStr) && isEmptyString(secondStr)) ) {
alert(SOME_VALIDATION_MSG);
return;
}
OR
if( isEmptyString(firstStr)? !isEmptyString(secondStr): isEmptyString(secondStr)) {
alert(SOME_VALIDATION_MSG);
return;
}
OR
if( (isEmptyString(firstStr) ? 1 : 0 ) ^ (isEmptyString(secondStr) ? 1 : 0 ) ) {
alert(SOME_VALIDATION_MSG);
return;
}
OR
if( !isEmptyString(firstStr)!= !isEmptyString(secondStr)) {
alert(SOME_VALIDATION_MSG);
return;
}
Quoting from this article:
Unfortunately, JavaScript does not have a logical XOR operator.
You can "emulate" the behaviour of the XOR operator with something like:
if( !foo != !bar ) {
...
}
The linked article discusses a couple of alternative approaches.
XOR just means "are these two boolean values different?". Therefore:
if (!!isEmptyString(firstStr) != !!isEmptyString(secondStr)) {
// ...
}
The !!s are just to guarantee that the != operator compares two genuine boolean values, since conceivably isEmptyString() returns something else (like null for false, or the string itself for true).
Assuming you are looking for the BOOLEAN XOR, here is a simple implementation.
function xor(expr1, expr2){
return ((expr1 || expr2) && !(expr1 && expr2));
}
The above derives from the definition of an "exclusive disjunction" {either one, but not both}.
Since the boolean values true and false are converted to 1 and 0 respectively when using bitwise operators on them, the bitwise-XOR ^ can do double-duty as a logical XOR as well as a bitwiseone, so long as your values are boolean values (Javascript's "truthy" values wont work). This is easy to acheive with the negation ! operator.
a XOR b is logially equivalent to the following (short) list of expressions:
!a ^ !b;
!a != !b;
There are plenty of other forms possible - such as !a ? !!b : !b - but these two patterns have the advantage of only evaluating a and b once each (and will not "short-circuit" too if a is false and thus not evaluate b), while forms using ternary ?:, OR ||, or AND && operators will either double-evaluate or short-circuit.
The negation ! operators in both statements is important to include for a couple reasons: it converts all "truthy" values into boolean values ( "" -> false, 12 -> true, etc.) so that the bitwise operator has values it can work with, so the inequality != operator only compares each expression's truth value (a != b would not work properly if a or b were non-equal, non-empty strings, etc.), and so that each evaluation returns a boolean value result instead of the first "truthy" value.
You can keep expanding on these forms by adding double negations (or the exception, !!a ^ !!b, which is still equivalent to XOR), but be careful when negating just part of the expression. These forms may seem at first glance to "work" if you're thinking in terms of distribution in arithmatic (where 2(a + b) == 2a + 2b, etc.), but in fact produce different truth tables from XOR (these produce similar results to logical NXOR):
!( a ^ b )
!( !!a ^ !!b )
!!a == !!b
The general form for XOR, then, could be the function (truth table fiddle):
function xor( a, b ) { return !a ^ !b; }
And your specific example would then be:
if ( xor( isEmptyString( firstStr ), isEmptyString( secondStr ) ) ) { ... }
Or if isEmptyString returns only boolean values and you don't want a general xor function, simply:
if ( isEmptyString( firstStr ) ^ isEmptyString( secondStr ) ) { ... }
Javascript does not have a logical XOR operator, so your construct seems plausible. Had it been numbers then you could have used ^ i.e. bitwise XOR operator.
cheers
here's an XOR that can accommodate from two to many arguments
function XOR() {
for (var i = 1; i < arguments.length; i++)
if ( arguments[0] != arguments[i] )
return false;
return true;
}
Example of use:
if ( XOR( isEmptyString(firstStr), isEmptyString(secondStr) ) ) {
alert(SOME_VALIDATION_MSG);
return;
}
I hope this will be the shortest and cleanest one
function xor(x,y){return true==(x!==y);}
This will work for any type
Here is an XOR function that takes a variable number of arguments (including two). The arguments only need to be truthy or falsy, not true or false.
function xor() {
for (var i=arguments.length-1, trueCount=0; i>=0; --i)
if (arguments[i])
++trueCount;
return trueCount & 1;
}
On Chrome on my 2007 MacBook, it runs in 14 ns for three arguments. Oddly, this slightly different version takes 2935 ns for three arguments:
function xorSlow() {
for (var i=arguments.length-1, result=false; i>=0; --i)
if (arguments[i])
result ^= true;
return result;
}
Try this:
function xor(x,y)
var result = x || y
if (x === y) {
result = false
}
return result
}
There's a few methods, but the ternary method (a ? !b : b) appears to perform best. Also, setting Boolean.prototype.xor appears to be an option if you need to xor things often.
http://jsperf.com/xor-implementations
You could do this:
Math.abs( isEmptyString(firstStr) - isEmptyString(secondStr) )
The result of that is the result of a XOR operation.
#george, I like your function for its capability to take in more than 2 operands. I have a slight improvement to make it return faster:
function xor() {
for (var i=arguments.length-1, trueCount=0; i>=0; --i)
if (arguments[i]) {
if (trueCount)
return false
++trueCount;
}
return trueCount & 1;
}