I was asked to findout the bugs in this function but I am not able to do...
can you tell me whtats the bug in it...
I dont see anything
am i missing anythin...
providing my code below...
I thought return statement should have ;
function average(a, b) {
return a + b / 2;
}
What result do you get from this function, and what are you expecting?
Look into operator precedence
Note that division has a higher precedence than addition. This means that the division is going to happen first, then the addition. This will give you a different result than if the addition happened first.
If you add parenthesis around the addition, you will get the result you are looking for.
function average(a, b) { return (a + b) / 2; }
Related
I am new to JS and was learning functional programming and came across the term "referential transparency". Also, I found this statement "Referential transparency says it's safe to replace a pure function with its value". Does it mean that the use of RT makes it easy for JIT compiler to replace function with its return value as long as function gets hot? Is that true?
Here's an example:
This is a pure function: it will always return the same output for the same input
const even = x => x % 2 === 0;
And let's create isTenEven() which will check wether 10 is an even number or not:
const isTenEven = () => even(10);
Since we're guaranteed that even(10) === true will always be true then we can indeed replace a function call with a value:
const isTenEven = () => true;
And your program would still work.™
However you wouldn't be able to do so if even wasn't pure!
Here's a silly example: once per month 10 won't be an even number anymore:
const even = x => (new Date()).getDate() === 15 ? false : x % 2 === 0;
Perhaps your program is excepting isTenEven() to return either true or false, so forcing it to always assume that it will return true could lead to unexpected consequences.
Of course in this particular case I'm not sure what those consequences would be but you never know... which is exactly the point.
Yes, that is exactly an advantage of RT. The compiler can not only inline a function but replace its invocations with the corresponding return value, that is it can eliminate common sub-expressions and rewrite code according to specific rules like you can rewrite formulas in math. This way of reasoning about a program is called equational reasoning and is also very helpful for the programmer.
But RT allows other optimization techniques as well, like lazy evaluation. If you want to automatically delay the evaluation of an arbitrary expression up to the point where its result is actually needed, you need the guarantee that this expression yields the same result no matter when you actually evaluate it. RT gives this guarantee.
I have been looking at this code and scratching my head at it for too long and was hoping to gain insight into how exactly the value 33 is the end result.
I know that this code goes through the conditionals to the else and decrements the value of b until it reaches the else if conditional where the b ==1 condition is met.
What I don't understand, is how within that else if, the value of b is incremented and from then on, so too does the value of 'a' until the final value of 33 is reached.
The other strange feature of this code is that after the else if has made those changes, only the else runs and the other conditionals are no longer checked.
For someone relatively new to recursion, this behavior is truly weird.
function mlt(a, b) {
debugger;
if(!(a && b)) {
return 0;
} else if (b == 1) {
return a;
} else {
return (a + mlt(a, b - 1));
}
}
console.log(mlt(3, 11));
Copying this in the browser console and running through the loops will give insight into what I am on about.
This is not an example of closure, but of recursion.
In order to understand how recursion can bring the correct result, it can help to assume for a moment that the recursive call returns the correct result and see if that makes the overall return value correct as well.
Let's take for example this main call:
mlt(20, 4)
The execution will go to the else part and perform the recursive call:
return (a + mlt(a, b - 1));
As you can derive, the recursive call comes down to mlt(20, 3). Now let's just for a moment assume that this recursive call returns the correct result, i.e. 60. See what happens in the above expression:
return (20 + 60);
This is 80, which indeed is the correct result for our original call mlt(20, 4). So we can get a feel of how this function will return the correct product for any given b if we can assume the function does it right for b-1 also.
What happens when b = 1? Then the function returns a. We can also see that this is correct. So with the previous conclusion we now can be sure that if b >= 1 the result will be correct.
Note that the function will also do it right for b = 0 as then the first if kicks in. Also note that this function does not cope well with negative values of b: in that case the function will keep recurring with b-1 and will eventually bump into a stack capacity error.
After digging around online, I found a great article which explains recursion in JS clearly for those new to the topic.
The explanations and code examples helped me with getting a better understanding.
In short, this code will plus 3, 11 times which equals 33. We reach the second conditional when 1 is subtracted by 1. Then an anonymous function returns a 11 times.
I hope it helps someone else who stumbles on this issue too.
I've been doing Project Euler 'cause reasons. At one point, I found myself wanting to compare a value with the result of a function. I've since selected a different solution, but it's left me curious. How would this work? If I were to do something like:
//javascript
if x == mathyFunction(10){
//do this
}
function mathyFunction(y){
if(y>0){
mathyFunction(y-1);
return y;
} else {
return y;
}
}
I'm aware that this isn't tail recursive or anything fancy, I'm mostly just curious how the logic works behind this.
How would the computer interpret it? Would it return true if any one of the values == x or would it only return true if all the values == x. Experimentation has left me guessing, though I'll keep digging.
You didn't specify which language you're asking about, but assuming the usual semantics of the return statement, a function can't return more than once. So if by "return all values individually", you meant something like this:
function f() {
return 1;
return 2;
...
}
Then everything after the first return is just dead code and it's the same as if the return 1 was the only return statement in there. A function call has exactly one value and that value is what you're comparing against.
If you meant that mathyFunction returns a list or other collection object, which contains the values between x and y, then x will be compared to that list. Again the semantics will depend on the language, but in most languages comparing a number to a list will either be a type error or just false.
If by returning the values individually you were referring to a yield statement (like C#'s yield return or Python's yield), then the result of the function is going to be some kind of iterator object and the same thing as in the previous paragraph applies.
I was wondering what if there's any preferable way of returning values conditionally.
And if not, if it makes any different for minified Javascript.
I was checking Google Javascript Style guide and they don't name anything about the issue. Same with Airbnb guidelines
Using multiple conditional returns:
function demo(x, y) {
if (x < y) {
return getX();
} else if (x === y) {
return 'equal';
}
return getY();
}
Or having a single return with and making use of a variable:
function demo(x, y) {
var position;
if (x < y) {
position = getX();
} else if (x === y) {
position = 'equal';
} else {
position = getY();
}
return position;
}
The following is a definition of the return statement.
The return statement stops the execution of a function and returns a value from that function.
Clearly, a conditional return would have to include a condition before that return.
About preference, as the word implies, it is really is a matter of habits.
If you're used to one syntax from, say, another language, or you just like it better - use it, as it will probably reduce syntax errors.
About minifying the code, I believe the switch/case syntax best works for simple conditions, and the ternary operation fits well for two-side conditions.
(Caution! philosophical paragraph ahead)
But again, in the end, the important thing, I believe, is that you will understand the code you write. And, with experience, you will find what suits you best.
You should concern yourself with readability. Write the code in the way that is most understandable. If you are returning from with a deeply nest condition that is likely to be confusing to future read, but if you have a series of early exits at the start of your function that is likely to make the code more readable (when compared to deep nesting). Break up big functions and leave mangling to the compilers. The Closure Compiler will produce the same results for either of your examples.
Examples:
http://closure-compiler.appspot.com/home#code%3D%252F%252F%2520%253D%253DClosureCompiler%253D%253D%250A%252F%252F%2520%2540compilation_level%2520SIMPLE_OPTIMIZATIONS%250A%252F%252F%2520%2540output_file_name%2520default.js%250A%252F%252F%2520%2540formatting%2520pretty_print%250A%252F%252F%2520%253D%253D%252FClosureCompiler%253D%253D%250A%250Afunction%2520demo1(x%252C%2520y)%2520%257B%250A%2520%2520%2520%2520var%2520position%253B%250A%250A%2520%2520%2520%2520if%2520(x%2520%253C%2520y)%2520%257B%250A%2520%2520%2520%2520%2520%2520%2520%2520position%2520%253D%2520getX()%253B%250A%2520%2520%2520%2520%257D%2520else%2520if%2520(x%2520%253D%253D%253D%2520y)%2520%257B%250A%2520%2520%2520%2520%2520%2520%2520position%2520%253D%2520'equal'%253B%250A%2520%2520%2520%2520%257D%2520else%2520%257B%250A%2520%2520%2520%2520%2520%2520%2520%2520position%2520%253D%2520getY()%253B%250A%2520%2520%2520%2520%257D%250A%2520%2520%2520%2520return%2520position%253B%250A%257D%250A%250Afunction%2520demo2(x%252C%2520y)%2520%257B%250A%2520%2520%2520if%2520(x%2520%253C%2520y)%2520%257B%250A%2520%2520%2520%2520%2520%2520%2520return%2520getX()%253B%250A%2520%2520%2520%257D%2520else%2520if%2520(x%2520%253D%253D%253D%2520y)%2520%257B%250A%2520%2520%2520%2520%2520%2520%2520return%2520'equal'%253B%250A%2520%2520%2520%257D%250A%2520%2520%2520return%2520getY()%253B%250A%257D
Use ternary/conditional operator.
In Javascript conditional operator can evaluate to an expression, not just a statement.
var result = x < y ? getX() : getY();
This starts evaluation from left and if your condition meets criteria then result will be the first portion otherwise result would be second portion.
For more conditions you have to use it like
var result = IsYoungerThan18 ? serveMilk() : IsYoungerThan21 ? serveBear() : serveWine();
So in your case it should be
var result = (x < y) ? getX() : (x == y) ? "equal" : getY();
In typescript, I have the following:
self.newId = 0;
self.GetNewId = () => {
return --self.newId;
};
My guess is that return --self.newId; does two things:
it returns the current value of self.newId
it then decreases the value of self.newId by 1. (To -1)
I assume that the next time that GetNewId is called, it will return -1 and then decrease the value to -2, etc.
Can anyone confirm
No. What you are describing is the post-decrement operator, which is written like this:
foo--
It will indeed, first evaluate the expression and then decrement the value.
This is the pre-decrement operator, which is written like this:
--foo
It will first decrement, then evaluate.
So, what this snippet will do is
it decreases the value of self.newId by 1. (To -1)
it then returns the current value of self.newId
As a mnemonic, you can just think about reading the expression left-to-right: does the operator come first or last?
Your answer / thinking about the code is close, but not quite right. See this mozilla documentation on arithmetic operations for additional details.
the line
return --self.newID
is using a prefix decrement operator.
So it subtracts before returning the value, not after the return.
The first call to GetNewId() will return -1 not 0. It will decrement from there on.