Dynamic and interactive
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Demo</title>
</head>
<body>
<h1 id="header">Welcome to my JavaScript demo</h1>
<button onclick="changeText()">Change Text</button>
<script>
function changeText() {
var header = document.getElementById("header");
header.innerHTML = "Text has been changed";
}
</script>
</body>
</html>
In this example, we have a very basic HTML document that contains a button. When the button is clicked, the "changeText" function is called, which changes the text of the header using JavaScript. While an extremely simple example, this demonstrates how JavaScript can be used to manipulate the DOM in real-time, creating dynamic and interactive web pages.
Event-driven
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Demo</title>
</head>
<body>
<input type="text" id="input" onkeyup="showValue()">
<p id="output"></p>
<script>
function showValue() {
var input = document.getElementById("input");
var output = document.getElementById("output");
output.innerHTML = input.value;
}
</script>
</body>
</html>
In this example, we have an HTML document that contains an input field and a paragraph. The "onkeyup" event is used to call the "showValue" function whenever a key is pressed in the input field. The function gets the value of the input field and displays it in the paragraph. This demonstrates how JavaScript can be used to create event-driven interactions.
Cross-platform
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
server.listen(3000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:3000/');
In this example, we are using JavaScript on the server-side with the use of Node.js, it creates a simple HTTP server and listens on port 3000. This simple example shows how JavaScript can be used for both client-side and server-side programming, allowing for a more efficient and streamlined development process.
Libraries and Frameworks
const express = require('express')
const app = express()
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(3000, () => console.log('Example app listening on port 3000!'))
In this example, we are using the Express.js library to create a simple web server. This code accomplishes the same as the previous example with fewer lines of less complicated code. LIbraries typically layer onto existing functionality to improve This demonstrates how JavaScript libraries and frameworks can be used to simplify and streamline the development process.