const PI = 3.141593;
console.log(PI); PI = 3; // 报错: Uncaught TypeError: Assignment to constant variable. const PI = 3.1; // 报错: Uncaught SyntaxError: Identifier 'PI' has already been declared
{
let a = 10; var b = 1; } console.log(a); // 报错: Uncaught ReferenceError: a is not defined console.log(b); // 输出: 1 上面代码在代码块之中,分别用let和var声明了两个变量。然后在代码块之外调用这两个变量,结果let声明的变量报错,var声明的变量返回了正确的值。这表明,let声明的变量只在它所在的代码块有效。
for (let i = 0; i < 5; i++) {
console.log(i); } console.log(i) // 报错: ReferenceError: i is not defined
function test() {
let x = 1; let y = 2; { let x = 10; let y = 20; } console.log(x, y); } test(); // 输出: 1 2 上面的函数有两个代码块,都声明了变量x, y,运行后输出1 2。这表示外层代码块不受内层代码块的影响。如果使用var定义变量n,最后输出的值就是10 20。
let square = (x) => x * x;
console.log('5 * 5 = ', square(5)); // 输出: 5 * 5 = 25
let add = (x, y) => x + y;
console.log('2 + 3 = ', add(2, 3)); // 输出: 2 + 3 = 5
let total = () => square(add(5, 3)); console.log( '(5 + 3)*(5 + 3) = ', total()); // 输出: (5 + 3)*(5 + 3) = 64
var array = [1, 2, 3]; array.forEach(v => console.log(v)); // 输出: 1 2 3
var bob = {
_name: "Bob", _friends: ['Tom', 'Jerry'], printFriends() { this._friends.forEach(f => console.log(this._name + " knows " + f)); } } bob.printFriends(); // 输出: Bob knows Tom Bob knows Jerry
function logName(name = 'Unknown') {
console.log('Name: ', name); } logName(); // 输出:Unknown logName('JavaScript'); // 输出:JavaScript
function add(...numArray) { let sum = 0; for (let num of numArray) { sum += num; } return sum; } console.log(add(1, 2, 3)); // 输出:6 console.log(add(1, 2, 3, 4, 5)); // 输出:15
function add(x, y, z) {
return x + y + z; } console.log(add(...[1, 2, 3])); // 输出:6 console.log(add(...[3, 4, 5])); // 输出:12