I'm having some frustration with this code. I may not be seeing it.
I keep getting either an "Unexpected Token" or "ILLEGAL" error (the latter which completely preplexed me, considering I've never seen an error like that before in my life.
I've been double checking the syntax and I'm thinking it may be something I'm just not catching?
function fizzBuzz(n) {
2 for (i = 0; i<=n; i++) {
3 if (n%3===0) {
4 print ("fizz")
5 }
6 if (n%5===0) {
7 print ("buzz")
8 }
9 if (i%3 !== 0 && i%5 !== 0) {
10 return [i];
11 }
12 }
13 }
14
15
16 fizzBuzz(100);
I'd be thankful for the help! <3
You need some changes:
remove line numbers,
check first for 'fizz buzz' value and use console.log for output. Then use continue statement for jumping to top for next loop,
use i instead of n for checking.
function fizzBuzz(n) {
for (i = 0; i <= n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("fizz buzz");
continue;
}
if (i % 3 === 0) {
console.log("fizz");
continue;
}
if (i % 5 === 0) {
console.log("buzz");
continue;
}
console.log(i);
}
}
fizzBuzz(100);
function fizzBuzz(n) {
2 for (i = 0; i<=n; i++) {
3 if (n%3===0) { You're checking if the maximum number (n) is divisible by 3.
4 print ("fizz") You should be checking i.
5 }
6 if (n%5===0) { You're checking if the maximum number (n) is divisible by 5.
7 print ("buzz") You should be checking i.
8 }
9 if (i%3 !== 0 && i%5 !== 0) {
10 return [i]; You're returning an array with a single element: i.
11 } You should print i instead.
12 }
13 }
14
15
16 fizzBuzz(100);
The line numbers are what's causing the "ILLEGAL" error. Remove them.
print in JavaScript opens the print dialog to literally print paper out of a printer. Use console.log
If a number is divisible by both 3 and 5, fizzbuzz should be printed. Your code prints fizz and buzz on separate lines.
Working version ( https://www.youtube.com/watch?v=QPZ0pIK_wsc ) :
function fizzBuzz(n) {
for (var i = 0; i <= n; i++) {
var printVal = "";
if (i % 3 === 0) {
printVal += "fizz";
}
if (i % 5 === 0) {
printVal += "buzz";
}
if (printVal === "") {
printVal = i;
}
console.log(printVal);
}
}
fizzBuzz(100);
Lets decrease number of if statements, I have seen many fizzbuzzs - I would like to try another approach
const fizzBuzz = (i = 0, ret) => {
while (++i, ret = '', i <= 100) {
if (i % 3 === 0) {
ret += `fizz`
}
if (i % 5 === 0) {
ret += `buzz`
}
console.log(ret || i)
}
}
fizzBuzz()
The most important part is console.log(ret || i) - empty string is falsy value, so console will log ret if there is some value or current i value
If you're trying to print to your browser's console, use console.log() instead of print(), since print() will open the printer preview in a browser. I'm using Chrome. Remember to check the console by pressing F12 and clicking on "console" in case you've created a html file that includes your javascript script.
Since you are iterating i until it reaches the value of n, you if statements should look like:
if(i%3===0){
// your code...
}
Based on your code, it seems like you want to check for a value that is not a multiple of 3 && a multiple of 5. However, the fizzbuzz challenge requires to print fizzbuzz when encountering a number that is both a multiple of 3 && a multiple of 5. So, you'll need to add the following condition:
if (i%3 === 0 && i%5 === 0) {
console.log("fizzbuzz");
continue; /* Continue may or may not be necessary depending on your program's logic. Continue allows to re-enter the loop
without checking for the remaining if statements. If you use continue, this condition must be the first if statement inside the loop */
}
Your function doesn't need to return anything, since you're using console.log() to visualize the values in each loop iteration. That's why you need to change return [i] for console.log(i).
Don't give up and keep trying!
If you have further questions, I'll be glad to help you.
Related
I am doing an exercise, the problem is that my if/else structure does not work properly and I do not know why.
Here is the exercise statement and my code
Your task is to write a function, fizzBuzz, that accepts a number and returns a string:
'fizz' if the number is divisible by 3;
'buzz' if the number is divisible by 5;
'fizzbuzz' if the number is divisible by both 3 and 5.
'{number}' if the number doesn't fulfil any of the above conditions.
function fizzBuzz(number) {
if (number % 3 === 0) {
return "fizz"
};
if (number % 5 === 0) {
return "buzz"
};
if (number % 3 === 0 && number % 5 === 0) {
return "fizzbuz"
};
else return number
}
Try a little mental debugging. Look at your code and run different values through it in your mind:
What happens if you run the value 6 through it?
What happens if you run the value 10 through it?
What happens if you run the value 15 through it?
Ask yourself, "How could I fix this?" (hint: order of operations is important).
Something like this would do what you expect:
function fizzBuzz(n) {
const fizz = n % 3 ? '' : 'fizz' ;
const buzz = n % 5 ? '' : 'buzz' ;
return !fizz && !buzz ? '{number}' : `${fizz}${buzz}` ;
}
or this:
function fizzBuzz( n ) {
let s;
if ( n % 3 === 0 ) {
s = 'fizz' ;
if ( n % 5 === 0 ) {
s = 'fizzbuzz' ;
}
} else if ( n % 5 == 0 ) {
s = 'buzz' ;
} else {
s = '{number}' ;
}
return s;
}
This does [at most] 2 divisions and 2 comparisions.
The former does 2 divisions and 3-4 comparisons, so it is nominally less efficient.
But I know which version I'd rather look at.
The problem is, if a number is divisible by 5 and 3 (ex 15) "fizz" would only be returned (as a factor of 3) because every block {...} terminates the function with a return (this technique is called a "short-circuit", which isn't a bad practice). So you need to put the 5 and 3 condition first. Also that condition had an undefined variable called solution so that would've been the first error. One minor thing is that each block {...} was suffixed with a semi-colon: ; which is just bad formatting but it doesn't affect functionality.
function fB(number) {
if (number % 3 === 0 && number % 5 === 0) {
return "fizzbizz";
}
if (number % 3 === 0) {
return "fizz";
}
if (number % 5 === 0) {
return "bizz";
}
return number;
}
console.log(fB(15));
console.log(fB(575));
console.log(fB(49));
console.log(fB(51));
console.log(fB(80));
console.log(fB(375));
console.log(fB(99));
console.log(fB(Infinity));
This question already has answers here:
Difference between console.log and return in javascript? [closed]
(7 answers)
Closed 1 year ago.
I get different outputs when I use console.log() in my function vs when I use the return statement.
When I run the function with the return statement I get a one word output which is one of the following: 'fizz' 'buzz' or 'fizzbuzz', but when I run the function using console.log the output is counting to the limit and saying 'fizz' 'buzz' or 'fizzbuzz' whenever it comes across a multiple of 3, 5 or both/ why is this so?
input = fizzBuzz(100)
console.log(input)
function fizzBuzz(limit){
for (let i = 0; i <= limit; ++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)
}
input = fizzBuzz(100)
console.log(input)
function fizzBuzz(limit){
for (let i = 0; i <= limit; ++i) {
if (i % 3 === 0 && i % 5 === 0)
return 'fizzbuzz'
else if (i % 3 === 0)
return 'fizz'
else if (i % 5 === 0)
return 'buzz'
else return i
}
}
I think it is because the return statement stops the function from executing anything further but I am not sure, still new and self teaching!
return evaluates its argument (if supplied) and ends the execution of the containing function immediately.
console.log evaluates its argument and prints it, continuing the execution of the function it's called from.
So in your example with return, the fact that you're in a for-loop that goes limit times doesn't matter, because you'll only go through it once and return from fizzBuzz.
Putting it all together with another example:
function print_dog() {
console.log('dog');
return;
console.log('cat');
}
If you then call print_dog(), you'll see the output dog, but you won't see the output cat, because return ends execution of print_dog before it can get to console.log('cat');
You are correct in stating that it is because the return statement exits the function.
This is also the case in python,java, and many other languages.
Cheers!
Here's what each different function does:
function fizzBuzz(limit) {
for (let i = 0; i <= limit; ++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)
}
This iterates through to limit, and console.logs the FizzBuzz test result each time.
function fizzBuzz(limit){
for (let i = 0; i <= limit; ++i) {
if (i % 3 === 0 && i % 5 === 0)
return 'fizzbuzz'
else if (i % 3 === 0)
return 'fizz'
else if (i % 5 === 0)
return 'buzz'
else return i
}
}
This iterates through to limit, and returns a single value from the function - the result of the FizzBuzz test on the first iteration.
So essentially, one function logs all the FizzBuzz results to the console, and the other returns one FizzBuzz result, which you are logging to the console manually.
Yes, you are thinking on the correct lines.
A return statement in a function will return a value and stop further execution. Where as Console.log() is a side effect producing function that will print the arguments supplied to it in the console.
Having a console.log() inside a function is like calling a function within a function.
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++).
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">
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.