Skip to main content

JavaScript First Program

Welcome to your first step in the JavaScript journey! In this lesson, you'll write your first JavaScript program and learn how to run it. We'll cover different ways to execute JavaScript code and understand the basic structure of a JavaScript program.

Introduction to JavaScript Execution

Before we dive into coding, it's important to understand that JavaScript can be executed in different environments:

  1. Web Browser - The most common environment for JavaScript
  2. Node.js - A runtime environment for executing JavaScript outside the browser
  3. Other environments - Like mobile apps (React Native), desktop apps (Electron), etc.

For beginners, the browser is the easiest place to start since you don't need to install anything extra.

Your First JavaScript Program: Hello World

Let's start with the traditional "Hello World" program. This simple program will output the text "Hello, World!" to demonstrate that your JavaScript environment is working correctly.

Using the Browser Console

The quickest way to try JavaScript is using your browser's developer console:

  1. Open your web browser (Chrome, Firefox, Edge, etc.)
  2. Press F12 or right-click and select "Inspect" to open developer tools
  3. Click on the "Console" tab
  4. Type the following code and press Enter:
javascript
console.log("Hello, World!");

You should see:

Hello, World!

Congratulations! You've just written and executed your first JavaScript program!

Adding JavaScript to an HTML File

In real-world web development, you'll typically include JavaScript in HTML files. Let's create a simple webpage with JavaScript:

  1. Create a new file named index.html with the following content:
html
<!DOCTYPE html>
<html>
<head>
<title>My First JavaScript Program</title>
</head>
<body>
<h1>My First JavaScript Program</h1>

<!-- Method 1: JavaScript directly in HTML -->
<script>
console.log("Hello from inline JavaScript!");
document.write("<p>This text was written by JavaScript</p>");
</script>

<!-- Method 2: JavaScript from external file -->
<script src="script.js"></script>
</body>
</html>
  1. Create a file named script.js in the same folder with this content:
javascript
// This is an external JavaScript file
console.log("Hello from external JavaScript file!");
alert("Welcome to JavaScript programming!");
  1. Open the index.html file in your browser to see the results

Understanding Your First Program

Let's break down what's happening in these examples:

  • console.log() is a function that outputs text to the console
  • document.write() writes content directly to the HTML document
  • alert() displays a popup message box
  • // is used for single-line comments in JavaScript

JavaScript Statement Basics

JavaScript code consists of statements that tell the browser what to do. Each statement typically ends with a semicolon (;), although JavaScript has automatic semicolon insertion in many cases.

javascript
// Multiple statements
let name = "JavaScript Beginner"; // Declaration statement
console.log(name); // Function call statement
let sum = 5 + 10; // Expression statement

Variables and Basic Output

Let's create a more interactive example:

javascript
// Declaring variables
let userName = "Maria";
let userAge = 25;

// Using variables in output
console.log("Hello, " + userName + "!");
console.log(`You are ${userAge} years old.`); // Template literals (modern way)

// Simple calculation
let nextYearAge = userAge + 1;
console.log(`Next year, you will be ${nextYearAge} years old.`);

Output:

Hello, Maria!
You are 25 years old.
Next year, you will be 26 years old.

Running JavaScript with Node.js

If you have Node.js installed, you can run JavaScript directly from your computer without a browser:

  1. Create a file named firstProgram.js with this content:
javascript
// First Node.js program
console.log("Hello from Node.js!");

// A simple calculation
const num1 = 10;
const num2 = 5;
console.log(`${num1} + ${num2} = ${num1 + num2}`);
console.log(`${num1} * ${num2} = ${num1 * num2}`);
  1. Open a terminal or command prompt
  2. Navigate to the folder containing your file
  3. Run the command: node firstProgram.js

Output:

Hello from Node.js!
10 + 5 = 15
10 * 5 = 50

Real-World Example: Interactive Webpage

Let's create a simple interactive webpage that responds to user input:

html
<!DOCTYPE html>
<html>
<head>
<title>Interactive JavaScript Example</title>
</head>
<body>
<h1>Temperature Converter</h1>

<label for="celsius">Celsius:</label>
<input type="number" id="celsius" placeholder="Enter temperature in Celsius">
<button onclick="convertTemperature()">Convert</button>

<p id="result"></p>

<script>
function convertTemperature() {
// Get the input value
let celsius = document.getElementById("celsius").value;

// Check if input is valid
if (celsius === "" || isNaN(celsius)) {
document.getElementById("result").innerHTML = "Please enter a valid number";
return;
}

// Convert to number and calculate
celsius = Number(celsius);
let fahrenheit = (celsius * 9/5) + 32;

// Display the result
document.getElementById("result").innerHTML =
`${celsius}°C is equal to ${fahrenheit.toFixed(2)}°F`;
}
</script>
</body>
</html>

In this example:

  1. We create an HTML form with an input field and a button
  2. The button calls a JavaScript function when clicked
  3. The function reads the input value, performs a calculation, and updates the page

This demonstrates how JavaScript can make web pages interactive by:

  • Responding to user actions (button click)
  • Reading input values
  • Performing calculations
  • Updating the page content

Summary

Congratulations! You've written your first JavaScript programs and learned:

  • How to run JavaScript in different environments (browser console, HTML files, Node.js)
  • Basic JavaScript syntax for output (console.log(), document.write(), alert())
  • How to use variables and perform simple calculations
  • How to create interactive web pages that respond to user input

JavaScript is a versatile language that powers much of the modern web. With these fundamentals, you're ready to continue your journey into more advanced JavaScript concepts.

Practice Exercises

To reinforce your learning, try these exercises:

  1. Hello User: Modify the temperature converter to first ask for the user's name and display a personalized greeting.

  2. Age Calculator: Create a program that asks for the user's birth year and calculates their age.

  3. Tip Calculator: Build a simple web page that calculates the tip for a restaurant bill based on the bill amount and service quality.

Additional Resources

Happy coding!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)