Given a number the program should return a sequence of operations using only *3 or +5 to get to the number, thus there are two paths to take. How do this program know which function call to make when it calls itself? And how does it know how many times to call each path. In other words I dont understand how the OR operator is being used to determine which call to find() to use and how many of each.
function findSequence(goal) {
// we start at 1, and history is a string that will keep track of the operations
function find(start, history) {
// case when start and goal is 1.
if (start == goal)
return history; // return string containg 1
// case when we build start past what we needed
else if (start > goal)
return null;
else
// Dont understand this part!
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)");
}
return find(1, "1");
}
document.write(findSequence(13));
The || operator checks the truth value of the left operand. Interestingly, the || expression does not evaluate to true or false. If the truth value is true, the expression evaluates to that left operand. If it is not, then it evaluates to the right operand. Example:
> 5 || 10
5
> 5 || 0
5
> 0 || 10
10
> 0 || undefined
undefined
Thus a || b is actually equivalent to a ? a : b. Similarly, a && b is actually equivalent to a ? b : a:
> 0 && 10
0
> 0 && undefined
0
> 5 && 10
10
> 5 && undefined
undefined
Truth value for non-boolean values is determined in the JavaScript specification:
Undefined -> False
Null -> False
String -> False if empty string, True otherwise
Object > True
EDIT: Oh, as mattedgod points out, as soon as the expression evaluates to a result, the rest of the expression does not get evaluated at all. For example:
> function fail() { throw "I failed!"; }
> fail()
XXX "I failed!"
> 5 || fail()
5
> 0 && fail()
0
No failure happens in the above cases, but in the following they do:
> 0 || fail()
XXX "I failed!"
> 5 && fail()
XXX "I failed!"
Thus, if you have two calls to find() like find(...) || find(...), if the result of the first call has a true truth value, then its result will be returned and the second one won't execute at all. If the result of the first call has a false truth value, then the second call will execute and the expression evaluates to whatever that result is.
This is relying on a property of JavaScript (and many other languages) called "short-circuiting."
If you think about it, if you are evaluating something to be true and it is A || B, if A is true, then the whole expression will be true, there's no sense checking B. The opposite is true for &&, if A is false and you are evaluating A && B, the whole expression is false so no sense to bother with B.
In your example, if the first call to find succeeds, it will not execute the second one. However, if the first call does not succeed (I am guessing it returns false or null or something that evaluates to JS false), the second call will get executed.
Related
Please also describe that why this statement is executing that way.
I'm confused because < operator has higher precedence in the statement below. After execution of the x > 0 the execution should go for && operator but it is not executing. So I'm confused about what the execution order is and why it is executing in that way.
Thanks for your time!
The code is following:
let x = 1;
x > 0 || alert() && "hii"
If you take a look at the operators precedence.
> has a highest priority
&& is the next one by priority
|| is the next one by priority
So expression is executed like:
(x > 0) || (alert() && "hii")
In this case x > 0 is true. Because JavaScript || short-circuits if the first operand is truthy, the second operand will not be evaluated.
Its like:
fun1() || func2()
If the return value of fun1() is truthy, than func2() will not be executed at all.
There is no need to use the right side of the || because the left side is already truthy, so no matter what the right side would be, it couldn't change the outcome anyway (both true || true and true || false would evaluate to true). Therefore, nothing other than x > 0 needs to be evaluated to get an unambiguous result, alert() && "hii" is skipped and the return value is true (the result of x > 0). (This is called short-circuiting or conditional evaluation.) See docs.
If you tried this :
let x = 1;
x > 0 || alert() && false
The output would be true, this is because && is executed before the || operator, "hii" is evaluated as true so this what confused you to think that there is something wrong, as ( true || alert() && true will give the same result as true || (alert() && true).
How the 'return' to give me true or false without an 'if' statment like in the first example?
Example'1':
function isEven(){
if(num % 2 === 0){
return true;
} else {
return false;
}
}
And it works, but then my teacher shorten it up like this (ex-'2'):
function isEven(){
return num % 2 === 0
}
You can return anything from the function. Please refer to the Example below to understand it.
function myFunction(val) {
console.log(test(val))
}
function test(val){
if(val==1) return 'testing';
if(val == 2) return true;
if(val == 3) return 1>2;
if(val == 4) return 2%3 == 0;
}
<button onclick="myFunction(1)">Test1</button>
<button onclick="myFunction(2)">Test2</button>
<button onclick="myFunction(3)">Test3</button>
<button onclick="myFunction(4)">Test4</button>
not a real answer, just trying to help, so don't upvote please!
I think the easiest way of understanding the basics of programming is to go back to daily life examples, so here is one:
You are talking to a friend, lets call him Bob. Bob owns an ice cream shop. It's summer. You want ice cream, so you ask him if you can get one. Bob tells you:
If there is Ice left, i can give you some, otherwise i can't.
function canIGetIceCream() {
if(isIceCreamLeft) {
return true;
} else {
return false;
}
}
However, Bob could also shorten his answer without changing the meaning:
Depends on the ice left
function canIGetIceCream() {
return isIceCreamLeft;
}
Booelans are just values, just like numbers or strings. In the first example if isIceCreamLeft is true, it will enter the first if branch and then return true, otherwise if it is false it will return false. Instead you could just return the value the boolean is holding like in the second example.
You don't really ask it by using an if statement. An if statement just checks if what's between the brackets ( ) is either true or false. Like how an addition 1 + 2 results in 3, something like 3 === 2 results in false. You can view it as a normal mathematical problem which has an answer. When your computer evaluates:
num % 2 === 0
It calculates num % 2 and checks if that's equal to 0. This can be either true or false. These are both boolean values, and are the same as in your first example. So what your first example is really doing is checking if the expression is either true or false and then returning that exact value, like so:
var num = 2;
if(num % 2 === 0){
return true;
}
After evaluation, this will basically result in:
if(true){
return true;
}
See how it's easier to just leave out the if statement and return the result of num % 2 === 0?
The thing you need to understand here is how operators work.
Operators operate on operands. An operator and one or more operands form an expression. Expressions are evaluated.
The return statement takes an expression and returns the value that the expression evaluates to. For example, 1 + 2 evaluates to 3.
Comparison and logical operators, like ==, <, and &&, generally evaluates to true or false. These work similarly: true && false evaluates to false, 1 == 1 evaluates to true.
Therefore, return num % 2 == 0 is completely valid because when the code is executed, num % 2 will be evaluated, then the whole expression will be evaluated to either true or false. You can think of the whole statement becoming
return true;
or
return false;
after the expression is evaluated.
You have an evaluation here of
num % 2 === 0
The code will check if the remainder of num divided by 2 (num % 2) is equal to 0. This can be true or false, hence it will return true of false.
Why does the expression 1 && 2 evaluate as 2?
console.log("1 && 2 = " + (1 && 2));
&& (and operator) returns the last (right-side) value as long as the chain is "truthy".
if you would try 0 && 2 -> the result would be 0 (which is "falsy")
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical_operators
According to MDN:
expr1 && expr2 returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
Because 1 can be evaluated to true, 1 && 2 returns 2.
According to this page:
Why 1 && 2 == 2
AND returns the first falsy value or the last value if none were found.
OR returns the first truthy one.
For multiple operators in same statement:
precedence of the AND && operator is higher than OR ||, so it executes before OR.
alert( 5 || 1 && 0 ); // 5
Because its and, all the values need to be evaluated only up to the first 0, and the value of the last evaluation is returned, and it's the last one.
Although not directly relevant here, note that there's a difference between bitwise and logical operators. The former tests bits that are the same and only return those, the latter reduces to only true (!=0) or false (=0), so contrary to intuition, bitwise AND and AND are not interchangable unless the values are exactly 0 or 1.
In JavaScript, is it possible to place a Conditional statement after an Or operator? If so, why is the following fails for me?
var value = 1 || true ? 2 : 3; // equals to 2
When I set value to be equals to [1 || true ? 2 : 3], I get an unexpected result.
The result that get is that:
value == 2
I've expected value to be equals to 1 (value= = 1), since 1 is truthy, and the Or statement should have return 1. The conditional statement is not even supposed to be executed.
The only way val can be equals to 2 (val == 2) is if the Or operator is behaving not as expected, and runs the second part of the Or statement and the Conditional statement that is in it.
Why is it behaving that way?
I've expected value to be equals to 1 (value = 1), since 1 is truthy
To get that, you need parens:
var value = 1 || (true ? 2 : 3);
// --------------^------------^
Without them, the || is between 1 and true, and then the conditional operator's first operand is the result of that (which is 1).
This is because || has higher precedence than the conditional operator (just); here's a table on MDN.
Because Logical OR has precedence over the Conditional operator. Then your statement is actually interpreted as:
(1 || true) ? 2 : 3;
Which obviously evaluates to 2.
See MDN
Code-snippet 1:
if ( !x ) { /* do stuff */ }
Code-snippet 2:
if ( x == 0 ) { /* do stuff */ }
For what values of x do these two code-snippets differ?
I am asking because, although I read the chapter on == in the spec, I still find it hard to deal with situations like the above (where it is combined with ToBoolean coercion).
btw, I want to know this just for the sake of knowing it (I want to understand the language), so don't bother telling me about === or asking me what x is.
Update: I corrected the fist snippet. I meant !x.
[] == 0 is true; ![] is false
null == 0 is false; !null is true
NaN == 0 is false; !NaN is true
undefined == 0 is false; !undefined is true
!x will check whether x is "falsy".
x == 0 will check whether x is "equivalent to" 0.
Both of these terms are defined by the Javascript spec.
The following will give you true for the first and false for the second snippet:
NaN
null
undefined
And these will give you false for the first and true for the second snippet:
[]
"0" and any other string that converts to 0 using Number(x) such as "00", "000", "+0", and "-0" (which I will now call "noughty strings")
an array containing a single element that is 0, null, undefined or an empty or noughty string.
For everything else you'll get the same result for both snippets, although there may be one or two more cases I haven't thought of.
Here's an interesting one with regard to a non-empty String that has only space characters:
!!" "; // true
" " == true; // false
This is because when you do a == comparison, and one of the values being compared is a number or a boolean, an attempt is made to convert the other value to a number.
The reason you get the different result is that a string with only space characters converts to the number 0 (or falsey), while a string with only spaces converted to boolean via !! is seen as a non-empty string, and therefore true.
So:
var x = " ";
alert( !x ); // false
alert( x == 0 ); // true
EDIT:
Probably the key thing to remember is that when comparing a number or boolean to a non number type, == uses toNumber conversion if possible, while ! uses toBoolean conversion. They're not always the same.
It is easy to see the result of the toBoolean conversion using !!. As in:
alert( !![] ); // true
But you can't really see the result of the toNumber conversion when using ==.
You can, however, use the unary + to see the result of a toNumber conversion. As in:
alert( +[] ); // 0
I'm pretty sure that what happens in the case of an Array, is that it first gets a toString call. Therefore:
// ---------------------toString result-------toNumber result (from string)
alert( +[] ); // "" 0
alert( +[""] ); // "" 0
alert( +[" "] ); // " " 0
alert( +[0] ); // "0" 0
alert( +["0"] ); // "0" 0
alert( +["3"] ); // "3" 3
alert( +[3,4] ); // "3,4" NaN
Short answer: the two are almost always the same but not 100% the same.
An example would be (!'0') which is false whereas ('0' == 0) is true
Details:
From: http://www.joeyjavas.com/2007/08/04/javascript-true-false-checking-for-boolean-values/
Checking if a value is true or false is simple in JavaScript. All values evaluate to true, except for:
0
-0
null
undefined
NaN
empty string
false
Therefore, (!x) will be true for all of the above values of x and only those.
As for (x == 0), it will be true for any value of x which - when converted according to "==" conversion rules - is converted to 0 when compared to a number (for example, Boolean false value). Other examples that compare true to ==0 are objects which generate 0 from their valueOf() methods, or a string '0', or an empty Array ([])
The first test will succeed when x is non-zero, or evaluates to an object (as opposed to null or undefined), or is a non-empty string. So if x is 0 then the condition fails, but if it is "0" then it succeeds.
The second test will succeed when x is convertible to 0. This means it must not be null, undefined, or an object to pass this test. And it may be "0" or "".
In other words, these conditionals are not opposites. The value "0" will pass both tests, for example.
Code Snippet 1 will execute if x is "falsy" value. In Javascript, this means 0, -0, null, undefined, NaN, "", or false. Code Snippet 2, however, will only execute if x is zero. Unlike the first condition, this does not include other "falsy" values.
The difference between the two is that
if ( x ) { ... }
Tests whether x is "truthy"
Whereas
if ( x == 0 ) { ... }
Does type coercion between x and 0.
I presume you mean something like
if (x == 0) vs if (!x)
The main difference is type coercion of x to a number vs checking if x is falsy.
Clearly NaN itself will never equal 0 since its not a number. undefined will also coerce to NaN so that is not caught by == 0 I can't give a good explanation why null is not caught by 0 since Number(null) == 0
After some lookups, have to change my awnser.
There's no simple logic, implicit equality operations follows an algorithm.
http://interglacial.com/javascript_spec/a-11.html#a-11.9.3
I can't sum it up better then what the algoritm describes, it would just get more confusing.
So it's (!x) is equivalent to (typeof x === false) aka (not true)
And (x == 0) gets compared by algorithm.