Welcome to Chapter 1: Hello, World! In this chapter, we will learn how to write our first JavaScript program. The phrase "Hello, World!" is traditionally used to introduce a programming language because it is simple yet demonstrates how to output text.
By the end of this chapter, you will:
- Understand how JavaScript interacts with a web page.
- Learn how to use
console.log()
to print messages. - Write your first JavaScript program.
- Get comfortable with basic syntax and concepts.
To display "Hello, World!", follow these steps:
The console.log()
method is used to print messages to the browser console.
console.log("Hello, World!");
console.log()
is a built-in function in JavaScript that outputs text to the browser console."Hello, World!"
is the message we want to display.- The semicolon
;
at the end of the line is optional but recommended.
You can run this code in two ways:
- Open Google Chrome (or any browser).
- Right-click anywhere on the page and select Inspect.
- Go to the Console tab.
- Type the following code and press Enter:
console.log("Hello, World!");
- You will see
Hello, World!
printed in the console.
You can also write JavaScript inside an HTML file:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Hello World</title>
</head>
<body>
<script>
console.log("Hello, World!");
</script>
</body>
</html>
<script>
tags are used to insert JavaScript inside an HTML file.- The code inside
<script>
will run when the page loads. - Open this file in a browser and check the console to see the message.
Comments help you explain your code but do not affect execution.
// This is a single-line comment
console.log("Hello, World!");
/*
This is a multi-line comment
It can span multiple lines
*/
JavaScript allows storing values using variables.
let message = "Hello, World!";
console.log(message);
let
is used to declare a variable."Hello, World!"
is a string (text) assigned to the variablemessage
.console.log(message);
prints the value ofmessage
.
Write a JavaScript program that prints "Welcome to JavaScript!" in the console.
Create a variable named greeting
that stores "Good Morning!" and print it using console.log()
.
Write a JavaScript program that includes both single-line and multi-line comments.
Create an HTML file and write JavaScript inside the <script>
tag to print "Learning JavaScript!" in the console.
Write a JavaScript program that contains an intentional error (e.g., missing a closing quote) and see what error message appears in the console.
In this chapter, we learned:
- How to write and run JavaScript.
- Using
console.log()
to print messages. - The importance of comments.
- Declaring variables and using them.
Congratulations! You have successfully written your first JavaScript program. 🎉