JavaScript Examples

Before starting an example let us discuss how JavaScript can display the data.

JavaScript ways of data display:

1. window.alert(): Display data in an alert box.
2. document.write(): Display data into the HTML output.
3. innerHTML: Display data into an HTML element.
4. console.log(): Display data into the browser console.

Javascript in head tag example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<html>
<head>
<script type="text/javascript">
alert("Hello w3schools.com");
</script>
</head>
</html>
<html> <head> <script type="text/javascript"> alert("Hello w3schools.com"); </script> </head> </html>
<html>
<head>
<script type="text/javascript">
alert("Hello w3schools.com");
</script>
</head>
</html>

Try it:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<html>
<html>
<html>

Javascript in body tag example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<body>
<script type="text/javascript">
alert("Hello w3schools.com");
</script>
</body>
</html>
<body> <script type="text/javascript"> alert("Hello w3schools.com"); </script> </body> </html>
<body>
<script type="text/javascript">
alert("Hello w3schools.com");
</script>
</body>
</html>

Try it:

Javascript in head and body tag example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<html>
<head>
<script type="text/javascript">
function sayHello(){
alert("Hello w3schools.com");
}
</script>
</head>
<body>
<p>Hello World Javascript Example.</p>
<form>
<input type="button" value="Say Hello" onclick="sayHello()"/>
</form>
</body>
</html>
<html> <head> <script type="text/javascript"> function sayHello(){ alert("Hello w3schools.com"); } </script> </head> <body> <p>Hello World Javascript Example.</p> <form> <input type="button" value="Say Hello" onclick="sayHello()"/> </form> </body> </html>
<html>
<head>
<script type="text/javascript">
function sayHello(){
alert("Hello w3schools.com");
}
</script>
</head>
<body>
<p>Hello World Javascript Example.</p>
<form>
<input type="button" value="Say Hello" onclick="sayHello()"/>
</form>
</body>
</html>

Try it: