Javascript - for loops & if-else statements - syntax error - javascript

//my code (with extra semi-colons)
for (var i=1; i < 11; i++) {
if (i<4) {
console.log("Your number is between 1 & 3.");
} else if (i>7) {
console.log("Your number is between 8 & 10.");
} else if {
console.log("Your number is between 4 & 7.");
}
}
I understand I do not need the semi-colon after the (), but I'm confused as to why not. Why exactly is the semi-colon not needed?
Any help would be greatly appreciated!

It's not needed because the JS engine can work out the end of a statement.
Google around for ASI, automatic semi-colon insertion.
Here's one: http://cjihrig.com/blog/the-dangers-of-javascripts-automatic-semicolon-insertion/

semicolons are used to signal the end of a statement like this a=b+c;. The conditional statements like if and loops like for run on group of statements. So their syntax is not really complete without the group of statements they supposed to run. If you enter ; after if or for they consider it as a statement and execute it. But their effect wouldn't be applied to block of code after the ;

You last statement of else if doesn't contain any condition, hence you get the syntax error. The compiler marks this right away as well...
your fixed code should look like this:
for (var i = 1; i < 11; i++) {
if (i < 4) {
console.log("Your number is between 1 & 3.");
} else if (i > 7) {
console.log("Your number is between 8 & 10.");
} else {
console.log("Your number is between 4 & 7.");
}
}

Related

After Effects: Javascript - Undefined value used in the expression(Could be out of range array subscript)

I'm not a programmer by any means. I'm an animator trying to use JS expressions in After Effects. I'm getting an "Undefined value used in expression" error on line 1 where I define a variable.I already showed it to my friend on discord who is a cs major, and he had no clue what was wrong with it.
Here's just a paste of the code if you need it:
var count = 1;
if (framesToTime(time) % 12 == 0) {
count = count + 1
if (count % 2 == 0){
thisProperty = 95
} else {
thisProperty = 20
};
} ;
Ok I don't know why the hell this fixed it, but I changed the name of the variable from "count" to just "x" and it works now. Go figure
Try it.
var count = 1;
if (framesToTime(time) % 12 == 0) {
count = count + 1;
if (count % 2 == 0){
thisProperty = 95;
} else {
thisProperty = 20;
}
}
thisProperty;
In your code, thisProperty has become an ordinary variable. If you write its name at the end of the code, then its value will be assigned to the property.
In AE, if there is nothing inside an if statement or the if statement contains malformed/error code you will receive this error. Put a temp value inside the curly braces or something to process and ensure nothing inside will throw an error.
I also received this error with this:
pastTime = timeToFrames(time)-1;
curPos = transform.xPosition;
pastPos = transform.xPosition.valueAtTime(framesToTime(pastTime));
if (curPos-pastPos[0] != 0) {
// Here is the problem in my case. added a value here 99 to fix until finished testing.
}
else {
effect("Angle Control")("Angle")
}
if/else statements are strict
The syntax for if/else statements is strict in the JavaScript engine
and need to be written for standardized JavaScript.
https://helpx.adobe.com/after-effects/using/expression-language-reference.html*
I got this error because there was a missing semicolon.

Infinite While loop mod 3

I basically just want to print numbers a list of numbers a skip multiples of 3. I got it to work but the initial way i tried it did not work and i do not understand why, just need someone to please explain why it doesn't work and goes into an infinite loop.
This is the problem, why does it go into an infinite loop? I am clearly missing a key concept about code, if someone could help thanks.
var i = 0;
while (i <= 10) {
if (i % 3 == 0) {
continue;
}
document.write( i + "</br>");
i++;
}
I know you can do it this way.
while (i <= 10)
{
if (i % 3 != 0) {
document.write("Number is " + i + "<br />");
}
i++
}
If we ignore the code producing the output and look only at the code checking and modifying i, it might become a little more clear why it's not working. It also helps to format our code for extra clarity.
var i = 0;
while (i <= 10) {
if (i % 3 == 0) {
continue;
}
i++;
}
Start with i = 0.
i <= 10 is true. Enter the loop.
i % 3 == 0 is true. Enter the if block.
continue;. Go straight to the top of the while loop again. Do not pass i++;. Do not collect 1.
Lather. Rinse. Repeat (infinitely).
continue jumps to the next iteration and doesnt complete the rest of your code in the while. So i is not being incremented but rather staying as 0 becuase you wrote continue before incrementing the i. so therefore it is in an endless loop, it is always less than 10

