JavaScript Tutorial with Node.js
Learn JavaScript fundamentals with Node.js
This article will guide you through JavaScript fundamentals from basic concepts using Node.js. Perfect for beginners who want to learn JavaScript for both frontend and backend development.
0. Getting Started#
0.1 What You’ll Learn#
- Understand JavaScript basics: comments, variables, data types, and operators
- Learn control flow: conditionals and loops
- Work with functions and modules
- Handle asynchronous code with Promises and async/await
0.2 What is JavaScript?#
JavaScript (JS) is a programming language originally designed for web browsers. Today it also runs on servers using Node.js.
| Frontend (Browser) | Backend (Server) |
|---|---|
| UI interactions | APIs |
| Form validation | Authentication |
| Fetching data | Database access |
| React/Next.js apps | File processing |
0.3 Why Use JavaScript for Full-Stack?#
- One language across the entire stack
- Huge ecosystem via npm (Node Package Manager)
- Fast development with extensive libraries
- Excellent for building APIs and web applications
0.4 Project Setup#
Prerequisites: Install Node.js (LTS) from nodejs.org ↗
# Create project folder
mkdir js-node-tutorial
cd js-node-tutorial
# Run any JavaScript file
node filename.jsbash1. Variables & Data Types#
1.1 Code Example#
File: 01_variables.js
// 01_variables.js
const course = "JavaScript + Node.js";
let version = 1;
let isFun = true;
console.log("Course:", course);
console.log("Version:", version);
console.log("Is fun?", isFun);
version = version + 1;
console.log("Next version:", version);
console.log("Type of course:", typeof course);
console.log("Type of version:", typeof version);
console.log("Type of isFun:", typeof isFun);javascript1.2 Run the Code#
node 01_variables.jsbash1.3 Expected Result#
Course: JavaScript + Node.js
Version: 1
Is fun? true
Next version: 2
Type of course: string
Type of version: number
Type of isFun: booleanplaintext1.4 Variable Types Explained#
| Keyword | Description | Example |
|---|---|---|
const | Cannot be reassigned | const name = "John"; |
let | Can be reassigned | let age = 25; |
var | Old way (avoid) | var old = "legacy"; |
1.5 Data Types#
| Type | Description | Example |
|---|---|---|
string | Text | "Hello" |
number | Numeric | 42, 3.14 |
boolean | True/False | true, false |
object | Collections | {}, [] |
undefined | Not assigned | undefined |
1.6 Naming Conventions#
| Convention | Rule | Valid Examples | Invalid |
|---|---|---|---|
| camelCase | First word lowercase, each subsequent word capitalized | userName, totalPrice, isLoggedIn | Username, user_name |
| descriptive | Use meaningful names | userAge, totalPrice | x, data, temp |
| Start with letter | Variable names must start with a letter, $, or _ | name, _private, $count | 1name, @var |
| No spaces | Use camelCase instead of spaces | firstName, lastName | first name |
| Case sensitive | name and Name are different | myVar, myvar | N/A |
| No keywords | Can’t use reserved words | userCount, className | var, function, return |
Tip: Choose names that describe what the variable holds, not how it’s used. For example, prefer
userNameoverdata.
1.7 Assignment#
- Create
02_assignment.js - Store your name, age, and favorite programming language
- Print them + print
typeofeach variable
2. Comments#
Comments are notes in your code that JavaScript ignores. They help explain what your code does.
2.1 Types of Comments#
File: 02_comments.js
// This is a single-line comment
// Use // for short notes on one line
/*
This is a multi-line comment.
Use it for longer explanations
that span multiple lines.
*/
// Comment before a line of code
const greeting = "Hello";
const name = "Karn"; // Comment after code
/* Multi-line comments
can also be used inline */
const age = 25;javascript2.2 Run the Code#
node 02_comments.jsbash2.3 Expected Result#
Hello
Karn
25plaintextNotice: Comments are not displayed in the output. JavaScript completely ignores them.
2.4 When to Use Comments#
| Use Case | Example |
|---|---|
| Explain why not what | // Check if user is admin before allowing access |
| Document complex logic | // Calculate compound interest: A = P(1 + r/n)^nt |
| TODO reminders | // TODO: Add error handling for edge cases |
| Temporarily disable code | // console.log(debugValue); |
Tip: Don’t comment obvious code.
let x = 5; // Set x to 5is not helpful.
2.5 Comment Syntax Reference#
| Syntax | Type | Use For |
|---|---|---|
// comment | Single-line | Short notes, inline explanations |
/* comment */ | Multi-line | Longer descriptions, documentation |
2.6 Assignment + IDE Shortcuts#
Task: Create 02_assignment.js and practice using keyboard shortcuts for commenting.
VS Code Shortcuts
| Action | Windows/Linux | macOS |
|---|---|---|
| Toggle Line Comment | Ctrl + / | Cmd + / |
| Toggle Block Comment | Shift + Alt + A | Shift + Option + A |
| Copy Line Up | Shift + Alt + Up | Shift + Option + Up |
| Move Line Up/Down | Alt + Up/Down | Option + Up/Down |
Practice Steps
-
Create
02_assignment.js -
Type the following code (without comments first):
javascriptconst name = "YourName" const age = 25 console.log(name) console.log(age) -
Practice Shortcuts:
- Go to line
console.log(name)and pressCtrl + /(Windows) orCmd + /(Mac) → line gets commented - Go to line
const age = 25and pressCtrl + /again → line gets commented - Press
Ctrl + /again → uncomment
- Go to line
-
Practice Block Comment:
- Select multiple lines (e.g., from
console.log(name)toconsole.log(age)) - Press
Shift + Alt + A(Windows) orShift + Option + A(Mac) - Selected code gets wrapped in
/* ... */
- Select multiple lines (e.g., from
Tip: Building keyboard shortcut habits will dramatically increase your coding speed. Press
Ctrl + Shift + Pand search “Keyboard Shortcuts” to see all available shortcuts.
3. Operators & String Templates#
3.1 Code Example#
File: 03_operators.js
// 03_operators.js
const a = 10;
const b = 3;
console.log("a + b =", a + b);
console.log("a - b =", a - b);
console.log("a * b =", a * b);
console.log("a / b =", a / b);
console.log("a % b =", a % b);
const name = "Karn";
const msg = `Hello ${name}, a=${a}, b=${b}, a*b=${a * b}`;
console.log(msg);javascript3.2 Run the Code#
node 03_operators.jsbash3.3 Expected Result#
a + b = 13
a - b = 7
a * b = 30
a / b = 3.3333333333333335
a % b = 1
Hello Karn, a=10, b=3, a*b=30plaintext3.4 Operators Reference#
| Operator | Description | Example |
|---|---|---|
+ | Addition | 5 + 3 = 8 |
- | Subtraction | 5 - 3 = 2 |
* | Multiplication | 5 * 3 = 15 |
/ | Division | 6 / 3 = 2 |
% | Modulus (remainder) | 5 % 3 = 2 |
` | Template literal | `${var}` |
3.5 Assignment#
- Create
03_assignment.js - Given
price=120anddiscount=15(%), calculate final price - Print a template string:
Final price is ...
4. Conditionals (if / else)#
4.1 Code Example#
File: 04_conditionals.js
// 04_conditionals.js
const score = 72;
if (score >= 80) {
console.log("Grade: A");
} else if (score >= 70) {
console.log("Grade: B");
} else if (score >= 60) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}javascript4.2 Run the Code#
node 04_conditionals.jsbash4.3 Expected Result#
Grade: Bplaintext4.4 Comparison Operators#
| Operator | Description | Example |
|---|---|---|
=== | Equal value and type | 5 === "5" → false |
!== | Not equal value or type | 5 !== "5" → true |
> | Greater than | 10 > 5 → true |
< | Less than | 5 < 10 → true |
>= | Greater or equal | 5 >= 5 → true |
<= | Less or equal | 5 <= 5 → true |
4.5 Logical Operators#
| Operator | Description | Example |
|---|---|---|
&& | AND | true && false → false |
|| | OR | true || false → true |
! | NOT | !true → false |
4.6 Assignment#
- Create
04_assignment.js - Use
const hour = 14; - If
hour < 12print"Good morning", else"Good afternoon"
5. Loops (for / while)#
5.1 Code Example#
File: 05_loops.js
// 05_loops.js
for (let i = 1; i <= 5; i++) {
console.log("for loop i =", i);
}
let n = 3;
while (n > 0) {
console.log("while loop n =", n);
n--;
}javascript5.2 Run the Code#
node 05_loops.jsbash5.3 Expected Result#
for loop i = 1
for loop i = 2
for loop i = 3
for loop i = 4
for loop i = 5
while loop n = 3
while loop n = 2
while loop n = 1plaintext5.4 Loop Types#
| Loop | Use When | Example |
|---|---|---|
for | Known iterations | for (let i = 0; i < 10; i++) |
while | Unknown iterations | while (condition) |
for...of | Iterate arrays | for (item of array) |
for...in | Iterate objects | for (key in object) |
5.5 Assignment#
- Create
05_assignment.js - Print even numbers from 2 to 20 (2, 4, 6, …, 20)
6. Functions#
6.1 Code Example#
File: 06_functions.js
// 06_functions.js
function add(x, y) {
return x + y;
}
const multiply = (x, y) => x * y;
console.log("add(2, 5) =", add(2, 5));
console.log("multiply(3, 4) =", multiply(3, 4));javascript6.2 Run the Code#
node 06_functions.jsbash6.3 Expected Result#
add(2, 5) = 7
multiply(3, 4) = 12plaintext6.4 Function Syntax Comparison#
| Type | Syntax | Use Case |
|---|---|---|
| Function Declaration | function name() {} | General use |
| Function Expression | const name = function() {} | Callbacks |
| Arrow Function | const name = () => {} | Short, callbacks |
6.5 Function Naming Conventions#
| Convention | Rule | Valid Examples | Invalid |
|---|---|---|---|
| camelCase | First word lowercase, subsequent words capitalized | getUserData, calculateTotal, isValid | GetUserData, get_user_data |
| Verb-first | Start with a verb describing the action | fetchUser, saveData, deleteItem | user, data, item |
| Booleans | Use is, has, can, should prefix | isLoggedIn, hasPermission, canEdit | logged, permission, editable |
| Handlers | Use handle prefix for event handlers | handleSubmit, handleClick | submit, onClick |
Good vs Bad Examples:
| Bad | Good | Reason |
|---|---|---|
data() | getUserData() | Describes what data |
process() | calculateTotal() | Describes the calculation |
check() | isValidEmail() | Describes what’s being checked |
bool() | hasPermission() | Boolean naming convention |
x() | formatDate() | Meaningful name |
Tip: Function names should answer “what does it do?” —
calculateTotal(price, tax)is clearer thancalc(p, t).
6.6 Assignment#
- Create
06_assignment.js - Write
isAdult(age)returningtrue/false(adult >= 18) - Test with 2 ages
7. Arrays & Objects#
7.1 Code Example#
File: 07_arrays_objects.js
// 07_arrays_objects.js
const fruits = ["apple", "banana", "mango"];
fruits.push("orange");
console.log("fruits:", fruits);
console.log("first fruit:", fruits[0]);
console.log("count:", fruits.length);
const user = {
id: 1,
name: "Karn",
roles: ["admin", "teacher"],
};
console.log("user name:", user.name);
console.log("user roles:", user.roles.join(", "));javascript7.2 Run the Code#
node 07_arrays_objects.jsbash7.3 Expected Result#
fruits: [ 'apple', 'banana', 'mango', 'orange' ]
first fruit: apple
count: 4
user name: Karn
user roles: admin, teacherplaintext7.4 Array Methods#
| Method | Description | Example |
|---|---|---|
push() | Add to end | arr.push(5) |
pop() | Remove from end | arr.pop() |
unshift() | Add to start | arr.unshift(5) |
shift() | Remove from start | arr.shift() |
map() | Transform array | arr.map(x => x*2) |
filter() | Filter array | arr.filter(x => x>5) |
7.5 Assignment#
- Create
07_assignment.js - Make an array of 5 numbers
- Compute the sum using a loop
- Create an object
{ title, year }and print it
8. Array of Objects#
8.1 Code Example#
File: 08_array_of_objects.js
// 08_array_of_objects.js
const users = [
{ id: 1, name: "Karn", role: "admin" },
{ id: 2, name: "John", role: "user" },
{ id: 3, name: "Jane", role: "user" }
];
console.log("All users:", users);
console.log("First user:", users[0]);
console.log("User name:", users[0].name);
// Loop through array of objects
console.log("\n--- User List ---");
for (let i = 0; i < users.length; i++) {
console.log(`${users[i].id}: ${users[i].name} (${users[i].role})`);
}
// Find user by id
const userId = 2;
const foundUser = users.find(u => u.id === userId);
console.log("\nFound user:", foundUser);javascript8.2 Run the Code#
node 08_array_of_objects.jsbash8.3 Expected Result#
All users: [
{ id: 1, name: 'Karn', role: 'admin' },
{ id: 2, name: 'John', role: 'user' },
{ id: 3, name: 'Jane', role: 'user' }
]
First user: { id: 1, name: 'Karn', role: 'admin' }
User name: Karn
--- User List ---
1: Karn (admin)
2: John (user)
3: Jane (user)
Found user: { id: 2, name: 'John', role: 'user' }plaintext8.4 Common Operations#
| Operation | Method | Example |
|---|---|---|
| Access item | arr[index] | users[0].name |
| Find item | arr.find() | users.find(u => u.id === 1) |
| Filter items | arr.filter() | users.filter(u => u.role === 'admin') |
| Transform items | arr.map() | users.map(u => u.name) |
| Add item | arr.push() | users.push(newUser) |
8.5 Assignment#
- Create
08_assignment.js - Make an array of 3 products (each with
id,name,price) - Print all products
- Find and print the product with
id = 2
9. Modules (import/export)#
9.1 Code Example#
You will create two files for this topic.
File: mathUtil.js
// mathUtil.js
function square(n) {
return n * n;
}
module.exports = { square };javascriptFile: 09_modules.js
// 09_modules.js
const { square } = require("./mathUtil");
console.log("square(5) =", square(5));
console.log("square(12) =", square(12));javascript9.2 Run the Code#
node 09_modules.jsbash9.3 Expected Result#
square(5) = 25
square(12) = 144plaintext9.4 Module Syntax#
| Syntax | Type | Example |
|---|---|---|
require() | CommonJS (Node.js) | const mod = require('./mod') |
import | ES Modules | import { mod } from './mod.js' |
module.exports | CommonJS export | module.exports = { func } |
export | ES Module export | export function func() {} |
9.5 Assignment#
- Add a new function
cube(n)inmathUtil.js - Use it in
09_assignment.jsand print results
10. Async JavaScript (Promises / async-await)#
10.1 Code Example#
File: 10_async.js
// 10_async.js
const { setTimeout } = require("node:timers/promises");
async function main() {
console.log("Start");
await setTimeout(500);
console.log("After 500ms");
await setTimeout(300);
console.log("After 300ms");
}
main();javascript10.2 Run the Code#
node 10_async.jsbash10.3 Expected Result#
Start
After 500ms
After 300msplaintext10.4 Async Concepts#
| Concept | Description |
|---|---|
Promise | Represents eventual completion |
async | Declares an async function |
await | Pauses until Promise resolves |
setTimeout() | Node.js built-in promisified delay (Node 16+) |
Note:
setTimeoutfromnode:timers/promisesis available in Node.js 16+. For browser code, you’d still need to wrapsetTimeoutin a Promise manually.
10.5 Error Handling (try/catch)#
File: 11_errors.js
// 11_errors.js
async function fetchUserData(userId) {
// Simulate API call that might fail
if (userId <= 0) {
throw new Error("Invalid user ID");
}
return { id: userId, name: `User ${userId}` };
}
async function main() {
try {
console.log("Fetching user...");
const user = await fetchUserData(-1); // This will throw an error
console.log("User:", user);
} catch (error) {
console.log("Error caught:", error.message);
}
// This will run successfully
try {
const user = await fetchUserData(123);
console.log("User:", user);
} catch (error) {
console.log("Error:", error.message);
}
console.log("Program continues...");
}
main();javascriptRun the Code
node 11_errors.jsbashExpected Result
Fetching user...
Error caught: Invalid user ID
User: { id: 123, name: 'User 123' }
Program continues...plaintextKey Points:
try- Code that might throw an errorcatch- Handles the error if one occursthrow- Manually throw an error
10.6 Assignment#
Create a file named 12_assignment.js and write a countdown function that:
- Takes a number
nas input - Prints numbers from
ndown to 1 with a 300ms delay between each number - Stops automatically when reaching 1
Hint: Use
setInterval()to repeatedly execute code andclearInterval()to stop it.
11. Best Practices#
11.1 What to Do#
- Use
constby default,letwhen needed - Use arrow functions for callbacks
- Use template literals for strings
- Handle errors with try/catch
- Use meaningful variable names
- Add comments to explain complex logic
11.2 What to Avoid#
- Don’t use
var(legacy) - Don’t skip error handling
- Don’t create global variables
- Don’t use blocking operations in async code
- Don’t forget to return values
- Don’t comment obvious code