JavaScript 是 Web 的"通用语言":浏览器里它驱动页面交互,Node.js 让它跑在服务器端。本文用最短的篇幅,把最核心的语法讲清楚——变量、类型、运算符、流程控制与函数,看完就能读懂大多数代码。

1. 变量声明:var、let 与 const

ES6 之后推荐用 letconst:const 声明不可重新赋值的变量,let 声明可变的变量,var 存在函数作用域和变量提升等历史遗留问题,新代码应避免使用。

const PI = 3.14159;   // 常量,不可重新赋值
let count = 0;        // 可变变量
count = count + 1;    // 1

// var 的变量提升容易造成困惑
console.log(x);       // undefined(不是报错!)
var x = 10;

2. 数据类型与 typeof

JS 有 8 种内置类型,其中 7 种是原始类型。用 typeof 可以快速判断类型,但要注意几个特例。

typeof 42          // "number"
typeof "hello"     // "string"
typeof true        // "boolean"
typeof undefined   // "undefined"
typeof null        // "object"  ← 历史遗留 bug,注意!
typeof {}          // "object"
typeof []          // "object"  ← 数组也是 object
typeof function(){}// "function"

3. 运算符与隐式转换

== 会做类型转换,=== 严格要求类型和值都相等。团队规范几乎都要求使用 ===

1 == "1"    // true(做了隐式转换)
1 === "1"   // false(类型不同)

// 逻辑运算符返回的不一定是布尔值
const name = userInput || "匿名用户";  // 取第一个"真值"
const ok = a > 0 && b > 0;            // 全真才为真
const neg = !ok;                       // 取反

4. 条件与循环

// if / else if / else
const score = 85;
if (score >= 90) {
  console.log("优秀");
} else if (score >= 60) {
  console.log("及格");
} else {
  console.log("加油");
}

// for 循环
for (let i = 0; i < 5; i++) {
  console.log(i);   // 0 1 2 3 4
}

// while 循环
let n = 3;
while (n > 0) {
  console.log(n);
  n--;
}

5. 函数:声明式与箭头函数

// 函数声明
function add(a, b) {
  return a + b;
}

// 箭头函数(ES6)
const add2 = (a, b) => a + b;

// 默认参数与剩余参数
function greet(name = "朋友", ...others) {
  console.log(`你好,${name}!`);
}
greet();            // 你好,朋友!
greet("小明");       // 你好,小明!

6. 字符串与模板字符串

反引号包裹的模板字符串可以嵌入表达式、保留换行,是拼接字符串的首选。

const user = "Ada";
const age = 18;
const msg = `${user}今年${age}岁,
欢迎来到 CodeLab!`;
console.log(msg);

7. 给初学者的三个建议

💡 语法只是地图,练习才是走路。建议用变量、循环和函数写一个"猜数字"小游戏,把本文的知识全部用上。