Back

JavaScript Tutorial with Node.jsBlur image

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 interactionsAPIs
Form validationAuthentication
Fetching dataDatabase access
React/Next.js appsFile 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.js
bash

1. 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);
javascript

1.2 Run the Code#

node 01_variables.js
bash

1.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: boolean
plaintext

1.4 Variable Types Explained#

KeywordDescriptionExample
constCannot be reassignedconst name = "John";
letCan be reassignedlet age = 25;
varOld way (avoid)var old = "legacy";

1.5 Data Types#

TypeDescriptionExample
stringText"Hello"
numberNumeric42, 3.14
booleanTrue/Falsetrue, false
objectCollections{}, []
undefinedNot assignedundefined

1.6 Naming Conventions#

ConventionRuleValid ExamplesInvalid
camelCaseFirst word lowercase, each subsequent word capitalizeduserName, totalPrice, isLoggedInUsername, user_name
descriptiveUse meaningful namesuserAge, totalPricex, data, temp
Start with letterVariable names must start with a letter, $, or _name, _private, $count1name, @var
No spacesUse camelCase instead of spacesfirstName, lastNamefirst name
Case sensitivename and Name are differentmyVar, myvarN/A
No keywordsCan’t use reserved wordsuserCount, classNamevar, function, return

Tip: Choose names that describe what the variable holds, not how it’s used. For example, prefer userName over data.

1.7 Assignment#

  1. Create 02_assignment.js
  2. Store your name, age, and favorite programming language
  3. Print them + print typeof each 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;
javascript

2.2 Run the Code#

node 02_comments.js
bash

2.3 Expected Result#

Hello
Karn
25
plaintext

Notice: Comments are not displayed in the output. JavaScript completely ignores them.

2.4 When to Use Comments#

Use CaseExample
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 5 is not helpful.

2.5 Comment Syntax Reference#

SyntaxTypeUse For
// commentSingle-lineShort notes, inline explanations
/* comment */Multi-lineLonger descriptions, documentation

2.6 Assignment + IDE Shortcuts#

Task: Create 02_assignment.js and practice using keyboard shortcuts for commenting.

VS Code Shortcuts

ActionWindows/LinuxmacOS
Toggle Line CommentCtrl + /Cmd + /
Toggle Block CommentShift + Alt + AShift + Option + A
Copy Line UpShift + Alt + UpShift + Option + Up
Move Line Up/DownAlt + Up/DownOption + Up/Down

Practice Steps

  1. Create 02_assignment.js

  2. Type the following code (without comments first):

    const name = "YourName"
    const age = 25
    console.log(name)
    console.log(age)
    javascript
  3. Practice Shortcuts:

    • Go to line console.log(name) and press Ctrl + / (Windows) or Cmd + / (Mac) → line gets commented
    • Go to line const age = 25 and press Ctrl + / again → line gets commented
    • Press Ctrl + / again → uncomment
  4. Practice Block Comment:

    • Select multiple lines (e.g., from console.log(name) to console.log(age))
    • Press Shift + Alt + A (Windows) or Shift + Option + A (Mac)
    • Selected code gets wrapped in /* ... */

Tip: Building keyboard shortcut habits will dramatically increase your coding speed. Press Ctrl + Shift + P and 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);
javascript

3.2 Run the Code#

node 03_operators.js
bash

3.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=30
plaintext

3.4 Operators Reference#