Freecodecamp - Counting Cards

I know there are a number of ways to complete this challenge and I can simply a different approach to pass the requirement however I am struggling to understand what's wrong with my code.
Challenge - https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/counting-cards/
Any help would be much appreciated.
var count = 0;
function cc(card) {
// Only change code below this line
if (card < 7){
count++;
} else if (card < 10){
count+=0;
} else (count--;)
if (count > 0){
return count + " Bet";
} else (
return count + " Hold";
)
// Only change code above this line
}
// Add/remove calls to test your function.
// Note: Only the last will display
cc(2); cc(3); cc(7); cc('K'); cc('A');
Firstly, when you try to execute your code, you should be seeing a Syntax Error, pointing to the semicolon in (count--;). The reason for this is: else expects a statements, if it sees a parenthesis it means the statement is an expression, and in an expression, semicolons can't appear inside parentheses (this is rather simplified). The correct way to write it is either without parentheses (generally frowned upon) as else count--;, or with curly braces: else { count--; }.
When you fix that error, there will be another one of the same kind, as you seem to systematically use parentheses instead of curly braces after else.
After that, your code kind of works. There's questionable comparisons of card, that can be a letter or a number, with an integer, but it coincidentally works the way you hope it does (because 'K', 'Q' and 'J' happen to be evaluated as greater than 7 and 10.) It would be better to not rely on such magic, and have a translation table between letters and values - or at least, if you're going to rely on magic, comment so that readers are aware you are aware of the magic. Also, count+=0 is a void statement, it does nothing, and could have been left out. That leaves you with an empty else if, but that's not an error. However, it would probably be much more readable if you had if (card < 7) { count--; } else if (card >= 10) { count++; }.
stupid mistake's.
answer is below:
var count = 0;
function cc(card) {
// Only change code below this line
if (card < 7){
count++;
} else if (card < 10){
count;
} else {count--;
}
if (count > 0){
return count + " Bet"
} else {
return count + " Hold"
}
// Only change code above this line
}

JavaScript - If statement inside a loop issues

function rot13(str) {
var yahoo = [];
for (var i = 0; i < str.length; i++) {
if (str.charCodeAt(i) > 64 && str.charCodeAt[i] < 91){continue;}{
var cnet = str.charCodeAt(i);
yahoo.push(cnet);
} else {
var j = str.charCodeAt(i);
yahoo.push(j);
}
}
var ugh = yahoo.toString();
return ugh;
}
rot13("SERR PBQR PNZC");
Attempting to use an if else statement inside a for loop and having some issues with the else statement (Getting "Syntax error: unexpected token else"). Main goal right now is to try to manipulate the strings alphabet characters while passing the other characters through (ie. spaces, exclamation points etc.). Sure there is an easier way of doing that but really just wondering what is the issue with writing an if else statement inside a loop and where im going wrong. Appreciate the help
You've got two code bodies after your if:
if (str.charCodeAt(i) > 64 && str.charCodeAt[i] < 91)
{continue;} // actual body of the if
{ // just a random block of code
var cnet = str.charCodeAt(i);
yahoo.push(cnet);
}
The second one is not part of the if at all, because you only get one code block for the if. That's why else is "unexpected".
You are attempting to invoke a statement after you have already completed the if statement. Your if results in the continue;and then does something else before you call the else. Try to refactor the continue;. It doesn't have anything to do with the for loop:)
Attempting to use an if else statement inside a for loop and having some issues with the else statement (Getting "Syntax error: unexpected token else").
but really just wondering what is the issue with writing an if else statement inside a loop and where im going wrong
that you don't write an if..else statement, but an if statement and a code block where you try to add your else statement; and this else-statement doesn't make sense there.
your code reads like this:
//this is your condition
if (str.charCodeAt(i) > 64 && str.charCodeAt[i] < 91){
continue;
}
//and this is an anonymous code block; anonymous, because you could name it
{
var cnet = str.charCodeAt(i);
yahoo.push(cnet);
//and such code-blocks have no `else`,
//that's why you get the error,
//this else doesn't belong to the condition above
} else {
var j = str.charCodeAt(i);
yahoo.push(j);
}
your problem is the {continue;} part that changes the whole menaing of your blocks to what I've described
Sure there is an easier way of doing that
yes, you could use String#replace, and replace the letters a-m with n-z and vice versa
//a little helper
const replace = (needle, replacement) => value => String(value).replace(needle, replacement);
//the definition of `rot13` as a String replacement
const rot13 = replace(
/[a-m]|([n-z])/gi,
(char,down) => String.fromCharCode(char.charCodeAt(0) + (down? -13: 13))
);
let s = "SERR PBQR PNZC";
console.log("input: %s\noutput: %s", s, rot13(s));
explanation: match[0] always contains the whole matched string, here this is the char; and I've added a group around [n-z] so that match[1] aka. down is filled when the character is a n-z, but not if the character is a-m.
Therefore I know, if down is filled, I have to do char.charCodeAt(0) - 13 otherwise char.charCodeAt(0) + 13

