javascript clean-code javascript-tutorial consolelog javascript-for-beginners javascript-basics hello-world javascript-syntax comments-in-javascript single-line-comments
Chapter 2: Basics of JavaScript
Section 2.1: Syntax and Basics
Tutorial 2.1.1: Hello World and Comments
Hello World and Comments in JavaScript
The first step in learning JavaScript is to write a simple program that outputs "Hello, World!" to the console. Additionally, understanding how to use comments is essential for writing clean, maintainable code.
Writing Your First JavaScript Program
- Creating a Script:
- Open a code editor (e.g., VS Code) or a browser console.
- The Code:
- In your script file or console, type:
console.log("Hello, World!");
- What happens?
- The
console.log()
function outputs text to the console. "Hello, World!"
is a string (text) enclosed in double quotes.
- Running the Code:
- In a browser:
- Open the console (
Ctrl+Shift+J
orCmd+Option+J
) and type the code. - In Node.js:
- Save the code in a file (e.g.,
hello.js
) and run it using:
node hello.js
- The output will be:
Hello, World!
Comments in JavaScript
Comments are notes in the code that are ignored by the JavaScript engine. They are useful for explaining what the code does or for temporarily disabling parts of the code.
- Single-Line Comments:
- Begin with
//
. - Example:
// This is a single-line comment
console.log("Hello, World!"); // Outputting to the console
- Multi-Line Comments:
- Enclosed within
/* */
. - Example:
/*
This is a multi-line comment.
It spans multiple lines.
*/
console.log("Hello, World!");
- Uses of Comments:
- Documenting code logic.
- Temporarily disabling code during debugging.
- Adding notes or reminders for developers.
Common Errors to Avoid
- Missing Quotes Around Strings:
- Incorrect:
console.log(Hello, World!);
- Correct:
console.log("Hello, World!");
- Unmatched Parentheses:
- Incorrect:
console.log("Hello, World!";
- Correct:
console.log("Hello, World!");
Exercise
- Write a script that outputs your name to the console.
- Example:
console.log("My name is Alice.");
- Add comments to explain each line of your script.
Comments
Please log in to leave a comment.