Does javascript skip statements if the outcome is already known? I'm asking this because for some reason my code doesn't console.log(b) when the outcome is alert('You Lose'). It does console.log when the outcome is alert('You Win').
C always equals true.
So when a = false it does not console.log(b), but when a = true it does console.log(b)
Why?
function example(c) {
var b = true;
var a = validateFunction($('.div1')); // returns true or false
console.log(a);
if (c === true) { // c always equals true
b = validateFunction($('.div2')); // returns true or false
console.log(b);
}
if (a === true && b === true) {
alert('You Win');
}
else {
alert('You Lose');
}
}
It would seem to me that c is not === true. To verify, add an else clause to if (c === true) that contains something to the effect of console.log('C is not === true.');
Yes, most languages parse if statements from left to right and stop as soon as they have a sure result.
Since your first expression in the if statement returns false, the whole statement can't return true, so it does not even try parsing it.
Same happens in an OR statement, if the first expression is false.
Related
I understand the 3rd Conditional but not 2nd one
On the 2nd Conditional - if the length of "str" is 2 (meaning it has 2 characters) then return "str[0] === str[1]" but what if those last two characters are different "c" "g" maybe?
how comparison is being executed in return str[0] === str[1] ? does the comparison have to be inside if() statement because if() statement returns true ?
However, this line return str[0] === str[1] being outside the scope of if() statement return true or false
function isPalindrome(str) {
// 1st Conditional
if (str.length === 1) return true
// 2nd Conditional
else if (str.length===2) return str[0]===str[1]
// 3rd Conditional
else if (str[0] === str.slice(-1)) {
return isPalindrome(str.slice(1,-1))
}
return false
}
return "str[0] === str[1]", but what if those last two characters are different "c" "g" maybe?
This statement will return a boolean value. That boolean value is determined by str[0] === str[1]. This is a comparison that is either false or true. In the example "cg", that comparison will evaluate to false, and so the return statement will make the function return with the value false.
how comparison is being executed in return str[0] === str[1]?
It is executed like in any other context. The expression is str[0] === str[1], and the result of that evaluation is returned by the return statement.
does the comparison have to be inside if() statement because if() statement returns true ?
The return should only be executed when the preceding if statement is true, i.e. that return should only be executed when the length of the string is true.
However, this line return str[0] === str[1] being outside the scope of if() statement return true or false
That statement is not outside the scope of the if statement. It is a statement that is only executed when the if condition is true.
If it helps, we could rewrite that if (str.length===2) return str[0]===str[1] as follows:
if (str.length===2) {
let isPalindromeOfTwo = str[0]===str[1];
return isPalindromeOfTwo;
}
Or even (but this is an antipattern):
if (str.length===2) {
if (str[0]===str[1]) {
return true; // It is a palindrome of 2
} else {
return false; // Not a palindrome
}
}
Just realise that a comparison represents a value: a boolean value. This value can be used in any context that requires a value. You can for instance do any of these:
console.log(str[0]===str[1]); // output will be "false" or "true"
let x = str[0]===str[1]; // x will be a boolean value: false or true
let y = Number(str[0]===str[1]); // y will be a number, 0 or 1
false
0
null
undefined
empty string
I use them,but I am still unaware of the marginal difference each prospect in the above list have.
I mostly use 0,false.But I have come across many scripts that uses undefined ,empty string.
I want to know the exact differnce between them.
I know its a silly question,but would be great If i get a small conscise answer.
It's called "truthy and falsy values" if you want to know how to refer to it.
Here is a link to explain the answer to your question: http://www.sitepoint.com/javascript-truthy-falsy/
(Keep in mind when reading the link at the beginning that !!(value) forces the value to be either true or false)
The type is the difference.
false is a boolean, 0 is a number, null is an object, undefined is undefined, and '' is a string.
You pick the type based on what it is being used as. For example:
// There is nothing wrong with this block of code
var num_cats = 7;
if(num_cats){
// num_cats is truthy
}
// This block works but it could be made more clear
var has_cat = num_cats;
if(has_cat){
// This would work, but it doesn't make sense. As a developer I would
// expect that has_cat should be either true or false, not 7.
// One way to convert the number to a boolean would be:
has_cat = !!num_cats
}
The two most confusing falsey values are probably null and undefined.
null basically means that the variable exists, but it's value is unknown.
undefined means that the variable doesn't exist (although a variable can be explicity set to undefined like var x = undefined; and then the variable x exists but it is explicitly not being defined which means that you can treat it as though it doesn't exist.
The list you have are 5 of the 6 "falsy" values in javascript. If you add "NaN" to that, you would have all the falsy values in javascript. So the complete "falsy" list is
1)0
2)""
3)false
4)undefined
5)null and
6)NaN
When used in a "if" statement, these all behave the same way so
if(0)
if("")
if(false)
if(undefined)
if(null) and
if(NaN) would behave the same
You asked for a short concise answer but I think the best way is just showing how it works with some basic test. Apologies for the long answer
//Checking if all the "falsy" values evaluate the same way in a "if" statement
console.log("Checking if(0)");
if(0) {
console.log(" if(0) Will not be reached");
}
console.log('Checking if("")');
if("") {
console.log(' if("") Will not be reached');
}
console.log("Checking if(undefined)");
if(undefined) {
console.log("if(undefined) Will not be reached");
}
console.log("Checking if(null)");
if(null) {
console.log("if(null) Will not be reached");
}
console.log("Checking if(Nan)");
if(NaN) {
console.log("if(NaN) Will not be reached");
}
console.log("Checking if(false)");
if(false) {
console.log("if(false) Will not be reached");
}
//Checking if all the falsy values are equal(==) to each other in a if statement
if(0 == "") {
console.log('if(0 == "") is true');
}
if(0 == false) {
console.log("if(0 == false) is true");
}
if("" == false) {
console.log('if("" == false) is true');
}
if(0 == undefined) {
console.log("if(0 == undefined) Will not be reached");
}
if("" == null) {
console.log('if("" == null) Will not be reached');
}
if(undefined == null) {
console.log("if(undefined == null) is true");
}
if(NaN == "") {
console.log('if(NaN == "") Will not be reached');
}
//Checking for strictly equality between false and falsy values
if(undefined === false) {
console.log("Will not be reached");
}
if(null === false) {
console.log("Will not be reached");
}
if(undefined ===false) {
console.log("Will not be reached");
}
if(0 === false) {
console.log("Will not be reached");
}
if("" === false) {
console.log("Will not be reached");
}
if(NaN === false) {
console.log("Will not be reached");
}
What this means that though these "falsy" values might be used in a "if" statement interchangeably, they all are not equal(==) to each other(particular the set of 0,"" and false with the other three). If a stricter equals(====) is used, none of these would be equal to false, hence perhaps the classification "falsy" instead of false.
Only two of the values you've mentioned are what I would call designated "special values".
null - In most cases this is equivalent to not applicable.
undefined - The implicit version of null
An example for both:
function findByTitle(arr, title)
{
for (var i = 0; i < arr.length; ++i) {
if (arr[i].title === title) {
return arr[i];
}
}
return null;
}
The return value of null indicates that the record could not be found, otherwise it's an object.
function increment(x, by)
{
return x + (by || 1); // by may be undefined
}
increment(4); // 5
In this case, the by argument is not passed, so JavaScript passes it as undefined implicitly. I wouldn't recommend assigning this to a variable though; rather, I would use null.
The other values you have mentioned are not particularly special; they can be used as a starting value, such as building a string value or calculating a sum, but they're not special in their own right.
"" is a string
false is a boolean
0 and NaN are numbers
The code below represents the idea I am trying to achieve but when I test it doesn't work, what would be the appropriate way to test if q1 and q2 is equal to true?
function processForm() {
if(q1_valid = true && q2_valid = true){
alert("yes");
} else {
alert("no");
}
}
When you use simple = in javascript (and most C-like languages), what happens is that you assign the variable, then return the result of said assignment.
For instance, take the code a = b = true. This can be split up into a = (b = true). Now, if we only look at the part inside the parenthesis, you'll see that what it does is first set b to true, then return b. Then, outside the parenthesis it sets a to whatever b was (which ofcause is true), and returns the value of a. The value of a has nowhere to go, so it's simply dropped.
Now, if we go back to your if-test, what you end up with is basically this:
Set q1_valid to true.
return true (the value of q1_valid) to the && operator.
true is valid for && so it looks at right hand side.
Set q2_valid to true.
return true to the &&.
&& now has true on both sides. Returns true.
Test always passes. q1_valid and q2_valid will always be true after test is run.
The simple solution is to replace = with either == (equals) or === (type and value equals). Your if-check should look like one of the following:
1.
if(q1_valid == true && q2_valid == true)
2.
if(q1_valid === true && q2_valid === true)
Also, since working with booleans (values that are either true or false), the check for equality to true can be omitted altogheter. Another way to do this is simply like this:
if(q1_valid && q2_valid)
Two issues here:
You need to use two equals signs for comparison ==
The variables don't exist in the function, you would need to pass them as parameters when calling the function
function processForm(q1_valid, q2_valid) {
if(q1_valid == true && q2_valid == true){
alert("yes");
} else {
alert("no");
}
}
Can someone explain why in javascript,
alert({} == true) shows false
if ({}) alert('true') shows true ?
What's different in the if condition that changes the result?
I wanted to write some shorthand argument validator obj || (obj = {}); and I was baffled by this discovery.
if ({}) alert('true') -> true
{} is an object, which, when evaluated in the context of an if statement, gets coerced to a Boolean, and since Boolean({}) evaluates to true, you get if (true). This is documented in the ECMAScript specification, Section 12.5 The if Statement:
The production If Statement : if ( Expression ) Statement is evaluated
as follows:
Let exprRef be the result of evaluating Expression.
If ToBoolean(GetValue(exprRef)) is false, return (normal, empty, empty).
Return the result of evaluating Statement.
alert({} == true) -> false
This one is more tricky. From the ECMAScript specification, Section 11.9.3 The Abstract Equality Comparison Algorithm:
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
Thus, {} == true will be evaluated as {} == Number(true), which is evaluated to {} == 1, which is false.
This is also why 1 == true evaluates to true, but 2 == true evaluates to false.
{} is not true so it won't show up in your first example. In your second example {} is not false so it will pass the test.
Like my teacher used to say, you can't compare potatoes and carrots.
It's not only with arrays, it will work with anything:
alert(3 == true); // shows false
if (3) alert('true'); // shows true
In boolean operations, generally anything that is not 0 evaluates to true.
http://jsfiddle.net/QF8GW/
if (0) console.log("0 shows true"); // does not log a value
if (-1) console.log("-1 shows true");
if (12345) console.log("12345 shows true");
if ({}) console.log("{} shows true");
if ([]) console.log("[] shows true");
All of these except 0 will evaluate to true.
However, their values, when compared to true will not evaluate to true.
// logs the statement (1 and true are the same.)
if (1 == true) console.log("1==true shows true");
if (12345 == true) console.log("12345==true shows true"); // does not log
I tried in jsfiddle.net and only try in the first alert says false, the IF does not alert true.
alert({} == true) //display "false"
if({} == true)
{
alert("it's true");
}else
{
alert("it's false"); // <-- alert this
}
( snippet )
var c = false;
if(c=[] && c.length==0)alert('hi');
hi is not alerted because c is still false when it executes the second operand of &&, can someone explain how the boolean operands in if condition are executed and in what order?
I believe this is just a precedence issue - && is binding tighter than =. Your code is equivalent to:
if (c = ([] && c.length == 0))
{
alert('hi');
}
So it's assigning c the value false rather than the empty array.
Try this instead:
if ((c = []) && c.length == 0)
{
alert('hi');
}
EDIT: To address Tryptich's comment - I did try this before posting :) As CMS said, an empty array is considered true. Try this:
if (c = [])
{
alert('empty array is true');
}
or even just this:
if ([])
{
alert('empty array is true');
}
I checked the spec before posting - I was somewhat surprised that an empty array is considered true, but it is...