I am trying to write a program in javascript in which there is a list of products in an array, and they are sorted in alphabetical order. However, when I enter the code into notepad, and load it up in the website format, it just displays the code I have entered, with no formatting
var products = ["Printer","Tablet","Router","Speakers","Mouse"];
Arrays.sort(products);
System.out.println(Arrays.toString(products));
This is the code exactly as it is in notepad, and in the website bit, it is displayed as one long line of all the programming
3 Answers 3
You have to surround your code with a script tag:
<script type="text/javascript">Your_code_here</script>
Furthermore System.out.println and Arrays.toString are Java functions. It seems like you have Java confused with JavaScript. I think what you are trying to do is:
<!DOCTYPE html>
<html>
<body>
<script>
var products = ["Printer", "Tablet", "Router", "Speakers", "Mouse"];
products.sort();
var productsString = products.join(" ");
document.write(productsString);
</script>
</body>
</html>
Comments
If you point a browser at a URL which returns JavaScript source code, then it will display the JavaScript source code (generally not as a single line those, that suggests a further error in which you are serving it to the browser with a Content-Type: text/html header instead of Content-Type: application/javascript).
If you want to execute client side JavaScript then you need to write an HTML document and import the JavaScript using a <script> element.
Your code will then fail because Arrays and System will be undefined.
Comments
Javascript not like java ..to use helper functions in javascript as ..sort,filter,reserve....you can use underscore.js library