JavaScript ES2017

Async/await and object improvements

⚡ What is ES2017?

ES2017 introduced async/await, making asynchronous code much easier to read and write. It also added useful object methods and string padding functions.


// ES2017 introduced async/await
async function fetchData() {
    const response = await fetch('/api/data');
    const data = await response.json();
    return data;
}

// Much cleaner than promises!
fetchData().then(data => console.log(data));
                                    

Output:

// Data from API will be logged

ES2017 Features

🔄

Async/Await

Cleaner asynchronous code

async function getData() {
  const result = await fetch(url);
  return result;
}
📋

Object Methods

Object.values() & Object.entries()

Object.values(obj)
Object.entries(obj)
📏

String Padding

padStart() & padEnd() methods

"5".padStart(3, "0")
// "005"
🏷️

Trailing Commas

Commas in function parameters

function test(
  a,
  b,
  c, // trailing comma OK
) {}

🔹 Async/Await

Write asynchronous code that looks synchronous:

// Old way with Promises
function fetchUserData() {
    return fetch('/api/user')
        .then(response => response.json())
        .then(user => {
            return fetch(`/api/posts/${user.id}`);
        })
        .then(response => response.json())
        .then(posts => {
            console.log('User posts:', posts);
            return posts;
        })
        .catch(error => {
            console.error('Error:', error);
        });
}

// New way with async/await
async function fetchUserDataAsync() {
    try {
        const userResponse = await fetch('/api/user');
        const user = await userResponse.json();
        
        const postsResponse = await fetch(`/api/posts/${user.id}`);
        const posts = await postsResponse.json();
        
        console.log('User posts:', posts);
        return posts;
    } catch (error) {
        console.error('Error:', error);
    }
}

// Simple example with timeout
function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function example() {
    console.log('Starting...');
    await delay(1000);
    console.log('After 1 second');
    await delay(1000);
    console.log('After 2 seconds');
}

example();

Output:

Starting...
(1 second delay)
After 1 second
(1 second delay)
After 2 seconds

🔹 Object.values() and Object.entries()

New methods to work with object data:

const person = {
    name: "Alice",
    age: 30,
    city: "New York",
    job: "Developer"
};

// Object.keys() (existed before ES2017)
const keys = Object.keys(person);
console.log("Keys:", keys);

// Object.values() - NEW in ES2017
const values = Object.values(person);
console.log("Values:", values);

// Object.entries() - NEW in ES2017
const entries = Object.entries(person);
console.log("Entries:", entries);

// Practical use: Convert object to array for processing
const scores = { math: 95, english: 87, science: 92 };

// Calculate average using Object.values()
const average = Object.values(scores).reduce((sum, score) => sum + score, 0) / Object.values(scores).length;
console.log("Average score:", average);

// Create formatted list using Object.entries()
Object.entries(scores).forEach(([subject, score]) => {
    console.log(`${subject}: ${score}%`);
});

Output:

Keys: ["name", "age", "city", "job"]
Values: ["Alice", 30, "New York", "Developer"]
Entries: [["name", "Alice"], ["age", 30], ["city", "New York"], ["job", "Developer"]]
Average score: 91.33
math: 95%
english: 87%
science: 92%

🔹 String Padding

Add padding to strings with padStart() and padEnd():

// padStart() - add padding to the beginning
const number = "5";
const paddedStart = number.padStart(3, "0");
console.log(paddedStart); // "005"

// padEnd() - add padding to the end
const name = "John";
const paddedEnd = name.padEnd(10, ".");
console.log(paddedEnd); // "John......"

// Practical examples
const prices = [5.99, 12.50, 100.00];
console.log("Price List:");
prices.forEach(price => {
    const formatted = price.toFixed(2).padStart(8, " ");
    console.log(`$${formatted}`);
});

// Format time
function formatTime(hours, minutes, seconds) {
    const h = hours.toString().padStart(2, "0");
    const m = minutes.toString().padStart(2, "0");
    const s = seconds.toString().padStart(2, "0");
    return `${h}:${m}:${s}`;
}

console.log(formatTime(9, 5, 3));  // "09:05:03"
console.log(formatTime(14, 30, 45)); // "14:30:45"

// Create simple table
const data = [
    { name: "Alice", score: 95 },
    { name: "Bob", score: 87 },
    { name: "Charlie", score: 92 }
];

console.log("Name".padEnd(10) + "Score");
console.log("-".repeat(15));
data.forEach(item => {
    console.log(item.name.padEnd(10) + item.score);
});

Output:

005
John......
Price List:
$ 5.99
$ 12.50
$ 100.00
09:05:03
14:30:45
Name Score
---------------
Alice 95
Bob 87
Charlie 92

🔹 Trailing Commas in Functions

You can now add trailing commas in function parameters:

// Function definition with trailing comma
function createUser(
    name,
    email,
    age,
    city, // This trailing comma is now allowed
) {
    return {
        name,
        email,
        age,
        city
    };
}

// Function call with trailing comma
const user = createUser(
    "John Doe",
    "[email protected]",
    25,
    "New York", // This trailing comma is also allowed
);

console.log(user);

// This makes it easier to add/remove parameters
// and creates cleaner git diffs

Output:

{ name: "John Doe", email: "[email protected]", age: 25, city: "New York" }

🧠 Test Your Knowledge

What keyword is used with async functions to wait for promises?