Are these line codes the same? - javascript

I want to know if these two scripts do the same thing:
parseInt(num)?num=parseInt(num):num=str.length
and
num=parseInt(num)||str.length;
And in case they are not, I need to know what the second do.

Yes they are same with later (short circuit evaluation) being terse and a beauty of JS (or other languages that support it):
num = parseInt(num) || str.length;
Both in turn are short-cut of this:
if (parseInt(num)){
num = parseInt(num);
}
else {
num = str.length;
}
Good Practices:
Don't foget var keyword before num variable otherwise it goes into global scope.
Always specify a base to parseInt eg parseInt(num, 10) unless otherwise needed
Readings:
Short-Circuit Evaluation
Ternary Operator

Yes, they do (but the second is very slightly more efficient as it doesn't have to run parseInt twice).

yes, they are equal. This is also the same:
num = parseInt(num)?parseInt(num):str.length

Related

What is the use of = sign (single) in a condition?

I had read in some articles that in some languages, like in JavaScript, assignment operators can be used in conditional statements. I want to know what is the logic behind that operation? As far as I know, only comparison operators are allowed in condition checking statements.
Any expression is allowed in a condition checking statement. If the value of the expression isn't boolean, then it will be converted to boolean to determine what the statement should do.
You can for example use a number in an if statement:
if (1) { ... }
Any non-zero number will be converted to true.
In Javascript an assignment is also an expression, i.e. it has a value. The value of the expression is the same value that was assigned to the variable.
So, you can use an assignment expression in a condition checking statement, and the value of the expression is converted to boolean if needed:
if (x = 1) { ... }
Using an assignment in an condition checking statement can be useful, if the value that you assign should be used to control what happens. If you for example have a function that returns different values for the first calls, then a null when there are no more values, you can use that in a loop:
while (line = getLine()) {
document.write(line);
}
You can of couse do that with the assignment separated from the logic, but then the code gets more complicated:
while (true) {
line = getLine();
if (line == null) break;
document.write(line);
}
In JavaScript (and many other languages), when a value is assigned to a variable, the value "returned" is the value that was assigned to a variable. As such, such a statement can be used in a condition with any assigned value being evaluated in the standard way.
For example:
var y = 0;
if(x = y){
alert("Y(and thus X) is Truthy");
}
else{
alert("Y(and thus X) is Falsy");
}
There are two factors that combine to give this effect:
in many languages, including JavaScript, an expression of the form left = right evaluates to the new left. For example, a = b = c = 0 sets all of a, b, and c to zero.
in many languages, including JavaScript, a wide variety of values can be used as conditional expressions. if(7) is equivalent to if(true); so if(a = 7) is equivalent to a = 7; if(true) rather than to the presumably-intended if(a == 7).
Assigning a value with = returns that value. You can use it to make an assignment while testing if the outcome is truthy or falsey (null, 0, "" undefined, NaN, false)
if (myVar = myArgument) ...
//same as:
// myVar=myArgument;
// if (myArgument) ...
This assigns myArgument to myVar while testing myArgument. Another more specific example:
If (myVar = 3+2) ...
// same as:
// myVar=3+2;
// if (5) ...
The benefit is more compact, terse code, sometimes at the expense of clarity.
This could be used to make a condition check and also use the value after it, without writing more lines.
if (value = someFunction()) {
...
}
This is valid syntax, though highly discouraged. In quite a few languages this is explicitely forbidden, but some languages also does not make this rule (e.g. C).

JavaScript if statement not behaving as expected

Just learning to code JavaScript, trying to learn if statements but my code isn't working:
var car = 8;
if (car = 9) {
document.write("your code is not working")
}
This executes the write command and I have no idea why. I'm using the tab button for indents, is that not allowed?
= is called assignment operator in JavaScript, it assigns the value of the right hand side expression to the variable on the left hand side.
You have to use comparison operator instead of assignment operator like this
if (car === 9)
We have two comparison operators in JavaScript, == and ===. The difference between them is that,
== checks if the values are the same, but === checks if the type and the value is also the same.
Go through the wonderful answers, to know more about == and ===
This line assigns car to the value of 9 and check if it is truthy (which 9 is).
if (car=9)
I think you want to use a comparison operator, like this:
if(car == 9)
use this code
var car = 8;
if (car==9)
{
document.write("your code is not working")
}
you need to understand about operators '=' is an assignment operator whereas '==' is a comparision operator.
See Tutorial
If you want
to compare if car is equal to 9, then you have to use code
if(car === 9){
/*Your code goes here*/
}

Is <boolean expression> && statement() the same as if(<boolean expression>) statement()?

Are the two identical?
Suppose you have:
var x = true;
And then you have one of either:
x && doSomething();
or
if(x) doSomething();
Is there any differene whatsoever between the two syntaxes? Did I stumble across a nice bit of sugar?
Strictly speaking, they will produce the same results, but if you use the former case as a condition for something else, you will get dissimilar results. This is because in the case of x && doSomething(), doSomething() will return a value to signify its success.
No, they are not identical. While if is a statement, the AND operator is an expression.
That means you could use its result in an other expression, which you can't with an if-statement:
var result = x && doSomething();
Yet, in your case both have the same effect. Use the one that is more readable and represents your program structure better; I'd recommend the if-statement.
Short answer: No.
Long answer:
A stated by #Steve x && doSomething() is an expression,
whereas if(x) doSomething(); is a statement,
As suggested by #Daniel Li and #Bergi, think:
an expression is computed ( supposed to return a value here ).
a statement is declared ( not supposed to return a value here, think side-effects ).
Why is it confusing?
JS allows us to write ( thatExpression );
JS allows us to write thatExpression;
both assuming some kind of doNothingWithValueOf statement.
How to choose?
Do you use:
doSomething() as an
expression , think IsMyObjectWhatever() or MyObjectComputedValue(),
or as a statement, think ModifyMyObject()
And then: Do you use x && doSomething() as an expression ?
You'll end up thinking something like thisStatement( thatExpression ); everywhere, think:
() expression,
; statement.
Then why should I choose?
Obvious is that "It works." doesn´t stand for "It´s right".
If less obvious is when it will make the difference:
just think ()(()())()(); can be right, (;) is wrong.
check #wwaawaw Javascript: difference between a statement and an expression?
or expressions-vs-statements post by Axel Rauschmayer
In a word no, the two statements are not equal, though in the specific circumstances you present the outcome is the same.
x && doSomething(); is an expression, first the x evaluated, because this is an AND and since x is true the second argument (doSomething()) is then evaluated. In this case this means that the method is executed. If x were false then doSomething() would not be executed as the result of the expression cannot be true.
if(x) doSomething(); is a statement. The value of x is checked, and if it is true the scope of the if statement is executed.
I've put together this fiddle to demonstrate (with minor modifications).
Let's play detective.
We'll call our first approach Conditional Arrow Invocation and our second approach Traditional If Else.
We'll create two separate cases in jsperf to evaluate how these two approaches fair.
Conditional Arrow Invocations
const VALUE = true;
const TEST = false;
//test 1
VALUE && !TEST && (() => {
console.log('print me!');
})();
Ops/sec result:
FireFox: 65,152
Chrome: 129,045
Traditional If Else
const VALUE = true;
const TEST = false;
//test 2
if(VALUE && !TEST) {
console.log('print me!');
}
Ops/sec result:
FireFox: 65,967
Chrome: 130,499
Conclusion
As you can see, performance wise there isn't a huge difference but marginally Traditional If Else won over Conditional Arrow Invocation most of the times by an insignificantly small number. This might have something to do with creating an implicit function on the fly.
I also realized Chrome's JavaScript is a lot faster than FireFox's JavaScript execution.
Here is the jsperf link that you can run to evaluate this for yourself.
https://jsperf.com/conditional-methods-vs-traditional-if-else/1

What's the equivalent way of writing inline assignment and checking PHP 'logic' but in JavaScript

In PHP you could write this:
if(false !== ($value = someFunctionCall())) {
// use $value
}
How would you write an equivalent of this in JavaScript without defining
var value;
before this comparison?
You'd write
if (value = someFunction()) {
I don't trust my knowledge of PHP that heavily, but I suspect that explicit comparisons to false in if statements aren't necessary, as the expression is implicitly boolean. (edit — sometimes, if a function can return either an explicit boolean or some "good" value that evaluates to "falsy", then yes you do need the explicit comparison to boolean.)
edit — if you're squeamish about the ages-old confusion (or potential thereof) between = and ==, then I'd advise avoiding the construct entirely. There's nothing wrong with it, other than the fact that sometimes you want an equality comparison and sometimes you want an assignment.
edit oh also this presumes that "value" has been declared with var somewhere — if the question is about how you do the declaration in the context of an if statement, then the answer is that you cannot do that.
final edit I kind-of promise — to sum it up:
Assuming that "value" is declared:
var value;
somewhere, then:
if (false !== (value = someFunction())) { ... }
has pretty much the same semantics as the PHP original.
You can just have it assign when it's executed and JavaScript will automatically add the var declaration:
function foo(){
return (Math.random() * 0.5) > 0;
}
if (false !== (f = foo())){
alert('True!');
}
alert('f=' + f.toString());
jsFiddle Example
However, this is very bad practice. You should always declare your variables when and where you need them first. Just because PHP and JS accept this syntax doesn't mean it's good practice. The proper style would be as follows:
var f = false;
if (false !== (f = foo())){
alert('True!');
}
alert('f=' + f.toString());
That would be very bad practice in JavaScript,
You would be best to do
if(!(var value = someFunctionCall())) { // use value //}
Personally i would say define it before. Your call though. If you worried about memory then define it and null it after use.

Have the parenthesis in the javascript expression "(p) ? 1 : 0" any effect?

Take the following javascript:
var x = (p) ? 1 : 0;
p can be any value. It there any situation the parenthesis can have effect?
If so: please provide examples.
This is a bit of a contrived example, but hey, why not?
var y = -2;
var x = (y+=2)?0:1?1:0;
alert(x); // will alert '1'
versus
var y = -2;
var x = y+=2?0:1?1:0;
alert(x); // will alert '-2'
Check out this Javascript precedence table: http://www.codehouse.com/javascript/precedence/. Anything below the ternary operator (e.g. "?:") is going to require parentheses if you use it in ternary operator's evaluated expression.
In case p was divided into several boolean expressions with different operators, nested parenthesis can decide the order of how to expressions are computed. But I have the feeling you already know that, and it was not part of the question.
But no, parenthesis have no effect on p as a whole. And I don't know why would someone put them, for I don't think they improve readability.
I can't think of any reason you would need parenthesis there except for readability.
No. It's sometimes done by analogy with:
if (p)
where the brackets are compulsory.

Categories

Resources