OperatorDescriptionExample
+Addition5 + 3 = 8
-Subtraction5 - 3 = 2
*Multiplication5 * 3 = 15
/Division6 / 3 = 2
%Modulus (remainder)5 % 3 = 2
`Template literal`${var}`

3.5 Assignment#

  1. Create 03_assignment.js
  2. Given price=120 and discount=15 (%), calculate final price
  3. 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");
}
javascript

4.2 Run the Code#

node 04_conditionals.js
bash

4.3 Expected Result#

Grade: B
plaintext

4.4 Comparison Operators#

OperatorDescriptionExample
===Equal value and type5 === "5"false
!==Not equal value or type5 !== "5"true
>Greater than10 > 5true
<Less than5 < 10true
>=Greater or equal5 >= 5true
<=Less or equal5 <= 5true

4.5 Logical Operators#

OperatorDescriptionExample
&&ANDtrue && falsefalse
||ORtrue || falsetrue
!NOT!truefalse

4.6 Assignment#

  1. Create 04_assignment.js
  2. Use const hour = 14;
  3. If hour < 12 print "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--;
}
javascript

5.2 Run the Code#

node 05_loops.js
bash

5.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 = 1
plaintext

5.4 Loop Types#

LoopUse WhenExample
forKnown iterationsfor (let i = 0; i < 10; i++)
whileUnknown iterationswhile (condition)
for...ofIterate arraysfor (item of array)
for...inIterate objectsfor (key in object)

5.5 Assignment#

  1. Create 05_assignment.js
  2. 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));
javascript

6.2 Run the Code#

node 06_functions.js
bash

6.3 Expected Result#

add(2, 5) = 7
multiply(3, 4) = 12
plaintext

6.4 Function Syntax Comparison#

TypeSyntaxUse Case
Function Declarationfunction name() {}General use
Function Expressionconst name = function() {}Callbacks
Arrow Functionconst name = () => {}Short, callbacks

6.5 Function Naming Conventions#

ConventionRuleValid ExamplesInvalid
camelCaseFirst word lowercase, subsequent words capitalizedgetUserData, calculateTotal, isValidGetUserData, get_user_data
Verb-firstStart with a verb describing the actionfetchUser, saveData, deleteItemuser, data, item
BooleansUse is, has, can, should prefixisLoggedIn, hasPermission, canEditlogged, permission, editable
HandlersUse handle prefix for event handlershandleSubmit, handleClicksubmit, onClick

Good vs Bad Examples:

BadGoodReason
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 than calc(p, t).

6.6 Assignment#

  1. Create 06_assignment.js
  2. Write isAdult(age) returning true/false (adult >= 18)
  3. 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(", "));
javascript

7.2 Run the Code#

node 07_arrays_objects.js
bash

7.3 Expected Result#

fruits: [ 'apple', 'banana', 'mango', 'orange' ]
first fruit: apple
count: 4
user name: Karn
user roles: admin, teacher
plaintext

7.4 Array Methods#

MethodDescriptionExample
push()Add to endarr.push(5)
pop()Remove from endarr.pop()
unshift()Add to startarr.unshift(5)
shift()Remove from startarr.shift()
map()Transform arrayarr.map(x => x*2)
filter()Filter arrayarr.filter(x => x>5)

7.5 Assignment#

  1. Create 07_assignment.js
  2. Make an array of 5 numbers
  3. Compute the sum using a loop
  4. 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);
javascript

8.2 Run the Code#

node 08_array_of_objects.js
bash

8.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' }
plaintext

8.4 Common Operations#

OperationMethodExample
Access itemarr[index]users[0].name
Find itemarr.find()users.find(u => u.id === 1)
Filter itemsarr.filter()users.filter(u => u.role === 'admin')
Transform itemsarr.map()users.map(u => u.name)
Add itemarr.push()users.push(newUser)

8.5 Assignment#

  1. Create 08_assignment.js
  2. Make an array of 3 products (each with id, name, price)
  3. Print all products
  4. 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 };
javascript

File: 09_modules.js

// 09_modules.js
const { square } = require("./mathUtil");

console.log("square(5) =", square(5));
console.log("square(12) =", square(12));
javascript

9.2 Run the Code#

node 09_modules.js
bash

9.3 Expected Result#

square(5) = 25
square(12) = 144
plaintext

9.4 Module Syntax#

SyntaxTypeExample
require()CommonJS (Node.js)const mod = require('./mod')
importES Modulesimport { mod } from './mod.js'
module.exportsCommonJS exportmodule.exports = { func }
exportES Module exportexport function func() {}

9.5 Assignment#

  1. Add a new function cube(n) in mathUtil.js
  2. Use it in 09_assignment.js and 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();
javascript

10.2 Run the Code#

node 10_async.js
bash

10.3 Expected Result#

Start
After 500ms
After 300ms
plaintext

10.4 Async Concepts#

ConceptDescription
PromiseRepresents eventual completion
asyncDeclares an async function
awaitPauses until Promise resolves
setTimeout()Node.js built-in promisified delay (Node 16+)

Note: setTimeout from node:timers/promises is available in Node.js 16+. For browser code, you’d still need to wrap setTimeout in 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();
javascript

Run the Code

node 11_errors.js
bash

Expected Result

Fetching user...
Error caught: Invalid user ID
User: { id: 123, name: 'User 123' }
Program continues...
plaintext

Key Points:

  • try - Code that might throw an error
  • catch - Handles the error if one occurs
  • throw - Manually throw an error

10.6 Assignment#

Create a file named 12_assignment.js and write a countdown function that:

  • Takes a number n as input
  • Prints numbers from n down to 1 with a 300ms delay between each number
  • Stops automatically when reaching 1

Hint: Use setInterval() to repeatedly execute code and clearInterval() to stop it.


11. Best Practices#

11.1 What to Do#

  • Use const by default, let when 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
JavaScript Tutorial with Node.js
Author กานต์ ยงศิริวิทย์ / Karn Yongsiriwit
Published at January 17, 2026

Loading comments...

Comments 0