else statement within nested if statements. How does this code know which else statement to execute?

I get the nested if loops (same as using && operator), but how does this code here know which conditions to execute with no conditions and just back to back else statements? One of them is within the nested if statements. I can tell that's obviously why this works the way it does, I just don't get how. Also, I know how to write this in several more readable ways testing multiple conditions. Please just explain what is happening with this code here. How does it know to output "You are too old" or "You are too young?"
var age = prompt("Please enter Your age here :");
var min_age=18;
var max_age=40;
if(age>=min_age){
if(age<=max_age){
console.log("You meet the requirements for this competition");
}else{
console.log("You are too old");
}
}else{
console.log("You are too young");
}
The if-then-else ambiguity is known for a long time. All languages have solved it by defining that an else will match the first perceding if. So:
if (a)
if (b)
x = 1;
else
x = 2;
resolves to:
if (a) {
if (b) {
x = 1;
}
else {
x = 2;
}
}
EDIT by Nisar's reuest:
The if statement is defined as:
if (<condition>) <statement> [else <statement>]
This means that a <statement> in the above may also be an if statement. So, for example:
if (<condition>) if (<condition>) [else <statement>] [else <statement>]
As each else part is optional, the compiler has no way of knowing when it sees an else part to which if it belongs. To solve that the language defines that an else always matches the first preceding if.
The brackets {} set the limit.
Try to think in pseudocode, look beyond the characters and think about what is happening.
Reading in order:
If you are old enough
If your are not too old
'You meet the requirements for this competition'
OTHERWISE
'You are too old'
END
OTHERWISE
'You are too young'
END
Note how indentation can help see the limits of the conditions. Each indented part can be separated.
Firstly, let's indent your code.
var age = prompt("Please enter Your age here :");
var min_age = 18;
var max_age = 40;
if (age >= min_age)
{
if (age <= max_age)
{
console.log("You meet the requirements for this competition");
}
else
{
console.log("You are too old");
}
}
else
{
console.log("You are too young");
}
Starting off..
var age = prompt("Please enter Your age here :");
Let's say you enter 21 in the prompt box, so age=21
We initialize
var min_age = 18;
var max_age = 40;
Now let's look at the first if condition.
if (age >= min_age)
If you substitute the values,this translates to
if (21 >= 18)
This is true,therefore we go inside the if block and not to the else.
The next line is.
if (age <= max_age)
This translates to
if (21 <= 40)
Considering this is also true, we print You meet the requirements for this competition.
The most important take-away from this is, indent your code, and the rest becomes pretty simple.
There are just 3 Options
too young
correct age
too old
First Check - is the person old enough?
if(age>=min_age)
Second check - is the person too old?
if(age<=max_age)
the only possible option left after this if statment is FALSE :
too old

Categories