JavaScript is a programming language that makes web pages interactive. You can use it to respond to button clicks, process forms, call APIs, and also write backend programs with Node.js. This article starts with a few of the most commonly used concepts.
1. Run Your First Piece of Code
Open the browser developer tools, switch to the Console, and enter:
console.log('你好,JavaScript!');
console.log() is used to output information and is a common tool for observing how a program runs.
2. Use Variables to Store Data
Prefer const; if a variable needs to be reassigned, then use let.
const name = '小明';
let count = 1;
count += 1;
console.log(name, count); // 小明 2
const only restricts reassigning the variable; properties inside the object can still be modified.
3. Get to Know Basic Data Types
const title = '学习笔记'; // 字符串
const price = 19.9; // 数字
const isPublished = true; // 布尔值
const emptyValue = null; // 主动表示空值
let pendingValue; // undefined
When comparing values, usually use === to avoid surprises caused by implicit type coercion.
4. Conditionals and Loops
const score = 85;
if (score >= 60) {
console.log('通过');
} else {
console.log('继续练习');
}
for (let i = 1; i <= 3; i++) {
console.log('第 ' + i + ' 次练习');
}
5. Organize Logic with Functions
Functions can receive input, perform operations, and return results.
function add(a, b) {
return a + b;
}
const double = (value) => value * 2;
console.log(add(2, 3)); // 5
console.log(double(4)); // 8
6. Arrays and Objects
Arrays are good for storing lists, and objects are good for describing a single thing.
const languages = ['JavaScript', 'TypeScript', 'Python'];
const user = { name: '小明', age: 18 };
for (const language of languages) {
console.log(language);
}
const lengths = languages.map((language) => language.length);
console.log(user.name, lengths);
map() returns a new array; when you need to filter elements, you can use filter().
7. Add Interactivity to a Web Page
Suppose the page has a button and a text area:
<button id="hello-button">打个招呼</button>
<p id="message"></p>
Run the following code after the page elements have loaded:
const button = document.querySelector('#hello-button');
const message = document.querySelector('#message');
button.addEventListener('click', () => {
message.textContent = '欢迎开始学习 JavaScript!';
});
When inserting plain text, use textContent; do not write untrusted input directly into innerHTML.
8. Understand Asynchronous Operations
Requesting an API takes time; you can use async/await to wait for the result and try/catch to handle failures.
async function loadPost() {
try {
const response = await fetch('/api/example');
if (!response.ok) throw new Error('请求失败');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
The API address here is just an example; you need to replace it with the actual API you provide before it can run.
Hands-on Practice
Try making a counter: click a button to increase the number by one, then add a reset button. You'll practice variables, functions, DOM queries, and event listeners at the same time.
When you run into problems, first look at the error in the console, then reduce the program to the simplest reproducible example. Writing several small programs is more effective than trying to memorize all the syntax at once.
