Search code examples
javascriptjavascript-objects

Displaying functions, objects & arrays on a chrome browser


We have used both Notepad++ and Brackets.io, and have the same issue with both.

We can display a variable like the code below:

var storedVariable = 2+2;
alert(storedVaribale);

When we try to display a function or object the page is blank:

 function Andrewsfuntion (x=0,x<100,x++){
 document.write(x);
 }

 beer = {
 Name: "Heineken",
 Country: "Australia",
 Price: 7.50
 }

The html code:

<!DOCTYPE html>
<html>

<head>
<title> Scrath Pad </title>
<script type="text/javascript" src="scratchpad.js"></script>
<h1> Hello World </h1>
</head>

<body>
<div container = class> 
<p> I don't know how to code </p>
</div>
<script> 


function Andrewsfuntion (x=0,x<100,x++){
document.write(x);
}

var x;
Andrewsfuntion();

</script>
</body>
</html>

Solution

  • Functions and Loops

    From your code, it is not particularly clear what you are trying to do.

    A function is simply a wrapper for code, so that you can use it multiple times.

    What you seem to be trying to write, however, is a for loop (that is, a block of code that repeats some actions numerous times). If you want to make a loop that prints out the numbers from 0 to 100, you can do it like this:

    for (var i=0;i<100;i++) {
      document.write(i);
     }

    (you'd probably want to add line breaks or some other kind of delimiter so that the numbers are all seperate).

    However, a function would look like this:

    function AndrewsFunction() {
      document.write("hello, world!");
    }
    
    AndrewsFunction();

    There, you have just wrapped up other code and then called it to run it, whereas in the for loop, you have wrapped up other code and i number of times.


    Displaying Object Fields

    With regards to displaying information from an object, you would have to simply specify what information you want to display from the object, for example:

     function AndrewsFunction () {
       document.write(beer.Name);
     }
    
     beer = {
     Name: "Heineken",
     Country: "Australia",
     Price: 7.50
     }
     
     AndrewsFunction();

    There, you can see we are getting the Name field from the beer object, and then printing it to the page.


    Next Steps

    I would recommend that you take a look at a Javascript book or online tutorial. Some that come to mind:

    A quick Google search should come up with a lot more.