Intro to JavaScript: Outputting Data

JavaScript is a really great language for anyone learning web development. Today we will talk about how to output JavaScript data. There are four ways we can do this: 

  • Write into an HTML element 
  • Write to the browser console 
  • Write into a pop-up box 
  • Write into the page

Write to an HTML element:

document.getElementById(status).innerHTML = “You are Awesome”;

Breaking this down it reads like so: Hi page, when you read this get the HTML tag with the ID status, and inside the HTML tag write “You are awesome”. Your actual HTML would just be <div id=status></div> and JavaScript will add the “You are awesome” text inside that tag. 


As you can see JavaScript syntax, for the most part, is quite simple once you break it down. But don’t worry, even today I freak out when I see a lot of JavaScript lines bundled together.


Writing to the console:

console.log(output);

This output (you guessed it) outputs into the browser console. Normally this is good for debugging. Again the syntax is just “Hey console, log this message.” You can also do console.dir which prints the element in a JSON-like tree vs. in the HTML format as found with console.log. If you are not sure what the console is, enable your browser's developer tools and you should see an option to view console.


Writing to an Alert Box:

window.alert(output);

This is generally used to alert the user in a way that breaks out of the normal UI and is really effective in grabbing the user’s attention. It's also possible you have seen such elements when visiting websites that are full of annoying ads.


Writing to the Page:

document.write(output);

This is normally used for testing and would replace the existing page’s HTML with the data from the JavaScript function. In very few cases will you ever find yourself needing to use this but it’s still good to know.


In the end, as you embark on building your JS functions and applications, no doubt at some point you will end up using one of these functions.