I am currently studying if condition statement and it is one of my weakest topic ever. Here in this code below, there are two if conditions and I would like to know, how do we find the output of this? I know how to get the output when there is one if. But what about having two if?
function exercise3(){
var x, y, z;
x = 20;
y = 30;
z = 50;
if ((x - 10) < y) {
if (y - 5 > x) {
alert (z - x);
}
else {
alert (z - 5);
}
}
}
exercise3();
This is referred as Nested If statement. Basically you deal with the most outer block first before the going into the inner block. You would only go into the inner block if the condition in the statement is true.
Your statement condition is true
if ((x - 10) < y) {
...
}
Hence you would proceed to read through.
Take note generally to make it more readable better use If else statements rather than if alone as the execution will proceed to check the next if statement with is actually block one and block two (one by one) bringing about slow execution in long written statements.
Ref: https://www.w3schools.com/js/js_if_else.asp
Cheers, happy learning and happy coding.
That is the same as this, if it helps you understand better. The below snippet is just for example purpose, do not follow that. You need to use nested if conditionals.
function exercise3(){
var x, y, z;
x = 20;
y = 30;
z = 50;
// The first if and nested if from your snippet
if ((x - 10) < y) && (y - 5) > x) {
alert(z - x);
}
// The first if and nested else from your snippet
if ((x - 10) < y && (y - 5) <= x) {
alert (z - 5);
}
}
exercise3();
Related
When ran it gives an alert box with undefined written, Can you help me debug this code? I am unable to find the correct error you can check it and please help me. It must give the derivative at point x=10 for f(x)=x^2+1 by using smaller and smaller h till desired accuracy is reached.
function f(x) {
return x * x + 1;
}
var iter = [];
var h = 0;
var ddx = 0;
iter[0] = ((f(10 + h) - f(10)) / h);
function d_dx(p) {
for (i = 1; i < 20; i++) {
iter[i] = ((f(p + h) - f(p)) / h);
if (iter[i] = iter[i - 1]) {
break;
var ddx = iter[i];
} else {
h = h / 2;
}
}
return ddx;
}
console.log(d_dx(10));
Your iter array will be NaN. h will be always 0 and you divide by 0.
if (iter[i] = iter[i - 1]) statement is wrong, you should use === to compare values. You cannot use break in if if you want to loop this code multiple times. There are many mistakes in your code.
var ddx is not reachable after break. That's why it is returning undefined. And one more thing, you are using assignment instead of conditional expression.(correct comparison is - if (iter[i] == iter[i - 1])) )
You have used var ddx out of scope while you are returning the ddx.
I'm going through a JavaScript book and have been executing code samples using Node.js. I've been writing files then running node file.js.
Normally, I use semicolons writing JavaScript, but I'm following the book's style.
I came across a error while executing one of the code samples, and I can't figure out why it happens.
Executing:
var x = 2
var y = 3
(x == 2) && (y == 3)
(x > 3) || (y < 3)
Results in the error:
TypeError: 3 is not a function
If I add a ; after line 2, e.g.
var x = 2
var y = 3;
(x == 2) && (y == 3)
(x > 3) || (y < 3)
It results in the error:
TypeError: (y == 3) is not a function
However, if I place a ; after the third line as well, e.g.
var x = 2
var y = 3;
(x == 2) && (y == 3);
(x > 3) || (y < 3)
Things work fine.
Or if I run each line (individually) in the Node.js command line, everything works fine.
It's probably just my misunderstanding of Node.js or JavaScript. But I couldn't find another similar situation online.
I'm using OS X 10.11.1 and Node.js v5.2.0 (installed through Homebrew).
This would happen in any JavaScript environment, not just node. There are specific rules as to when semi-colons can be omitted. This is why the majority if the community advocates against omitting semi-colons.
This is being executed as a single statement:
var y = 3
(x == 2) && (y == 3)
(x > 3) || (y < 3)
Statements are delineated by context (or semi-colon), not by whitespace or newlines.
var y = parseInt('10px');
is the same as
var y = parseInt
('10px');
is the same as
var y = parseInt ('10px');
So when you try to execute var y = 3 (x == 2), the JIT is interpreting 3 as a function, due to the parenthesis that follow it.
If the next line starts with a '(' then the statement is not terminated by a new line. Therefore, you need a ';' or some other token to specify that the statement has ended.
You can read more about javascript and semicolons here and here.
Your first error is occurring because the code is being interrupted as:
var y = 3(x == 2)
The second error if from the code being interrupted as:
(y == 3)(x > 3)
These are invalid.
Adding the semicolons changes your code to
var y = 3;(x == 2)
and
(y == 3);(x > 3)
These are valid.
Javascript uses the semicolon and not newline to denote the end of a statement and the possible beginning of another. So, when you tried to execute:
var x = 2
var y = 3
(x == 2) && (y == 3)
(x > 3) || (y < 3)
It interpreted it as:
var x = 2 var y = 3(x==2) && (y==3)(x > 3) || (y<3)
Which seemed like you were trying to initialize y with the value of function 3(x=2) which is wrong syntax and semantics for a function declaration in javascript.
When you put a semicolon after the second line, it interpreted lines 1 and 2 as you meant them to be interpreted, but again a similar issue arose in lines 3 and 4, which were fixed once you added the semicolons.
You only need semicolons where javascript cannot tell the end of one statement and the beginning of another. You can omit them, but the general rule is something like this.
As you can see here,
The source
a = b + c
(d + e).print()
is not transformed by automatic semicolon insertion, because the parenthesised expression that begins the second line can be interpreted as an argument list for a function call:
a = b +c(d + e).print()
In the circumstance that an assignment statement must begin with a left parenthesis, it is a good idea for the programmer to provide an explicit semicolon at the end of the preceding statement rather than to rely on automatic semicolon insertion.
It's a well known pitfall when coding without semicolons in JavaScript and that also behaves the same for Node.js.
I don't know much about JavaScript, here is the code I have:
<script language="JavaScript">
var x = 10
function startClock() {
if (x !== ' ') {
x = x - 1
document.frm.clock.value = x
setTimeout("startClock()", 1000)
}
if (x == 0) {
x = ' ';
document.frm.clock.value = x;
success.location.href = "success.php";
}
}
</script>
<body onLoad(startClock);>
affected iframe:
<input name="clock" size="3" readonly="readonly"
<iframe name="success" src="blank.htm"></iframe>
when the timer counts down, success.php is loaded twice. I know thise because 1.)It inserts data into my DB twice, 2.)I can actually see the loading symbol in the tab reloading a second.
When I change the function to something like:
<script language="JavaScript">
var x = 10
var y = 1
function startClock() {
if (x !== 'Fin') {
x = x - y
document.frm.clock.value = x
setTimeout("startClock()", 1000)
}
if (x == 0) {
x = 'Fin';
document.frm.clock.value = x;
success.location.href = "success.php";
}
}
</script>
...the page is only loaded once.
Can anyone tell me what is happening here? I also tried using '0' in place of ' ' and got the same double execution...
In Javascript there are TWO comparison operators:
"==" -- means equal to
"===" means "exactly equal to" -- which means that the value and the TYPE must be the same
I suspect (although I dind't bother to test the theory) that if you use "===" rather than "==" in your original code you will find it works as you intended. However, there are a number of things that need fixing -- 1) you are inconsistent with using ";", 2) the code should be structured to ensure that on any given iteration it can only "restart" the timer OR fire the sucess and NEVER both. Here is a cleaner version:
<script language="JavaScript">
// 10 iterations at 1 second intervals
var x = 10;
function startClock() {
document.frm.clock.value = --x;
if (x <= 0) {
document.frm.clock.value = x;
success.location.href = "success.php";
} else {
setTimeout("startClock()", 1000);
}
} // startClock
</script>
<body onLoad(startClock);>
First a couple of things. There's a number of "sloppy" coding practices in your example (missing semicolons for instance). While the code may run, it could improve with some jslint help.
So look at the case when x = 1. You decrement x so now x = 0. You then call setTimeout which will wait 1 second and then call your method named startClock. However, setTimeout doesn't block your execution. So immediately after setTimeout is called with x = 0, the code below it is executed where you set x to ' ' (and load your page). Now one second after that code has run, your method is called again due to the timer firing. Since x is now ' ', the top block is skipped and you fall into x == 0 block a second time.
Change it to:
if (x == 0) { // note this is now first
x = ' ';
document.frm.clock.value = x;
success.location.href = "success.php";
} else if (x !== ' ') { // note the else/if
x = x - 1;
document.frm.clock.value = x;
setTimeout("startClock()", 1000)
}
Otherwise, when x is 1, a timeout for startClock() will be set, AND the location will be loaded. Then, the timeout will fire, loading the page again (since x = ' ' and ' ' == 0 returns true).
It is probably better practice to say:
if (x === 0) { // note the ===
x = ' ';
document.frm.clock.value = x;
success.location.href = "success.php";
} else if (x !== ' ') {
x = x - 1;
document.frm.clock.value = x;
setTimeout("startClock()", 1000)
}
Because you don't need the truth conversion that == does for you.
Your example with 'Fin' instead of ' ' worked, because on the startClock() call after the location had been loaded, x was 'Fin', and ('Fin' == 0) is false.
What I would like to do is replace the two if statements with a single mathematical formula. I can't for the life of me figure out how, as mathematics was never my strong point. Any advice would be greatly appreciated.
<script>
var x, y, z;
x = 200;
y = 100;
i = 0;
while(z != y) {
i++;
if (x < y) z = x + i;
if (x > y) z = x - i;
document.write(z + "<br>");
}
</script>
Edit: the real code looks like this. It's not too pretty, was hoping I could shrink it down to two lines.
if (prevposX < newposX) posX = prevposX + animStep_;
if (prevposX > newposX) posX = prevposX - animStep_;
if (prevposY < newposY) posY = prevposY + animStep_;
if (prevposY > newposY) posY = prevposY - animStep_;
Edit:
It has been a while, but I believe the Modulus (%) operator would have helped me. I've now moved on to a library to do graphics for me so I didn't need it in the end.
You can make use of a ternary operator
z = x + ((x<y) ? i : -i)
This assumes that when x >= y then you want to -i. If you want to stick exactly to your original you need a second ternary operator, which gets a bit messy:
z = x + ((x<y) ? i : ((x>y) ? -i : 0))
Frankly, it might be clearer to just keep it on 2 lines with 2 if statements like you already have.
I seem to handle special cases like this somewhat frequently. There's got to be a more concise syntax or construct:
var x = solveForX(); /* some slow calculation here */
if (x < 0)
{
x = 0;
}
This is equivalent, but doesn't feel any more elegant:
var x;
x = (x = solveForX()) < 0 ? 0 : x;
Maybe there's a bit shift trick?
Update: I ran some benchmarks to compare my two favorite answers - the one I accepted, and Peter Ajtai's. Turns out Peter's is quite a bit faster! Running 1,000,000 iterations of each (I also ran a version that caches Math.max to see how much time the lookup contributed) shows that Peter's runs in under half the time of the Math.max version, even with max caching.
That said, even the "slowest" method is still quite fast.
How about
var x = Math.max(solveForX(), 0);
Something like:
x = Math.max(0, solveForX());
(x < 0) && (x = 0);
Edit: Removed the if statement. Thanks Andreas.
This is one line, and it's clear what it does (in my personal opinion) - if you're familiar with boolean short circuit evaluation.
The above makes use of boolean short circuit evaluation. This can be very useful in certain situations (especially pointer arithmetic in C++, but boolean short circuit evaluation also works in Javascript).
x = 0 only evaluates if x < 0.
Here are two examples:
This alerts 1:
<script type="text/javascript">
var x = 1;
(x < 0) && (x = 0);
alert(x);
</script>
This alerts 0:
<script type="text/javascript">
var x = -1;
(x < 0) && (x = 0);
alert(x);
</script>
I'd decorate the original solveForX function.
function returnNonNegative(fn) {
function _f() {
var x = fn();
if (x < 0) {
x = 0;
}
return x;
}
return _f;
}
solveForX = returnNonNegative(solveForX);
In this particular case, using Math.max seems to be fine, but this pattern provides a generic solution for this type of problems.
The accepted answer is perfect. If you want to accomplish the same without a function call, I believe that this is most concise:
var x;
(x = solveForX()) > 0 || (x = 0);
(In Safari, this implementation is a whole 7% faster than Math.max(), which is probably not worth caring about)
I think that this way is pretty nice!
var x = Math.max(solveForX(), 0);
Good luck!