JavaScript is a versatile programming language commonly used for web development. It allows you to add interactivity and dynamic behavior to your web pages.
Here's a simple JavaScript example that displays a "Hello, World!" message:
const greeting = "Hello, World!";
console.log(greeting);
// Output: Hello, World!
You can add JavaScript to your HTML documents in two ways:
<script>
tag.You can add JavaScript directly to your HTML document using the <script>
tag. The <script>
tag can be placed in the <head>
or <body>
section of your HTML document.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Inline JavaScript</title>
<script>
const greeting = "Hello, World!";
console.log(greeting);
</script>
</head>
<body></body>
</html>
You can also add JavaScript to your HTML document using an external JavaScript file. The <script>
tag should be placed in the <head>
section of your HTML document. The src
attribute specifies the path to the external JavaScript file.
<!DOCTYPE html>
<html lang="en">
<head>
<title>External JavaScript</title>
<script src="script.js"></script>
</head>
<body></body>
</html>
JavaScript can display data in different ways:
console.log()
- Displays data in the browser console.alert()
- Displays data in an alert box.document.write()
- Displays data in the HTML document.console.log()
The console.log()
method displays data in the browser console. The browser console can be accessed by pressing F12
or Ctrl + Shift + I
on Windows and Cmd + Opt + I
on Mac.
const greeting = "Hello, World!";
console.log(greeting);
// Output: Hello, World!
alert()
The alert()
method displays data in an alert box.
const greeting = "Hello, World!";
alert(greeting);
// Output: Hello, World!
document.write()
The document.write()
method displays data in the HTML document.
const greeting = "Hello, World!";
document.write(greeting);
// Output: Hello, World!