JavaScript 3

JavaScript 3

Chapter 3 with Examples

Hi Everyone!, My name is Arinze Calistus, the purpose of this blog is to teach you all about JavaScript/Programming.

JavaScript Displaying Output.

Displaying or generating output in JS is very important, especially when learning the language. For example, if your JS statements or code blocks are correct, you can output data to check. In JavaScript, there are 4 ways to display your output namely: console.log(), alert(),document.getElementById().innerHTML and lastly document.write().

1. Using Console:

By using the console.log( ) function we can write into the browser's developer console.

var x = 5;
var y = 5;
var sum = x + y; // adds x and y
console.log(sum); // prints 10 in your browser console

However, the output of console.log() cannot be seen on mobile devices because the developer console is only available on desktop browsers like chrome and firefox. Moreover, the output of console.log() can run on various IDE's( Integrated Development Environment) software like VS code when you download the code runner extension.

Here's a display of what it will look like after installing this extension.

blog1.jpg

The arrow indicates the play button that will run your code.

2. Using Dialog Boxes

By using the alert() function, we can output data on a dialog box.

function myFunc() {

var x = 5;
var y = 5;
var sum = x + y; // adds x and y

alert(sum); // shows 10
}

blog2.jpg

3. Writing to HTML Elements

By using the innerHTML property, we can change the content or text of the selected element. We can use the document.getElementById() function to select an element.

<body>
<p id="demo"></p>
<button type ="button" onclick="myFunc()"> Write </button>
<script>
 function myFunc() {
var x = 5;
var y = 5;
var sum = x + y; // adds x and y

document.getElementById("demo").innerHTML=sum; // writes 10

}
</script>
</body>

4. Writing to the Browser Window

By using the document.write() function, we can write to the content of the document.

Note! This should only be used for testing purposes as it will delete all existing HTML in the current page.

<body>
<p id="demo"></p>
<button type ="button" onclick="myFunc()"> Write </button>
<script>
 function myFunc() {
var x = 5;
var y = 5;
var sum = x + y; // adds x and y

document.write(sum) // writes 10

}
</script>
</body>

Thanks for reading this blog. Do let me know what you think about it. PEACE!

Connect with me on:

%[twitter.com/just_Arizon]