javascript two conditions in if statement - javascript

I'm trying to write code that checks two conditions in an if statement but no luck.
for(var num = 1; num<=100;num +=1)
{if (num % 3==0) and (num % 5==0) console.log("fizzbuzz");
else if (num % 3==0) console.log("fizz");
else if(num % 5==0) console.log("buzz");
else console.log(num);}

First, change and to &&,
Also, your if statement does not have parenthesis like that:
for(var num = 1; num<=100;num +=1){
if ((num % 3==0) && (num % 5==0)) console.log("fizzbuzz");
else if (num % 3==0) console.log("fizz");
else if(num % 5==0) console.log("buzz");
else console.log(num);
}
Then it should work like a charm!
You need to work your indentation too.

Use && instead of and.
for (var num = 1; num <= 50; num += 1) {
if (num % 3 == 0 && num % 5 == 0) console.log("fizzbuzz");
else if (num % 3 == 0) console.log("fizz");
else if (num % 5 == 0) console.log("buzz");
else console.log(num);
}

Indentation. If you use IDE (like webstorm), there should be an option to auto format the code. FYI: indentation plays a very big role in understanding your own code in some time (for example, right after you write it:))
I wouldn't call it js becase there's logical AND operator: &&, not and. At first glance it can be even treated as a portion of pseudocode, bad pseudocode
if statement has structure like if (condition) operator, so when you want to check multiple conditions, you should wrap them with parenthesis: if (condition1 && condition2 && ... && conditionN). All the conditions are finally equvalent to a single condition that's checked after evaluation.
Of course, if statement allows you not to wrap operators with curly brases: if (condition) some operator;. But it's more readable and understandable if you write if (condition) {operator}. For example, when you change your code and want to add some more operators, it will be more secured from some confusing mistakes. Let's say you want to write smth like this:
if(everythingIsOk)informUser;
Let's say you'd like to add a message if everything is ok. You could write this:
if (everythingIsOk)
informUser;
writeMessage;
In the example above you make the program to write the message anyway because it's a separate instruction. If you wrote initially if (everythingIsOk){informUser} it would be easier to just add one more instruction that must be executed in this particular case. More than that, it's more readable.
You would probably be surprised, but the following is valid too:
if (everythingIsOk);
The following is more readable because at least it makes people think that you haven't forgotten about your construction somewhere in the middle:
if (everythingIsOk){}
And finally, if you want to emphasize that nothing should be done in some cases, that's the approach (just fyi):
if (everythingIsOk){/* Do nothing, no code here is not a mistake! */}
So your code would be more readable if you wrote it like this:
for (var num = 1; num <= 100; num += 1) {
if ((num % 3 == 0) && (num % 5 == 0)) {
console.log("fizzbuzz");
} else if (num % 3 == 0) {
console.log("fizz");
} else if (num % 5 == 0) {
console.log("buzz");
} else {
console.log(num);
}
}
I'd recommend you read at least examples you learn more accurately.

Related

JS - Why does the order of this if/else matter?

Why would this not work if I took the first "if" statement and put it as the third "else if" statement? Just want to understand. Thanks!
function fizzBuzz(num) {
if ((num % 3 === 0) && (num % 5 === 0)) {
return 'fizzbuzz';
} else if (num % 3 === 0) {
return 'fizz';
} else if (num % 5 === 0) {
return 'buzz';
} else {
return num;
}
// if num is divisible by 3 return 'fizz'
// if num is divisible by 5 return 'buzz'
// if num is divisible by 3 & 5 return 'fizzbuzz'
// otherwise return num
}
If-else-if statement only work until one of the if statements becomes true.
This scenario prevents to check other "else if" conditions.
In your second scenario if modulus of "num" is 0 for 3 OR 5, it will stop checking other else if statements,
It is necessary to prioritize the sequence of if-else-if conditions.
So a if/else if statement works so that as soon as one of the ifs is true, it executes the code inside that if statement and then skips the rest of the ifs and else statements. In this case, however, the return ends the function and therefore it skips the rest of the code in the method.
If else if checks each condition on by one. If any of the conditional blocks executes, the rest of the conditions won't work.
function fizzBuzz(num) {
if ((num % 3 === 0) && (num % 5 === 0)) {
return 'fizzbuzz';
} else if (num % 3 === 0) {
return 'fizz';
} else if (num % 5 === 0) {
return 'buzz';
} else {
return num;
}
// if num is divisible by 3 return 'fizz'
// if num is divisible by 5 return 'buzz'
// if num is divisible by 3 & 5 return 'fizzbuzz'
// otherwise return num
}
In your example, if you put the first condition in the third block, i.e, else if, if the number is divisible by either 3 or, 5, the corresponding conditional block work and resulting in skipping the third block. The order of execution is important in if-else-if ladder.
Yes Remember that if/else-if/else executes in order and will stop when it finds an acceptable case. In your example, if (num % 3 === 0) you'll return return 'fizz' and that condition is true. So This is (num % 5 === 0) and (num % 3 === 0) && (num % 5 === 0)) are not mutually exclusive - they can both be true, so the order matters.

