I had this question in a test.
What is the output of the following incorrect javascript code and what is the error?
num=0;
if (num > 10);
{
num = num + 10;
}
alert(num);
The possible answers:
a) Output 10. There should not be a semicolon(;) at the end of the if statement if(num > 10)
b) Output 0
There should not be quotes around the num in the alert statement alert("num");
c) Output 10. There should not be a semicolon(;) at the end of the if statement if (num > 10)
d) Does not execute at all. There is an error with the calculation num = num + 10;. num == num + 10;
My answer is:
As is it would not execute, but if we removed the semicolon after if statement, and added var it would. The output would be zero.
This is because num is not greater than 10, therefore the if statement doesn't do anything. num still = 0.
There should be no semicolon after the IF statement. var should be used in front of the num variable.
Their answer was a).the output would be 10, and there should be no semicolon after if statement.
The statement doesn't work, but if we tidy it up the answer would still never be 10.
Is the question a poorly written question? Are they wrong, or am I wrong?
A semicolon after an if condition is not a syntax error, unfortunately - it just means that the result of the if condition is not used, because no statements run if it's true.
The { immediately following it is valid syntax, despite being disconnected from the if - it's a bare block. Bare blocks are valid too, but pretty weird - they mostly just create a new scope that const and let variables declared inside do not leak out of.
num=0;
if (num > 10);
{
num = num + 10;
}
alert(num);
See how "Run code snippet" results in 10 popping up.
The quiz is correct.
Since there's a semicolon after the if statement, it essentially has no body and therefore nothing to run if it's true. You can think of it as ending at the semicolon.
Block statements (statements inside of brackets, {}) are valid in Javascript and, in this case, would just run like normal code. So the num = num + 10 runs. Since the if statement above ended at the semicolon, this code runs regardless of the result of the if statement. Think of it as having nothing to do with the if statement.
So the result is 10. And yes, you likely want to remove the semicolon after the if statement to get the desired result.
You can test it out if you want:
num=0;
if (num > 10);
{
num = num + 10;
}
alert(num);
Since there is a semicolon after the if statement, the if statement is ignored.
The statements inside the block will be executed so the below code executes :
num = num+10
And you get 10 as your answer.
Related
This is a freecodecamp problem where the string argument should be multiplied by the num argument. I understood the other methods they provided, but I'm hung up on how this one works.
repeatStringNumTimes("abc", 3);
//should return "abcabcabc"
I am trying to figure out how the last part of this function (the else statement) inherently knows to multiply the parameters together even though there is no instruction to do so. The way I see it, all it says is: x + (x, y - 1) yet somehow it's still returning correctly.
What am I missing?
function repeatStringNumTimes(str, num) {
if(num < 0)
return "";
if(num === 1)
return str;
else
return str + repeatStringNumTimes(str, num - 1);
}
This is a form of computing called "recursion". It refers to functions that can refer to themselves, thus restarting their cycles until a certain condition is met. In this case, the function is recursively calling itself num times, which in this case yields a simple repetition of its commands.
So, while experimenting in the Chrome JS Console, I found something which is a bit puzzling.
When I run, the following in the console, the console prints undefined
var i = 10;
However, when I run this, it prints 10:
j = 10
Here is a screenshot of the results in my console.
Could anyone explain to me why this difference in behavior?
That's the fundamental difference between statements and expressions. Expressions evaluate to something, statements don't.
var j = 10; is a statement (a variable statement specifically), so it does not evaluate to anything and can only be used in statement contexts.
j = 10 is an expression, so it evaluates to a value and can be included anywhere a value is expected (EG. if ( j = 10 ) or console.log( j = 10 )). Any expression can also be used on its own in a statement context since there is a type of statement called an expression statement.
In a REPL (read,evaluate,print,loop), such as Chrome's console, the result of an expression statement is printed immediately after it is evaluated, other statements such as a variable statement don't evaluate to anything so a REPL can't print anything, or, in Chrome's case, prints undefined.
Chrome will print the return value of the code you enter. This means what it prints is equivalent to console.log(WHAT_YOU_ENTER);. As commented by #elclanrs (upvoted), it's a difference between an expression j = 10 and a statement var i = 10.
Declaration does not return a value, so var i = 10 returns undefined
On the other hand, j = 10, is an assignment, which returns a value, so the console returns that value.
The console will print the result of evaluating an expression. The result of evaluating var i = 10 is undefined since var does not explicitly return something.
You can observe the same behavior with many expressions:
> console.loe(10);
10
undefined;
An assignment expression does not produce a value so again undefined is printed to the console.
As a counter-example, expressions containing mathematical operators do produce a value which is printed to the console instead of undefined:
> j = 10;
10
var i = 10 is just a statement.
It is assigning a value to variable i.
It is just declaration.It does not return a value.
when you print it it will give you an answer 10.
while if you write k = 10. It works as an expression. it will assign and return value.
My book says something and I'm not entirely sure what it means. It says that to make sure a loop executes properly, you need to include some code to change the value of the conditional expression?
What does that mean? Is that correct? I may be reading it wrong but when you have a basic Javascript loop like
if(contactsCount > 0) {
for (i = 0; i < contactsCount; i = i + 1){
var item = object[i],
name = item.name,
email = item.email;
target.innerHTML += '<p>' + name + '!</p>;
}
}
})();
Surely you aren't changing any values to make it work? I'm new to this so I'm kind of clueless.
...you need to include some code to change the value of the conditional expression? What does that mean?
That this is a bad idea:
var i = 0;
while (i < 10) {
doSomething(i);
}
Why? Because the loop will never end. i's value is never changed. Endless loops are a classic form of bug.
So what the book is saying is that you must provide for a way for the loop condition (i < 10) to change (e.g., by modifying i's value).
A bit of a tangent, but:
Sometimes you see loops where the condition seemingly can't change, e.g.:
while (true) {
// ...
}
If you find yourself reaching for something like that, stop yourself and try to find a better way. There are very rare use cases for the above, they look like this:
while (true) {
doThis();
doThat();
if (someCondition) {
break;
}
doAnotherThing();
}
...so in that case, the controlling condition is actually in the middle, and the one in the looping statement itself isn't really the condition. This is almost always poor practice, but in very rare situations they can be the right thing to do.
It also says that you can have other statements on the same line as the "if statement", is that right?
Yes, it is. JavaScript doesn't care about lines at all (except when it's doing a form of error-correction for you called Automatic Semicolon Insertion; then lines matter because linebreaks stand in for semicolons as part of the error-correction algorithm). All of these are valid and they all do the same thing:
// 1
if (a < b) {
alert("a is less than b");
foo();
}
// 2
if (a < b) { alert("a is less than b"); foo(); }
// 3
if (a < b)
{
alert("a is less than b");
foo();
}
// 4
if (a < b)
{ alert("a is less than b");
foo; }
Because JavaScript doesn't care about lines at all, they're a matter of style.
By far, the most common style for the above is #1.
Separately, if you have just a single statement in the control-flow statement's body, the block (the {...}) is optional. These do the same thing:
// 1
if (a < b) {
alert("a is less than b");
}
// 2
if (a < b)
alert("a is less than b");
// 3
if (a < b) alert("a is less than b");
So using {...} for a single statement in the body is also, technically, a matter of style. In practice, however, always using blocks leads to fewer bugs in your code. If you leave off the blocks, it will eventually bite you when you add a second statement and forget to add a block:
if (a < b)
alert("a is less than b");
foo();
In the above, foo() is always called, because it's not in the body of the if. That code does this:
if (a < b) {
alert("a is less than b");
}
foo();
In a for loop you should really use the (i++) shorthand but the way your doing it (i=i+1) will work fine as well.
Since I don't have your full source code here is an example...
Here is the JSFiddle demo
//JAVASCRIPT
//animals array
var animals = ['cat','dog','fish','bird','tiger'];
//loop through the animals array
for (i = 0; i < animals.length; i++){
console.log(animals[i]);
}
I can put a return anywhere such as in a function, in an if block, case block.
How come this doesn't work:
(x == "good") ? (return("works")):"";
UPDATE: I know I can do this:
return (x == "good") ? ("works"):"";
Just want to know why the first case isn't acceptable.
It's because the grammar of a ternary operation is this:
condition ? expr1 : expr2
And a return statement isn't technically considered an expression.
Edit: here's some more info. The above explains it in terms of the grammar of the language, but here's a little bit about the reasoning of why.
I've actually dug into this before, because I've always thought it would be cool to be able to do stuff like:
someFlag && return;
Rather than
if (someFlag) return;
The problem, however, is that expressions always need to evaluate to something. This requirement is at odds with the role of the return statement, however, which along with (optionally) returning a result, also immediately terminates execution of the current function. This termination of the current function is logically inconsistent with the need to evaluate the value of the return statement itself, if it were indeed an expression.
Given that inconsistency, the language authors apparently chose to not allow return statements to act as expressions. Hope I managed to word that in a way that makes sense.
are you trying to do this:
return (x == "good") ? "works":"";
return isn't a function, so return("works") isn't correct.
alternatively you could also do:
var x = "bad";
var y = (x=="good")? "works" : "";
return y;
but this is more verbose. So to answer your question, you can put return anywhere in a function, but anything after it won't be executed. so
function x ()
{
var str = "";
return "I love puppies.";
str = "me too!" //this won't ever execute, because return exits the function.
}
The one exception to this is variable declaration, because variables are automatically declared at the beginning no matter where you put them.
function y (){
return "";
var x;
}
is really:
function y (){
var x;
return "";
}
The return keyword should come first:
return (x == "good") ? "works": "";
The reason is that return x; is a statement. You can't use (return x) as an expression.
All expressions can be used where a statement is expected, but not all statements can be used where an expression is expected.
The return keyword marks the beginning of a statement. It is not an expression, which you could use with the ternary operator.
Based off of this grammar for javascript, The ternary operator is defined as :
OrExpression ? AssignmentExpression : AssignmentExpression
Whereas return is a statement (well, the beginning of one anyways).
In any case messing with control flow in an "expressive" (read: "I want to be clever") form like ternary expressions would not be recommended by anyone I know. an if statement is the same amount of characters:
if(x==good) return x;
(x==good)?(return x)
Because "Almost everything is an expression" hasn't made it into the language yet.
Are you saying if x is "good", then return, otherwise do nothing else? In that case,
if (x == "good") return "works";
does the trick. Furthermore, return is not a function, it is a javascript token, so no parentheses should be used with return.
All the answers that begin with "return" are doing different behavior from what I think the OP intended in his ternary operation. I'm guessing the OP wants
x == "good" ? return "works" : "";
to mean
if(x == "good") {
return works;
}
else {
""; //does nothing because the statement ""; has no side effects
}
It doesn't do this because the format is
statement1 ? statement2 : statement3;
All statements may have side-effects but only the return value (in the case of statement1, just the truthiness of it) are considered by the ternary operator.
Even though the ? : is best read in terms of "if" and "then," when thinking closer to the level of syntax it should be thought of as an expression that factors into side-effects and a return value. If you understand the difference between x++ and ++x, you will be able to understand the ternary operator.
By way of example, here are some illegal statements that are illegal for the same reason.
if( (return 5) == 5) {
//...
}
if (loadUserStats(return userId)) == "FAILED") {
throw error("oops");
}
x = return y++;
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