Lesson 5.5: Your First "Hello World" Program
Duration: 45 minutes
Learning Objectives
After completing this lesson, you will be able to:
- Create and run your first JavaScript program
- Understand the traditional "Hello World" program
- Use the terminal to execute JavaScript files
- Install TypeScript and compile your first TypeScript program
- Understand the relationship between TypeScript and JavaScript
- Feel confident that your development environment is ready
Introduction
"Hello World" is the traditional first program every programmer writes. It's simple - it just displays the text "Hello, World!" on the screen. But don't let its simplicity fool you. Successfully running a Hello World program means your entire development environment is working correctly.
In this lesson, you'll write your first programs in both JavaScript and TypeScript, bringing together everything you've set up in this module.
Main Content
The Tradition of "Hello World"
┌─────────────────────────────────────────────────────────────┐
│ HELLO WORLD │
│ │
│ The first program you write in any new programming │
│ language or environment. Tradition since 1978! │
│ │
│ Why "Hello World"? │
│ • Simple enough to type without errors │
│ • Tests that your environment works │
│ • Quick win to build confidence │
│ • Universal tradition among programmers │
│ │
│ 1978: The C Programming Language (Kernighan & Ritchie) │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ main() { │ │
│ │ printf("hello, world\n"); │ │
│ │ } │ │
│ └──────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
Creating Your Project
Let's create a proper project folder for this exercise.
Step 1: Open VS Code and create a project folder
- Open VS Code
- Press
Ctrl + Shift + Eto open the Explorer - Click "Open Folder"
- Navigate to your
coding-projectsfolder (or Documents) - Create a new folder called
hello-world - Select it and click "Open"
Step 2: Open the integrated terminal
Press Ctrl + ` (backtick) to open the terminal. You should see something like:
PS C:\Users\YourName\coding-projects\hello-world>
or on macOS/Linux:
user@computer:~/coding-projects/hello-world$
Your First JavaScript Program
Writing the Code
Step 1: Create a new file
In VS Code:
- Click the "New File" icon in the Explorer (or press
Ctrl + N) - Save it as
hello.js(Ctrl + S)
Step 2: Write the code
Type the following into your file:
console.log('Hello, World!');
That's it! One line of code.
Let's understand what this does:
console.log()is a built-in function that prints output to the terminal"Hello, World!"is a string - text enclosed in quotes- The semicolon
;marks the end of the statement
Step 3: Save the file
Press Ctrl + S to save.
Running the Code
In your terminal, type:
node hello.js
You should see:
Hello, World!
Congratulations! You've just run your first program!
Expanding Your Program
Let's make it more interesting. Update hello.js:
// My first JavaScript program
console.log('Hello, World!');
console.log('My name is [Your Name]');
console.log('I am learning to code!');
// Let's do some math
let sum = 2 + 2;
console.log('2 + 2 =', sum);
// Current date and time
console.log('Today is:', new Date().toLocaleDateString());
Save and run again:
node hello.js
Output:
Hello, World!
My name is [Your Name]
I am learning to code!
2 + 2 = 4
Today is: 1/8/2024
Your First TypeScript Program
Now let's level up to TypeScript!
Installing TypeScript
TypeScript needs to be installed via npm (which came with Node.js).
Step 1: Initialize a package.json
In your terminal:
npm init -y
This creates a package.json file that tracks your project's dependencies.
Step 2: Install TypeScript
npm install typescript --save-dev
The --save-dev flag means TypeScript is a development dependency (used for building, not running).
Step 3: Verify installation
npx tsc --version
You should see something like: Version 5.3.3
Writing TypeScript Code
Step 1: Create a new file
Create a file called hello.ts (note the .ts extension).
Step 2: Write the code
// My first TypeScript program
// Type annotations - TypeScript's superpower!
const greeting: string = 'Hello, World!';
const year: number = 2024;
const isLearning: boolean = true;
console.log(greeting);
console.log(`The year is ${year}`);
console.log(`Am I learning TypeScript? ${isLearning}`);
// TypeScript catches errors before you run the code
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet('TypeScript Developer'));
Let's understand the TypeScript additions:
: stringtells TypeScript this variable holds text: numbermeans this variable holds a number: booleanmeans true or falsefunction greet(name: string): stringmeans the function takes a string and returns a string
Compiling TypeScript
TypeScript can't run directly. It must be compiled (converted) to JavaScript first.
Step 1: Compile the TypeScript file
npx tsc hello.ts
This creates a hello.js file. Look in your Explorer - you'll see both files now.
Step 2: Look at the generated JavaScript
Open hello.js to see what TypeScript created:
// My first TypeScript program
// Type annotations - TypeScript's superpower!
var greeting = 'Hello, World!';
var year = 2024;
var isLearning = true;
console.log(greeting);
console.log('The year is '.concat(year));
console.log('Am I learning TypeScript? '.concat(isLearning));
// TypeScript catches errors before you run the code
function greet(name) {
return 'Hello, '.concat(name, '!');
}
console.log(greet('TypeScript Developer'));
Notice: The type annotations are gone! They exist only to help you during development.
Step 3: Run the program
node hello.js
Output:
Hello, World!
The year is 2024
Am I learning TypeScript? true
Hello, TypeScript Developer!
TypeScript's Error Checking
The real power of TypeScript is catching errors before you run your code.
Create a file called error-demo.ts:
// This code has an error - TypeScript will catch it!
function add(a: number, b: number): number {
return a + b;
}
// Correct usage
console.log(add(5, 3));
// Error: TypeScript won't let you do this!
// Uncomment the line below to see the error:
// console.log(add("5", "3"));
Now uncomment the last line and try to compile:
npx tsc error-demo.ts
You'll see an error like:
error-demo.ts:11:17 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
TypeScript caught the bug before you even ran the code! This is why TypeScript is so valuable for building reliable software.
Setting Up TypeScript Properly
For real projects, we configure TypeScript with a tsconfig.json file.
Step 1: Create a TypeScript configuration
npx tsc --init
This creates a tsconfig.json with many options (most commented out).
Step 2: Update the configuration
Open tsconfig.json and look for these settings:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "./dist"
},
"include": ["*.ts"],
"exclude": ["node_modules"]
}
Key settings explained:
target: Which JavaScript version to compile tostrict: Enable all strict type checkingoutDir: Where to put compiled JavaScript files
Step 3: Compile all TypeScript files
npx tsc
Now all .ts files will be compiled to the dist folder.
Step 4: Run from dist folder
node dist/hello.js
Project Structure
Your project folder should now look like this:
hello-world/
├── dist/ # Compiled JavaScript (created by tsc)
│ ├── hello.js
│ └── error-demo.js
├── node_modules/ # Installed packages
├── hello.js # Original JavaScript file
├── hello.ts # TypeScript file
├── error-demo.ts # Error demo file
├── package.json # Project configuration
├── package-lock.json # Dependency lock file
└── tsconfig.json # TypeScript configuration
Troubleshooting
"'node' is not recognized"
Node.js isn't in your PATH. See Lesson 5.1 for troubleshooting.
"'npx' is not recognized"
npx comes with npm. Make sure Node.js is installed correctly. Try:
npm --version
"Cannot find module 'typescript'"
TypeScript isn't installed. Run:
npm install typescript --save-dev
TypeScript errors about modules
If you see errors about import/export, make sure your tsconfig.json has:
"module": "commonjs"
VS Code shows errors but tsc doesn't
Reload VS Code: Ctrl + Shift + P → "Developer: Reload Window"
Practice Exercise
Exercise 1: JavaScript Hello World
Create a file greeting.js that:
- Prints "Welcome to programming!"
- Asks for a name (use
const name = "Your Name";) - Prints "Hello, [name]! Nice to meet you."
- Prints the current time
Exercise 2: TypeScript with Types
Create a file calculator.ts that:
- Declares two number variables
- Creates functions for add, subtract, multiply, and divide
- Each function should have proper type annotations
- Print the results of each operation
Example structure:
function add(a: number, b: number): number {
return a + b;
}
Exercise 3: Catch Type Errors
Create a file debug.ts with intentional type errors. Try to compile it and understand the error messages:
const age: number = 'twenty-five'; // Error!
const name: string = 42; // Error!
const isActive: boolean = 'true'; // Error!
Exercise 4: Complete Project
Create a new folder called my-first-project with:
- A
package.json(vianpm init -y) - TypeScript installed as dev dependency
- A
tsconfig.json - A TypeScript file that prints your name, favorite programming concept, and what you're excited to learn
- Compile and run it successfully
Key Takeaways
- "Hello World" is the traditional first program - a milestone for every developer
- JavaScript files (
.js) can be run directly withnode filename.js - TypeScript files (
.ts) must be compiled to JavaScript first withnpx tsc - TypeScript adds types to JavaScript:
string,number,boolean, etc. - Type annotations help catch errors before running your code
- The
tsconfig.jsonfile configures how TypeScript compiles your code - Your development environment is now complete and ready for the next course!
What's Next?
Congratulations! You've completed Course 1: Foundations for Beginners!
You now have:
- Understanding of how computers work
- Command line skills
- Knowledge of what programming is
- Logical thinking and problem-solving approach
- A complete development environment (Node.js, VS Code, Git, TypeScript)
You're ready for Course 2: TypeScript from Scratch, where you'll dive deep into the TypeScript language and build real projects.
Resources
| Resource | Type | Difficulty |
|---|---|---|
| TypeScript Official Documentation | Documentation | Beginner |
| TypeScript Playground | Tool | Beginner |
| Node.js Documentation | Documentation | Beginner |
| TypeScript for JavaScript Programmers | Tutorial | Beginner |
| JavaScript.info | Tutorial | Beginner |