-2

I wrote

function factorial(n) {
    if (n === 0) {
        return 1;
    }
    return n * factorial(n - 1); 
}

console.log(factorial(3));

the codes is calculate factorial.

But I wrote the code in jsfiddle and run, nothing happens. And I wrote html like

<script>
   function factorial(n) {
           ・
       ・
  console.log(factorial(3));
</script>

and when it is browsed in GoogleChrome,nothing shows in console.I want to see 6 in console.log.6 is calculated by 1*2*3. What is wrong in my codes?How should I fix this?

Deepesh kumar Gupta
  • 884
  • 2
  • 11
  • 29
user7523656
  • 197
  • 3
  • 3
  • 12

3 Answers3

1

It runs for me. Try putting your script tag inside <body>.

<html>
  <head><title>Does it run?</title></head>
<body>
  <h1>Test</h1>

  <script>
  function factorial(n) {
    if (n === 0) {
      return 1;
    }
    return n * factorial(n - 1); 
  }
  console.log(factorial(3));
  </script>

</body>
</html>
Dan
  • 2,455
  • 3
  • 19
  • 53
1

Your code is fine, but jsfiddle, by default, doesn't display console output.

You can fix this by clicking on the left and adding a resource such as https://getfirebug.com/firebug-lite-debug.js then run your code and you should see the console output.

See this question for reference --> Print Var in JsFiddle

kyle
  • 691
  • 1
  • 7
  • 17
  • Edit: This may be a duplicate. The poster was asking if there was something wrong with his/her code. I explained that the problem was with the interface and showed a link to a question explaining how to enable a feature that he/she was looking for. – kyle Jun 10 '18 at 01:52
  • @JaromandaX you're actually correct literally, though, personally you seem like you're trying to be offensive. I edited my answer to better help OP. – kyle Jun 10 '18 at 02:03
  • @JaromandaX I'll stand by that your comments are trying to be offensive without asking for clarification or pointing out problems in the post. – kyle Jun 10 '18 at 02:13
  • @JaromandaX You deleted both of your previous comments because they were offensive. Now, what exactly are you trying to accomplish? There's a reason stackoverflow has a reputation for being hostile towards new users. Let's try to be part of the solution, not the problem. – kyle Jun 10 '18 at 02:20
  • Put it this way - you edited your error in response to my comment - so clearly my comment was correct - if you take a look at the "accepted" answer however, it's hard to say what the OP was having an issue with - I believe they put the script in the script box in jsfiddle with script tags!! – Jaromanda X Jun 10 '18 at 02:24
0

For jsFiddle one approach that works reasonably well is creating an output div and a log function

A simple way would be

HTML

<div id="output"><div>

CSS

#output{ white-space: pre-line;}

JavaScript

let output = document.querySelector("#output"),
log = (t) => output.textContent += t + "\r\n";
Stand__Sure
  • 253
  • 1
  • 13