JS - Appending a logged sequence of numbers

I've made a sequence of numbers from 0 to 20 and I want to change the sequence so once it comes up with a multiple of 3 and 5 it logs 'FizzBuzz' to the terminal then carries on with the rest of the numbers up to 20. My problem is once I have changed the number to the string the rest of the terms in the sequence come up with NaN. I know the problem with my code is that I'm changing the number to a string and you cannot perform addition to a string which is why NaN comes up. I'm pretty new to this so any thoughts on how to do complete this would be greatly appreciated. I've tried using .append() but I'm pretty sure I'm using it incorrectly.
My code thus far;
var increment = function(number)
{
for (var i = 1; i <= 20; i++)
{
console.log(number++)
if ((number % 3 === 0) && (number % 5 === 0))
{
number = "FizzBuzz"
console.log("FizzBuzz");
}
else if (number % 3 === 0)
{
console.log("Fizz");
}
else if (number % 5 === 0)
{
console.log("Buzz");
}
else
{}
}
}
increment(1)
When you find a multiple of 3 and 5, you are setting number to "FizzBuzz", which does not have a ++ operator. On the next iteration, you call ++ on number, which is now "FizzBuzz", so it logs NaN.
If you don't set number to "FizzBuzz" it should work fine.
This would do it
var increment = function()
{
for (var i = 1; i <= 20; i++)
{
if ((i % 3 === 0) && (i % 5 === 0))
{
console.log("FizzBuzz");
}
else if (i % 3 === 0)
{
console.log("Fizz");
}
else if (i % 5 === 0)
{
console.log("Buzz");
}
else{
console.log(i)
}
}
}
increment()
There's no need to pass the number parameter, since your for loop is already set to increment by 1 (i++).

for cycle and if statements

