Introduction to JavaScript
Pythons Tutorials
What is JavaScript?
JavaScript is a versatile programming language that adds interactivity and dynamic behavior to web pages. It’s commonly used for tasks like form validation, creating animations, and fetching data from servers. JavaScript is supported by all modern web browsers, making it an essential skill for web development.
1. Writing Your First JavaScript Program
To get started, let’s write a simple JavaScript program that displays “Hello, World!” in the browser’s console. The console is a developer tool that allows you to view messages and errors from your JavaScript code.
Example 1: Displaying “Hello, World!” in the Console
// This is a single-line comment
/* This is a
multi-line comment */
// Let's write our first JavaScript code
console.log("Hello, World!");
Explanation:
- JavaScript code can be added directly to an HTML file within
<script>
tags or in an external.js
file linked to the HTML document. console.log()
is a built-in JavaScript function used to print messages or data to the console. In this example, we’re logging the text “Hello, World!”.- Comments are used to add explanations to your code. Single-line comments start with
//
, and multi-line comments are enclosed in/*
and*/
.
2. Running Your JavaScript Code
To run the code in your browser:
- Open a text editor and create an HTML file (e.g.,
index.html
). - Add the following code to your HTML file:
<!DOCTYPE html>
<html>
<head>
<title>My First JavaScript</title>
</head>
<body>
<script>
// JavaScript code goes here
console.log("Hello, World!");
</script>
</body>
</html>
- Save the HTML file.
- Open the HTML file in a web browser.
- Right-click on the web page, select “Inspect” (or press
F12
orCtrl+Shift+I
), and go to the “Console” tab to see the output.
Congratulations! You’ve written and executed your first JavaScript program.