JavaScript Notes
Learn to write your very first JavaScript program from scratch. Master console.log, alert, variables, and string operations with 8+ hands-on code examples. Perfect beginner guide with detailed explanations.
Introduction — The Most Exciting First Step!
Congratulations! You are about to write your very first line of JavaScript code. This is the moment where everything changes — you go from *reading about programming* to actually doing it.
Think about it: every website you've ever visited — YouTube, Instagram, Google — runs JavaScript. Every animation, every button click, every dynamic feature you see? That's JavaScript in action. And today, YOU are going to make the computer do what you tell it to do.
💡 Quick Summary: Today you'll write your first JavaScript program. It's very easy — just write one line of code and the computer will obey!
By the end of this lesson, you will:
- ✅ Write and run your first JavaScript program
- ✅ Understand 3 different ways to write JavaScript
- ✅ Create 8+ working programs from scratch
- ✅ Know how JavaScript executes behind the scenes
- ✅ Avoid the most common beginner mistakes
Let's do this! 💪
Setting Up Your Environment (VS Code + Browser)
While you CAN use any text editor, Visual Studio Code (VS Code) is the best free tool for writing JavaScript:
Step 1: Install VS Code
- Go to code.visualstudio.com
- Download and install for your operating system
Step 2: Install Helpful Extensions
- Live Server — automatically refreshes your browser when you save
- Prettier — formats your code beautifully
Step 3: Create Your Project
- Create a new folder called
my-first-js - Open it in VS Code (File → Open Folder)
- Create two files:
index.htmlandscript.js - Right-click
index.html→ "Open with Live Server"
💡 Quick Summary: VS Code is a free code editor. Install the Live Server extension — whenever you save your code, the browser will automatically refresh!
Your First Program: Hello World! 🌍
Every programmer's journey starts with "Hello World." It's a tradition that began in the 1970s, and now it's YOUR turn!
console.log("Hello, World!");Hello, World!
That's it! You just wrote your first JavaScript program! Let's break it down:
| Part | What It Does |
|---|---|
console | A built-in object that gives access to the browser's debugging console |
.log() | A method (function) that prints/displays a message |
"Hello, World!" | The text (string) you want to display |
; | Semicolon — marks the end of a statement (like a full stop in English) |
🎯 Think of it this way: console.log() is like telling JavaScript — "Hey! Show this message on the screen!"Code Examples — 8+ Programs to Practice! 💻
Example 1: Your Classic Hello World
console.log("Hello, World!");
console.log("Welcome to JavaScript!");
console.log("I am learning to code!");Hello, World! Welcome to JavaScript! I am learning to code!
Explanation: Each console.log() prints one line. They execute top-to-bottom, one after another.
Example 2: Simulating alert() — Popup Message
// alert() shows a popup box in the browser
alert("Welcome to my website!");
console.log("Alert was shown to the user");[Browser shows popup: "Welcome to my website!"] Alert was shown to the user
Explanation: alert() creates a popup dialog box. The code pauses until the user clicks "OK". Then console.log runs next.
⚠️ Note: alert() works in the browser but NOT in Node.js. It's a browser-specific feature.Example 3: Multiple Statements — Building a Story
console.log("=== My JavaScript Journey ===");
console.log("Day 1: I learned Hello World");
console.log("Day 2: I learned variables");
console.log("Day 3: I built my first project!");
console.log("=============================");=== My JavaScript Journey === Day 1: I learned Hello World Day 2: I learned variables Day 3: I built my first project! =============================
Explanation: JavaScript runs each line in order, top to bottom. You can have as many console.log() statements as you want!
Example 4: Introduction to Variables
// Variables store data — like labeled boxes
let myName = "Rahul";
let myAge = 22;
let myCity = "Mumbai";
console.log(myName);
console.log(myAge);
console.log(myCity);Rahul 22 Mumbai
Explanation: let creates a variable. Think of variables as labeled boxes — you put a value inside and can use it later by its name.
💡 Quick Summary: A variable is a box in which you store data. let myName = "Rahul" means: put "Rahul" in the box named "myName".Example 5: Simple Math Operations
// JavaScript can do math!
console.log(10 + 5); // Addition
console.log(20 - 8); // Subtraction
console.log(6 * 7); // Multiplication
console.log(100 / 4); // Division
console.log(17 % 3); // Remainder (Modulus)
console.log(2 ** 10); // Power (2 to the power 10)15 12 42 25 2 1024
Explanation: JavaScript is also a powerful calculator! The % operator gives the remainder after division, and ** calculates powers.
Example 6: String Concatenation (Joining Text)
let firstName = "Priya";
let lastName = "Sharma";
// Method 1: Using + operator
let fullName = firstName + " " + lastName;
console.log("Full Name: " + fullName);
// Joining multiple things
let greeting = "Hello, " + fullName + "! Welcome to JavaScript.";
console.log(greeting);Full Name: Priya Sharma Hello, Priya Sharma! Welcome to JavaScript.
Explanation: The + operator joins (concatenates) strings together. Notice we added " " (a space) between first and last name — without it, we'd get "PriyaSharma"!
Example 7: Template Literals (Modern & Clean Way)
let language = "JavaScript";
let year = 2026;
let experience = "beginner";
// Template literals use backticks (`) and ${} for variables
let message = `I am learning ${language} in ${year} as a ${experience}!`;
console.log(message);
// Multi-line strings (super easy with backticks!)
let poem = `
Roses are red,
Code is my art,
JavaScript is awesome,
Right from the start!
`;
console.log(poem);I am learning JavaScript in 2026 as a beginner! Roses are red, Code is my art, JavaScript is awesome, Right from the start!
Explanation: Template literals (backticks ` `) are the modern way to build strings. Use ${} to insert variables — no more messy +` concatenation! They also support multi-line strings naturally.
Example 8: A Complete User Greeting Program
// A more complete program that brings it all together!
let userName = "Amit";
let userAge = 25;
let userLanguage = "JavaScript";
let currentYear = 2026;
let startYear = currentYear - 0; // Just started!
console.log("╔════════════════════════════════════╗");
console.log("║ WELCOME TO JAVASCRIPT! ║");
console.log("╠════════════════════════════════════╣");
console.log(`║ Name: ${userName}`);
console.log(`║ Age: ${userAge} years old`);
console.log(`║ Learning: ${userLanguage}`);
console.log(`║ Year: ${currentYear}`);
console.log("╠════════════════════════════════════╣");
console.log(`║ "${userName}, you're going to be`);
console.log(`║ an amazing developer!" 🚀`);
console.log("╚════════════════════════════════════╝");
// Fun calculation
let daysInYear = 365;
let hoursPerDay = 1; // 1 hour daily practice
let totalHours = daysInYear * hoursPerDay;
console.log(`\nIf you practice ${hoursPerDay} hour daily...`);
console.log(`You'll have ${totalHours} hours of practice by year end!`);╔════════════════════════════════════╗ ║ WELCOME TO JAVASCRIPT! ║ ╠════════════════════════════════════╣ ║ Name: Amit ║ Age: 25 years old ║ Learning: JavaScript ║ Year: 2026 ╠════════════════════════════════════╣ ║ "Amit, you're going to be ║ an amazing developer!" 🚀 ╚════════════════════════════════════╝ If you practice 1 hour daily... You'll have 365 hours of practice by year end!
Explanation: This program combines everything — variables, template literals, string output, and math. This is how real programs look — multiple concepts working together!
Example 9: document.write() — Writing to the Page
// document.write() puts content directly on the web page
document.write("<h1>Hello from JavaScript!</h1>");
document.write("<p>This text was created by code, not HTML!</p>");
document.write("<p>Today's lucky number: " + (Math.floor(Math.random() * 100) + 1) + "</p>");
console.log("Content written to the page!");[On the webpage:] Hello from JavaScript! This text was created by code, not HTML! Today's lucky number: 42 [In console:] Content written to the page!
Explanation: document.write() adds content directly to the HTML page. Note: it's mostly used for learning — real projects use other methods to update the page.
Example 10: Combining Different Output Methods
// JavaScript has multiple ways to show output!
console.log("1. This appears in the Console (F12)");
console.warn("2. This is a WARNING message (yellow)");
console.error("3. This is an ERROR message (red)");
console.info("4. This is an INFO message");
// Using console.table for structured data
console.table({
name: "JavaScript",
type: "Programming Language",
difficulty: "Beginner Friendly",
yearCreated: 1995
});1. This appears in the Console (F12) ⚠️ 2. This is a WARNING message (yellow) ❌ 3. This is an ERROR message (red) ℹ️ 4. This is an INFO message ┌──────────────┬─────────────────────────┐ │ (index) │ Values │ ├──────────────┼─────────────────────────┤ │ name │ 'JavaScript' │ │ type │ 'Programming Language' │ │ difficulty │ 'Beginner Friendly' │ │ yearCreated │ 1995 │ └──────────────┴─────────────────────────┘
Explanation: The console has different methods for different purposes — warn for warnings (yellow), error for errors (red), and table for displaying data in a neat table format!
How JavaScript Executes — Behind the Scenes 🔍
When you write JavaScript in an HTML file, here's exactly what happens:
Key Points About Execution:
- JavaScript is single-threaded — it runs one line at a time
- Code executes top to bottom (sequential)
- If there's an error, execution stops at that line
- The
<script>tag at the bottom of<body>is best practice (page loads first, then JS runs)
💡 Quick Summary: The browser reads your code from top to bottom, one line at a time. If there's an error in any line, it stops there and the remaining code won't execute!
Common Mistakes Beginners Make ❌ → ✅
Mistake 1: Typo in console.log
// ❌ WRONG — capital L, wrong spelling
Console.log("Hello"); // Error! (capital C)
console.Log("Hello"); // Error! (capital L)
consolelog("Hello"); // Error! (missing dot)
console.log("Hello") // Works but missing semicolon (not an error, but bad practice)
// ✅ CORRECT
console.log("Hello");❌ ReferenceError: Console is not defined ❌ TypeError: console.Log is not a function ❌ ReferenceError: consolelog is not defined ✅ Hello
Fix: JavaScript is CASE-SENSITIVE. console.log must be all lowercase with a dot between console and log.
Mistake 2: Mismatched Quotes
// ❌ WRONG — mixing quote types
console.log("Hello World!'); // Error! Started with " ended with '
console.log('Hello World!"); // Error! Started with ' ended with "
// ✅ CORRECT — quotes must match
console.log("Hello World!"); // Double quotes ✓
console.log('Hello World!'); // Single quotes ✓
console.log(`Hello World!`); // Backticks ✓❌ SyntaxError: Invalid or unexpected token ❌ SyntaxError: Invalid or unexpected token ✅ Hello World! ✅ Hello World! ✅ Hello World!
Fix: Always use matching quotes. Pick one style (" or ') and be consistent.
Mistake 3: Forgetting Parentheses
// ❌ WRONG — missing parentheses
console.log "Hello"; // Error!
// ✅ CORRECT — parentheses are required
console.log("Hello"); // Works!❌ SyntaxError: Unexpected string ✅ Hello
Fix: console.log is a function — functions ALWAYS need parentheses () to execute.
Mistake 4: Using Curly Quotes (Copy-Paste from Word/Docs)
// ❌ WRONG — these are "smart" curly quotes from Word/Google Docs
console.log("Hello"); // Error! These aren't real quotes
console.log('Hello'); // Error! These aren't real quotes either
// ✅ CORRECT — use straight quotes from your keyboard
console.log("Hello");
console.log('Hello');❌ SyntaxError: Invalid or unexpected token ❌ SyntaxError: Invalid or unexpected token ✅ Hello ✅ Hello
Fix: NEVER copy code from Word or Google Docs — the quotes look similar but are different characters. Always type code directly in your code editor.
Mistake 5: Script Tag in Wrong Place
❌ TypeError: Cannot set properties of null (element doesn't exist yet!) ✅ Page shows "Hello" in the h1 heading
Fix: Place <script> at the bottom of <body> so all HTML elements load before JavaScript tries to access them.
Mistake 6: Confusing = with == or ===
let score = 100; // ✅ Assignment: putting 100 into score
// ❌ This is COMPARISON, not assignment (common beginner confusion)
if (score = 50) { // WRONG! This CHANGES score to 50
console.log("Score is 50");
}
console.log(score); // score is now 50, not 100!
// ✅ CORRECT — use === for comparison
let points = 100;
if (points === 100) { // Checks if points equals 100
console.log("Perfect score!");
}
console.log(points); // points is still 100Score is 50 50 Perfect score! 100
Fix: Use = for assigning values, === for comparing values. This is one of the most common bugs in JavaScript!
Key Takeaways 📝
console.log()is your best friend — use it to display output and debug your code. You'll use it every single day as a developer.
- Three places to write JS — Browser Console (quick tests),
<script>tag (learning), External.jsfile (real projects).
- JavaScript is case-sensitive —
console.logis NOT the same asConsole.LogorCONSOLE.LOG.
- Code runs top-to-bottom — JavaScript executes one line at a time, in order. If line 5 has an error, lines 6+ won't run.
- Variables store data — use
letto create variables. Think of them as labeled boxes holding values.
- Template literals are powerful — use backticks (`
`) and${}for clean string building instead of messy+` concatenation.
- Semicolons end statements — while JavaScript can auto-insert them, always write them yourself to avoid unexpected bugs.
- Place scripts at the bottom — put your
<script>tag just before</body>to ensure the page loads before JavaScript runs.
- Errors are normal! — every developer makes mistakes. Read the error message carefully — it usually tells you exactly what's wrong and on which line.
- Practice is everything — type every example yourself. Don't just read — CODE IT, break it, fix it, modify it!
Interview Questions 🎯
Q1: What is console.log() in JavaScript?
Answer: console.log() is a built-in method that outputs a message to the web console (browser developer tools). It's primarily used for debugging — to check variable values, track code execution flow, and display messages during development. It does NOT show output to regular website users; only developers can see it by opening DevTools (F12).
Q2: What are the different ways to include JavaScript in a web page?
Answer: There are three ways:
- Inline (Script Tag): Write JS directly between
<script>...</script>tags in the HTML file - External File: Create a separate
.jsfile and link it using<script src="filename.js"></script> - Event Attributes (NOT recommended): Inline handlers like
<button onclick="alert('hi')">— this is bad practice and should be avoided in modern development
The best practice is using external files — it keeps HTML and JS separate (Separation of Concerns).
Q3: Why do we place the <script> tag at the bottom of the body?
Answer: Placing <script> before </body> ensures that:
- All HTML elements are fully loaded and available for JavaScript to manipulate
- The page content appears to the user faster (HTML renders first)
- We avoid "null" errors when trying to access elements that haven't been created yet
An alternative modern approach is using the defer attribute: <script src="app.js" defer></script> in <head>, which downloads the script in parallel but executes it after HTML parsing completes.
Q4: What is the difference between console.log(), alert(), and document.write()?
Answer:
| Method | Where Output Shows | User Visible? | Use Case |
|---|---|---|---|
console.log() | Browser DevTools console | No (dev only) | Debugging, development |
alert() | Popup dialog box | Yes (interrupts user) | Quick notifications (rarely used in production) |
document.write() | Directly on web page | Yes | Testing only — never in production (overwrites page) |
In professional development, console.log() is used most frequently for debugging, while DOM manipulation methods (like innerHTML, textContent) are used to display content to users.
Q5: Is JavaScript case-sensitive? Give an example.
Answer: Yes, JavaScript is completely case-sensitive. This means:
myVariableandmyvariableare TWO different variablesconsole.log()works butConsole.Log()throws an errorlet,const,varare keywords —Let,Const,Varare not
Example:
let name = "Alice";
let Name = "Bob";
let NAME = "Charlie";
// These are THREE separate variables!
console.log(name); // "Alice"
console.log(Name); // "Bob"
console.log(NAME); // "Charlie"This is why consistent naming conventions (camelCase for variables) are crucial in JavaScript.
Frequently Asked Questions (FAQ) ❓
Q: Where should I run my JavaScript code as a beginner?
A: Start with the Browser Console (press F12 → Console tab). It requires zero setup and gives instant feedback. Once comfortable, create HTML files with <script> tags and open them in your browser. Eventually, move to VS Code with the Live Server extension for the best development experience.
Q: Do I need a server to run JavaScript?
A: No! For client-side JavaScript (which is what you're learning now), you only need a web browser. Just open your HTML file directly in Chrome/Firefox — no server needed. You only need a server for:
- Node.js (server-side JavaScript)
- Certain advanced features (like
fetch()API for loading files) - Professional deployment of websites
For learning purposes, a browser is all you need!
Q: What's the difference between JavaScript and Java?
A: They are completely different languages despite the similar name! It's like "car" and "carpet" — sharing letters doesn't make them related.
| Feature | JavaScript | Java |
|---|---|---|
| Type | Scripting language | Programming language |
| Runs in | Browser + Node.js | JVM (Java Virtual Machine) |
| Typing | Dynamic (flexible) | Static (strict) |
| Use case | Web, apps, servers | Enterprise, Android, backend |
| Compilation | Just-in-time | Compiled to bytecode |
JavaScript was named to ride Java's popularity wave in 1995. That's the only connection!
Q: Can I use single quotes or double quotes for strings?
A: Both work perfectly fine in JavaScript:
"Hello"(double quotes) ✅'Hello'(single quotes) ✅- `
Hello` (backticks — template literals) ✅
The important rule: be consistent. Most modern style guides prefer single quotes for regular strings and backticks when you need to insert variables. Pick one style and stick with it throughout your project.
Q: I wrote the code correctly but nothing shows up. What's wrong?
A: Common reasons for "invisible" output:
- You're using
console.log()but not opening DevTools — press F12 to see the Console - There's an error before your code — check the Console for red error messages
- Your script file isn't linked properly — verify the
srcpath in your<script>tag - Browser is showing a cached (old) version — press Ctrl+Shift+R to hard refresh
- Script is in
<head>trying to access elements — move it to bottom of<body>
Always check the Console tab first — if there's a problem, JavaScript will tell you exactly what went wrong!
What's Next? 🎯
You've just written your first JavaScript programs — amazing work! 🎉 You now understand how to output text, use variables, do math, and avoid common mistakes.
In the next lesson, we'll dive deeper into JavaScript Variables and Data Types — learning about let, const, var, and the different types of data JavaScript can work with.
💡 Challenge: Before moving on, try modifying Example 8 (the greeting program) with YOUR name, YOUR age, and YOUR favorite programming language. Make it personal!
Keep coding, keep experimenting, and remember — every expert was once a beginner. You're on the right path! 🚀
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Your First JavaScript Program — Hello World & Beyond Complete Guide 2026.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, introduction, first, program
Related JavaScript Master Course Topics