1. JavaScript 是什么?能用来做什么

JavaScript(简称 JS)是一门运行在浏览器和**服务器(Node.js)**上的编程语言。

常见用途:

  • Web 前端交互:按钮点击、表单校验、动画、与后端接口通信

  • Node.js 后端:写 API 服务、脚本工具、自动化任务

  • 桌面与跨端:Electron、Tauri 等


2. 准备环境:浏览器控制台 / Node.js

2.1 浏览器控制台

打开任意网页,按 F12 → Console,就能直接运行 JS。

试试:

console.log('Hello JavaScript');

2.2 Node.js

安装 Node.js 后,在终端运行:

node -v

然后进入交互式 REPL:

node

在里面输入:

console.log('Hello from Node');

3. 第一个 JS 程序

创建文件 hello.js

const message = 'Hello JavaScript';
console.log(message);

运行:

node hello.js

4. 基础语法:变量、常量、类型

4.1 变量与常量:let / const

  • const:常量引用(推荐默认使用)

  • let:可重新赋值的变量

const name = 'Alice';
let count = 0;
count = count + 1;

console.log(name, count);

不推荐使用 var(历史遗留,作用域规则容易踩坑)。

4.2 常见数据类型

const n = 42;              // number
const s = 'hello';         // string
const ok = true;           // boolean
const nothing = null;      // null
let unknown;               // undefined
const big = 9007199254740993n; // bigint
const id = Symbol('id');   // symbol

console.log(typeof n, typeof s, typeof ok);

对象类型:

const obj = { x: 1, y: 2 };
const arr = [1, 2, 3];
const fn = () => 'hi';

console.log(typeof obj, Array.isArray(arr), typeof fn);

5. 运算与比较(易错点)

5.1 === vs ==

  • ===:严格相等(推荐)

  • ==:会做类型转换(容易出现意外)

console.log(0 == false);   // true(不推荐依赖)
console.log(0 === false);  // false(推荐)

5.2 真值/假值

假值(falsy)常见有:false0''nullundefinedNaN

if ('') {
  console.log('不会进入');
}

if ('0') {
  console.log('会进入');
}

6. 控制流:if / for / while

const score = 85;

if (score >= 90) {
  console.log('A');
} else if (score >= 60) {
  console.log('Pass');
} else {
  console.log('Fail');
}

遍历数组:

const nums = [1, 2, 3];

for (const n of nums) {
  console.log(n);
}

7. 函数:声明、箭头函数、参数默认值

function add(a, b) {
  return a + b;
}

const add2 = (a, b) => a + b;

function greet(name = '朋友') {
  return `你好,${name}`;
}

console.log(add(1, 2));
console.log(add2(3, 4));
console.log(greet());

可变参数:

function sum(...nums) {
  return nums.reduce((acc, x) => acc + x, 0);
}

console.log(sum(1, 2, 3));

8. 数组与对象(最常用)

8.1 数组

const arr = [10, 20, 30];

arr.push(40);
console.log(arr.length);

const doubled = arr.map((x) => x * 2);
const filtered = arr.filter((x) => x >= 20);

console.log(doubled, filtered);

8.2 对象

const user = {
  id: 1,
  name: 'Alice',
};

user.age = 18;
console.log(user.name, user['age']);

const { id, name } = user;
console.log(id, name);

9. 异步基础:Promise / async-await

JS 经常用于 I/O(网络、文件),这些操作通常是异步的。

9.1 Promise 示例

function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

wait(500).then(() => console.log('500ms 后执行'));

9.2 async/await(推荐写法)

async function main() {
  await wait(300);
  console.log('300ms 后执行');
}

main().catch(console.error);

浏览器里调用接口(Fetch):

async function fetchJson(url) {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

// 示例 URL 请换成你自己的接口
// fetchJson('/api/user').then(console.log).catch(console.error);

10. 模块:import/export(现代写法)

在 Node.js 或现代构建工具里,你会用模块来拆分代码。

math.js

export function add(a, b) {
  return a + b;
}

main.js

import { add } from './math.js';

console.log(add(1, 2));

Node.js 里是否能直接使用 import,取决于项目的模块设置(package.jsontype 字段等)。


11. 下一步学什么

建议学习路线:

  1. JS 语言核心:作用域、闭包、原型与继承、this

  2. 异步与事件循环:Promise 链、微任务/宏任务

  3. 浏览器方向:DOM、事件、Fetch、Storage、调试

  4. Node.js 方向:文件系统、HTTP、包管理(npm)、工程化

  5. 工程化:ESLint/Prettier、测试(Vitest/Jest)、构建(Vite)

如果你后续希望我继续输出系列文章,可以从“JavaScript 基础类型与常用对象”或“DOM + 事件 + Fetch 实战”开始。