iT邦幫忙

2025 iThome 鐵人賽

DAY 4
0
Modern Web

現在就學Node.js系列 第 4

Node.js 基本語法入門 -Day4

  • 分享至 

  • xImage
  •  

今天要進一步學習 Node.js 的基本語法,掌握變數、資料型別、函式、條件判斷、迴圈,
還有最重要的 模組化Promise 非同步基礎。其實這也是JavaScript 的基本概念。

這些內容不僅是 Node.js 的基石,也是之後能寫出 API、連接資料庫的基礎概念。

變數與資料型別

在 JavaScript / Node.js 中,有三種主要的變數宣告方式:

// var:舊時代語法,不建議再用
var a = 10;
var a = 20; // 可以重複宣告,容易踩坑

// let:區塊作用域,可重新賦值
let b = 15;
b = 30;

// const:常數,宣告後不可重新賦值
const c = 100;
// c = 200; // ❌ 會報錯

常見資料型別可以分成兩大類:

  • 原始型別 (Primitive)

    Number, String, Boolean, null, undefined, Symbol

  • 引用型別 (Reference)

    Object, Array, Function

範例:

let num = 42;
let str = "Hello, Node.js";
let flag = true;
let nothing = null;
let notDefined;
let arr = [1, 2, 3];
let obj = { name: "Alice", age: 25 };

函式:多種寫法

JavaScript 的函式有多種宣告方式:

// 傳統函式宣告
function add(x, y) {
  return x + y;
}

// 函式表達式
const multiply = function (x, y) {
  return x * y;
};

// 箭頭函式(ES6)
const divide = (x, y) => x / y;

呼叫函式並輸出結果:

console.log(add(5, 7));        // 12
console.log(multiply(4, 3));   // 12
console.log(divide(20, 5));    // 4

條件語句與迴圈

條件判斷:

const score = 75;

if (score >= 90) {
  console.log("優秀");
} else if (score >= 60) {
  console.log("及格");
} else {
  console.log("不及格");
}

常見迴圈寫法:

// for 迴圈
for (let i = 0; i < 3; i++) {
  console.log(`第 ${i + 1} 次`);
}

// while 迴圈
let j = 2;
while (j >= 0) {
  console.log(j);
  j--;
}

// for...of:遍歷陣列
for (const item of [10, 20, 30]) {
  console.log(item);
}

Promise

Node.js 最大特色就是「非同步處理」。為了避免 callback hell(回呼地獄),我們會用 Promise 讓程式碼更清晰。

// 一個簡單的延遲函式
const wait = (ms) =>
  new Promise((resolve) => {
    setTimeout(() => {
      resolve(`等了 ${ms} 毫秒`);
    }, ms);
  });

// 使用 Promise
wait(1000)
  .then((msg) => {
    console.log(msg); // 等了 1000 毫秒
    return wait(500);
  })
  .then((msg2) => {
    console.log(msg2); // 等了 500 毫秒
  })
  .catch((err) => {
    console.error("錯誤發生:", err);
  });

📦 模組化:require 與 module.exports

隨著程式越來越大,不可能把所有程式碼都塞在一個檔案。

Node.js 提供 模組系統,讓我們可以把功能拆開管理。

// mathUtils.js
function sum(a, b) {
  return a + b;
}
function subtract(a, b) {
  return a - b;
}
module.exports = { sum, subtract };

// app.js
const { sum, subtract } = require("./mathUtils");

console.log(sum(3, 4));        // 7
console.log(subtract(10, 6));  // 4

這樣就能清楚分工,把計算邏輯放在 mathUtils.js,主程式 app.js 專心負責流程。

小練習

請寫一個 grade.js 模組,輸入學生分數(0~100),輸出等級:

  • 90 以上 → A
  • 80 ~ 89 → B
  • 70 ~ 79 → C
  • 60 ~ 69 → D
  • 59 以下 → F

並在 app.js 呼叫這個模組,印出不同分數的結果。

小結

今天我們掌握了:

  • JavaScript 的基本語法(變數、型別、函式、條件、迴圈)
  • Promise 的非同步處理
  • Node.js 模組系統的基礎(requiremodule.exports

這些基礎知識會是往後 Node.js 專案開發中常用到的知識點。

小練習解答:

grade.js

// grade.js
function getGrade(score) {
  if (score >= 90) {
    return 'A'
  } else if (score >= 80) {
    return 'B'
  } else if (score >= 70) {
    return 'C'
  } else if (score >= 60) {
    return 'D'
  } else {
    return 'F'
  }
}

module.exports = getGrade

app.js

// app.js
const getGrade = require('./grade')

console.log('Score 95 →', getGrade(95)) // A
console.log('Score 85 →', getGrade(85)) // B
console.log('Score 75 →', getGrade(75)) // C
console.log('Score 65 →', getGrade(65)) // D
console.log('Score 50 →', getGrade(50)) // F


上一篇
認識npm、建立專案與必備開發套件 - Day3
下一篇
CommonJS (CJS) vs ES Modules (ESM) — Node.js 模組系統 - Day5
系列文
現在就學Node.js5
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言