ECMAScript, or ES, is a standardized version of JavaScript. Because all major browsers follow this specification, the terms ECMAScript and JavaScript are interchangeable.
Most of the JavaScript you’ve learned up to this point was in ES5 (ECMAScript 5), which was finalized in 2009. While you can still write programs in ES5, JavaScript is constantly evolving, and new features are released every year.
ES6, released in 2015, added many powerful new features to the language. In this course, you’ll learn these new features, including arrow functions, destructuring, classes, promises, and modules.
function checkScope() {
let i = ‘function scope’;
if (true) {
let i = ‘block scope’;
console.log(‘Block scope i is: ‘, i);
}
console.log(‘Function scope i is: ‘, i);
return i;
}
checkScope();
Block scope i is: block scope
Function scope i is: function scope
const s = [5, 7, 2];
function editInPlace() {
// Only change code below this line
s[0] = 2;
s[1] = 5;
s[2] = 7;
// Using s = [2, 5, 7] would be invalid
// Only change code above this line
}
editInPlace();
console.log(s);
[ 2, 5, 7 ]
To ensure your data doesn’t change, JavaScript provides a function Object.freeze
to prevent data mutation.
function freezeObj() {
const MATH_CONSTANTS = {
PI: 3.14
};
// Only change code below this line
Object.freeze(MATH_CONSTANTS);
// 將PI = 3.14固定
// Only change code above this line
try {
MATH_CONSTANTS.PI = 99;
} catch(ex) {
console.log(ex);
}
return MATH_CONSTANTS.PI;
}
const PI = freezeObj();
console.log(PI);
3.14
var magic = function() {
return new Date();
};
可以改成下方的寫法
const magic = () => {
return new Date();
};
concat()
方法被用來合併兩個或多個陣列。此方法不會改變現有的陣列,回傳一個包含呼叫者陣列本身的值,作為代替的是回傳一個新陣列。
var myConcat = function(arr1, arr2) {
return arr1.concat(arr2);
};
console.log(myConcat([1, 2], [3, 4, 5]));
const myConcat = (arr1, arr2) => {
return arr1.concat(arr2);
};
console.log(myConcat([1, 2], [3, 4, 5]));
onst greeting = (name = "Anonymous") => "Hello " + name;
console.log(greeting("John"));
console.log(greeting());
// Only change code below this line
const increment = (number, value = 1) => number + value; 預設值=1
// Only change code above this line
console.log(increment(5,2)); 7
reduce()
方法將一個累加器及陣列中每項元素(由左至右)傳入回呼函式,將陣列化為單一值。
const sum = (x, y, z) => {
const args = [x, y, z];
return args.reduce((a, b) => a + b, 0);
}
可以使用…arg改寫成
const sum = (…args) => {
return args.reduce((a, b) => a + b, 0);
}
console.log(sum(0,1,2)); 3
ES5 code
var arr = [6, 89, 3, 45];
var maximus = Math.max.apply(null, arr);
ES6 code
const arr = [6, 89, 3, 45];
const maximus = Math.max(...arr);
const arr1 = [‘JAN’, ‘FEB’, ‘MAR’, ‘APR’, ‘MAY’];
let arr2;
// 把arr1的內容改成…arr的形式
arr2 = […arr1]; // Change this line
console.log(arr2);
ES5 code
const user = { name: 'John Doe', age: 34 };
const name = user.name;
const age = user.age;
ES6 code
const { name, age } = user;
const HIGH_TEMPERATURES = {
yesterday: 75,
today: 77,
tomorrow: 80
};
// Only change code below this line
// const today = HIGH_TEMPERATURES.today;
// const tomorrow = HIGH_TEMPERATURES.tomorrow;
const { today, tomorrow } = HIGH_TEMPERATURES;
// Only change code above this line
const user = { name: 'John Doe', age: 34 };
轉化寫法
const { name: userName, age: userAge } = user;
const HIGH_TEMPERATURES = {
yesterday: 75,
today: 77,
tomorrow: 80
};
// Only change code below this line
// const highToday = HIGH_TEMPERATURES.today;
// const highTomorrow = HIGH_TEMPERATURES.tomorrow;
const { today: highToday, tomorrow: highTomorrow } = HIGH_TEMPERATURES;
// Only change code above this line
ES5 mode
const user = {
johnDoe: {
age: 34,
email: 'johnDoe@freeCodeCamp.com'
}
};
ES6 mode
const { johnDoe: { age, email }} = user;
const { johnDoe: { age: userAge, email: userEmail }} = user;
const LOCAL_FORECAST = {
yesterday: { low: 61, high: 75 },
today: { low: 64, high: 77 },
tomorrow: { low: 68, high: 80 }
};
// Only change code below this line
// ES5 code
// const lowToday = LOCAL_FORECAST.today.low;
// const highToday = LOCAL_FORECAST.today.high;
// ES6 code
const { today: { low: lowToday, high: highToday }} = LOCAL_FORECAST;
// Only change code above this line
let a = 8, b = 6;
[a, b] = [b, a];
const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];
console.log(a, b);
console.log(arr);
const source = [1,2,3,4,5,6,7,8,9,10];
function removeFirstTwo(list) {
// Only change code below this line
const [a, b, …arr] = list; // Change this line
// Only change code above this line
return arr;
}
const arr = removeFirstTwo(source);
console.log(arr);
[ 3, 4, 5, 6, 7, 8, 9, 10 ]
const profileUpdate = (profileData) => {
const { name, age, nationality, location } = profileData;
}
const profileUpdate = ({ name, age, nationality, location }) => {
}
const stats = {
max: 56.78,
standard_deviation: 4.34,
median: 34.54,
mode: 23.87,
min: -0.75,
average: 35.85
};
// Only change code below this line
const half = ({ max, min}) => (max + min) / 2.0;
// Only change code above this line
half(stats)
console.log(half(stats));
const result = {
success: [“max-length”, “no-amd”, “prefer-arrow-functions”],
failure: [“no-var”, “var-on-top”, “linebreak”],
skipped: [“no-extra-semi”, “no-dup-keys”]
};
function makeList(arr) {
// Only change code below this line
// 1 way:
// const failureItems = [];
// for (let i = 0; i < arr.length; i++){
// failureItems.push(`<li class=”text-warning”>${arr[i]}</li>`);
// }
// 2 way:
const failureItems = arr.map(item => `<li class=”text-warning”>${item}</li>`);
// Only change code above this line
return failureItems;
}
const failuresList = makeList(result.failure);
console.log(failuresList);
[ ‘<li class=”text-warning”>no-var</li>’,
‘<li class=”text-warning”>var-on-top</li>’,
‘<li class=”text-warning”>linebreak</li>’ ]
const createPerson = (name, age, gender) => {
“use strict”;
// Only change code below this line
return {
name,
age,
gender
};
// Only change code above this line
};
ES5
const person = {
name: "Taylor",
sayHello: function() {
return `Hello! My name is ${this.name}.`;
}
};
ES6
const person = {
name: "Taylor",
sayHello() {
return `Hello! My name is ${this.name}.`;
}
};
// Only change code below this line
const bicycle = {
gear: 2,
setGear(newGear) {
this.gear = newGear;
}
};
// Only change code above this line
bicycle.setGear(48);
console.log(bicycle.gear);
// Only change code below this line
class Vegetable {
constructor(name) {
this.name = name;
}
}
// Only change code above this line
const carrot = new Vegetable(‘carrot’);
console.log(carrot.name); // Should display ‘carrot’
// Only change code below this line
class Thermostat {
constructor(tmF) {
this.tmF = tmF;
}
// getter
get temperature() {
return 5/9 * (this.tmF – 32);
}
// setter
set temperature(celsius) {
this.tmF = (celsius * 9.0) / 5 + 32;
}
}
// Only change code above this line
const thermos = new Thermostat(76); // Setting in Fahrenheit scale
let temp = thermos.temperature; // 24.44 in Celsius
thermos.temperature = 26;
temp = thermos.temperature; // 26 in Celsius
console.log(temp); // 26
<html>
<body>
<!– Only change code below this line –>
<script type=”module” src=”index.js”></script>
<!– Only change code above this line –>
</body>
</html>
const uppercaseString = (string) => {
return string.toUpperCase();
}
const lowercaseString = (string) => {
return string.toLowerCase()
}
export { uppercaseString, lowercaseString };
import { uppercaseString, lowercaseString } from ‘./string_functions.js’;
// Only change code above this line
uppercaseString(“hello”);
lowercaseString(“WORLD!”);
import * as stringFunctions from “./string_functions.js”;
// Only change code above this line
stringFunctions.uppercaseString(“hello”);
stringFunctions.lowercaseString(“WORLD!”);
export default function subtract(x, y) {
return x – y;
}
import subtract from “./math_functions.js”;
// Only change code above this line
subtract(7,4);
const makeServerRequest = new Promise((resolve, reject) => {
});
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer represents a response from a server
let responseFromServer;
if(responseFromServer) {
resolve(“We got the data”);
} else {
reject(“Data not received”);
}
});
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer is set to true to represent a successful response from a server
let responseFromServer = true;
if(responseFromServer) {
resolve(“We got the data”);
} else {
reject(“Data not received”);
}
});
makeServerRequest.then(result => {
console.log(result);
});
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer is set to false to represent an unsuccessful response from a server
let responseFromServer = false;
if(responseFromServer) {
resolve(“We got the data”);
} else {
reject(“Data not received”);
}
});
makeServerRequest.then(result => {
console.log(result);
});
makeServerRequest.catch(error => {
console.log(error);
});
留言