I've encountered some misundertanding. There is a for cycle with some if statements:
for (var number = 1; number < 100; number++) {
if (number % 3 == 0 && number % 5 == 0)
console.log(number + "fizzbuzz");
if (number % 5 == 0)
console.log(number + " buzz");
if (number % 3 == 0)
console.log(number + " fizz");
else console.log(number);
}
The output of this code is 1, 2, 3 fizz, 4, 5 buzz, etc. So it's what expected.
But if we delete braces the output will be like this:
15fizzbuzz
30fizzbuzz
45fizzbuzz
60fizzbuzz
75fizzbuzz
90fizzbuzz
100 buzz
100
Also, there is a second implementation of this program(with the right-way if-else statements):
for (var number = 1; number < 100; number++)
if (number % 3 == 0 && number % 5 == 0)
console.log(number + "fizzbuzz");
else if (number % 5 == 0)
console.log(number + "buzz");
else if (number % 3 == 0)
console.log(number + "fizz");
else console.log(number);
Notice that there are no braces too, but the output is ok.
Can you explain, what's the difference?
When you miss a semicolon or brackets, javascript tries to insert it on its own, & at times can produce some weird results like this. (Which is correct by the rules, just humans & machine don't agree on how to process it :D )
When you remove braces of for loop javascript tries to puts braces in code & run it, this is different that how you expect it to behave thus you are confused!
What you wrote & read:
for (var number = 1; number < 100; number++)
if (number % 3 == 0 && number % 5 == 0)
console.log(number + "fizzbuzz");
if (number % 5 == 0)
console.log(number + " buzz");
if (number % 3 == 0)
console.log(number + " fizz");
else console.log(number);
What javascript did with it & executes:
for (var number = 1; number < 100; number++){ //runs loop here
if (number % 3 == 0 && number % 5 == 0){
console.log(number + "fizzbuzz"); //prints for first condition
}
}
//now number is 100!
if (number % 5 == 0){
console.log(number + " buzz"); //prints for second condition once cause 100%5==0 is true
}
if (number % 3 == 0){
console.log(number + " fizz");
}
else{
console.log(number); //prints for this else condition once cause 100%3==0 is false
}
Which is perfectly valid & there is no error or bug here!
This happens because if the is no immediate else after if then javascript terminate that statement there, but if you use else...if then it continues that statement till if find a else or a statement not followed by else
If you want to play with this type of behaviour use Google Closure Compiler to see how code is interpreted by machine.
NOTE: As #carcigenicate suggest in comments, Always use braces!
As a lot of comments pointed out, its the lack of elses ( or blocks ) in your first code that make it going wrong.
//a bit shortified to make it clearer
var a=true,b=true;
if(a && b){ }// will be executed
if(a){ } //will be executed
if(b){} //will be executed
//vs.
if(a&&b){}//will be executed
else if(a){}//else => not executed
else if(b){}//else => not executed
However, it might be better to restructure your code as its quite repetitive:
for (var number = 1; number < 100; number++)
console.log(number+ (number % 3 == 0?"fizz":"")+ (number % 5 == 0?"buzz":""));
So log the number, if its a multiple of 3 add "fizz" and if its an multiple of 5 add "buzz"...
The syntax of a for loop is for (statementA; statementB; statementC) statementD. Statements can be grouped together with {}, so {statement, statement, ...} can be used where a single statement is expected.
for (var number = 1; number < 100; number++) {
if (number % 3 == 0 && number % 5 == 0)
console.log(number + "fizzbuzz");
if (number % 5 == 0)
console.log(number + " buzz");
In this case statementA is var number = 1, statementB is number < 100, and statementC is number++ and statementD is if (number % 3 == 0 && number % 5 == 0) console.log(number + "fizzbuzz"). The second if is another statement that does not belong to the for loop. If you want for the second if statement to belong to the for loop, you need to use {} to group the statements together.
The syntax of a if statement is if (expression) statement or if (expression) else statement. Using several if else aligned you are able to pass the first statement to the for loop, the second statement is going to belong to the first if that still belongs to the for loop. That is why the last example works without {}.
It is important to note that the code may work, but it is still bad code. It is recommended to use {} to group the statement from below for for, while, and if even if it is a single statement.
You may want to learn the JavaScript syntax before trying to understand JavaScript code. https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps

For loop where i need to print out number from 1 to 20

So what i need to do in this task is to print out the numbers from 1-20. And the code should also fulfill the rules:
For numbers divisible by 3, print out "Fizz".
For numbers divisible by 5, print out "Buzz".
For numbers divisible by both 3 and 5, print out "FizzBuzz" in the
console.
Otherwise, just print out the number.
for ( var i = 0 ; i < 20 ; i++) {
if ( i % 3) {
console.log("Fizz");
}
else if( i % 5) {
console.log("Buzz");
}
else if(i % 3 || 5) {
console.log("FizzBuzz");
}
else {
console.log(i);
}
}
The error i am getting :"You printed FizzBuzz when you should have printed 1"
You have some errors in your code
for (var i = 1; i < 21; i++) { // needs to start with 1
// You should check this condition first
if (i % 3 == 0 && i % 5 == 0) { //needs '==' and '&&' operator
console.log("FizzBuzz");
} else if (i % 3 == 0) { // you need to check for equality to zero
console.log("Fizz");
} else if (i % 5 == 0) { // here too, needs '=='
console.log("Buzz");
} else {
console.log(i);
}
}
A one line solution
for(i=1;i<=20;i++)console.log((!(i%3)?'Fizz':'')+(!(i%5)?'Buzz':'') || i);
Tests for matches using two conditional (ternary) operators. The results are concatenated, eliminating the need for a third "matches both" test. A logical OR is used to print the index when the string result is empty, i.e., no matches. A single console statement outputs the final result.
As for the errors in OP's code, #elclanrs already pointed out the problem in a comment. else if(i % 3 || 5) is incorrect (suggest printing the result in the console to see why).
Run the snippet to try
// Here we output to the screen rather than the console
for(i=1;i<=20;i++)window.stdout.innerHTML+='<li>'+((!(i%3)?'Fizz':'')+(!(i%5)?'Buzz':'')||i);
<ol id="stdout">

Why doesn't my if / else statement work properly?

I am trying to iterate through the arrays in the numbers variable, and if a number can be divided by 3 I'm logging "fizz", if it can be divided by 5 I'm logging "buzz", and if a number can be divided by 3 + 5, or 15, I'm logging "fizzbuzz"
Here is the working code:
var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for (var i = 1; i <= numbers.length; i++) {
if (i % 15 === 0) {
console.log("FizzBuzz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else {
console.log(i);
}
};
Here is my original code, which doesn't log "fizzbuzz"
var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for (var i = 1; i <= numbers.length; i++) {
if (i % 5 === 0) {
console.log("Buzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 15 === 0) {
console.log("FizzBuzz");
} else {
console.log(i);
}
};
Why does the (i % 15 === 0) condition need to precede the other two conditions? Shouldn't it not matter?
The number 15 is divisible by both 3 and 5. If you don't test it first, then you'll never get there.
So let's take 30 as an example. If you check 15 first, you'll see that it's divisible by 15. However, if you check either 5 or 3 first, it'll be flagged as being divisible by either of those.
After one of your conditions evaluates as true, you break out of that if-block and don't evaluate following else-if/else statements. If you want the rest of them to evaluate you can make them if statements instead of else-if's.
It's because firstly the computer checks for the first statement and then the others as you use the ELSE IF which means, to check the statement after the first one is false. Use IF for all instead.

Categories