ThiepLV ThiepLV - 3 months ago 5x
Javascript Question

Include JavaScript file in HTML won't work as <script … />

I have two files in a folder :

  1. main.html

  2. main.js

The main.js as follows:

function revertNum(num){
var strNum = new String(num);
var strArr = strNum.split();
var result = '';
for(var i = strArr.length - 1; i > 0; i--){
result += strArr[i];
return result;
var x = revertNum(32132);

The main.html as follows:

<meta charset="utf-8" />
<script src="main.js"></script>

I expected console of browser will show reverse of 32132, but it only show SRC of main.js file.

Here is the output
enter image description here


There are two errors in your code:

  1. Your split line should give "" as a delimiter: var strArr = str.split("");

  2. Your loop condition should be i >= 0, not i > 0

You're seeing just a blank in the console output because the first error means that strArr is an array with just one element: "32132", and the second error means you stop before processing the last (only) element in the array and return "".

In future, you can find this out for yourself by using the debugger built into your browser:

  1. Add debugger; at the top of main.js -- later, when you're more familiar with the tools, you won't need to do that, but for now it's the easiest way to get you into the debugger

  2. Open a tab

  3. Use the menus to open your "developer tools" (it's F12 or Ctrl+Shift+I or Cmd+Shift+I on most browsers) Now that I see you're using Firefox, from the menus it's Web Developer > Debugger (Ctrl+Shift+S, although Ctrl+Shift+I works to open dev tools, then you just click the Debugger tab).

  4. Open your page. That should switch you to the "Source" or "Sources" or "Debugger" tab in the developer tools with your source code in front of you. (It's "Debugger" in Firefox's built-in tools.)

  5. Use the various tools there to step through the code statement-by-statement, look at the values of variables, etc.

You'll want to find the Developer Tools website for your browser's tools to find out how to use them. This question and its answers have a lot of useful links to those. Firefox's built-in tools are covered here.