ES6

Ace your homework & exams now with Quizwiz!

What is a promise?

A promise in JavaScript is exactly what it sounds like - you use it to make a promise to do something, usually asynchronously. When the task completes, you either fulfill your promise or fail to do so. Promise is a constructor function, so you need to use the new keyword to create one. It takes a function, as its argument, with two parameters - resolve and reject. These are methods used to determine the outcome of the promise. The syntax looks like this: const myPromise = new Promise((resolve, reject) => { });

How do you make a default export?

Below are examples using export default: // named function export default function add(x, y) { return x + y; } // anonymous function export default function(x, y) { return x + y; } Since export default is used to declare a fallback value for a module or file, you can only have one value be a default export in each module or file. Additionally, you cannot use export default with var, let, or const

When destructuring an object how would you assign a variable name to a value?

Destructuring allows you to assign a new variable name when extracting values. You can do this by putting the new name after a colon when assigning the value. const user = { name: 'John Doe', age: 34 }; Here's how you can give new variable names in the assignment: const { name: userName, age: userAge } = user; // userName = 'John Doe', userAge = 34 You may read it as "get the value of user.name and assign it to a new variable named userName" and so on.

What is the spread operator?

ES6 introduces the spread operator, which allows us to expand arrays and other expressions in places where multiple parameters or elements are expected. const arr = [6, 89, 3, 45]; const maximus = Math.max(...arr); // returns 89 ...arr returns an unpacked array. In other words, it spreads the array. However, the spread operator only works in-place, like in an argument to a function or in an array literal. The following code will not work: const spreaded = ...arr; // will throw a syntax error

What is the Rest parameter?

In order to help us create more flexible functions, ES6 introduces the rest parameter for function parameters. With the rest parameter, you can create functions that take a variable number of arguments. These arguments are stored in an array that can be accessed later from inside the function. function howMany(...args) { return "You have passed " + args.length + " arguments."; } console.log(howMany(0, 1, 2)); // You have passed 3 arguments. console.log(howMany("string", null, [1, 2, 3], { })); // You have passed 4 arguments.

When using const to define a function or array does that mean that the function or array are immutable.

No, only the variable identifier is immutable. const s = [5, 6, 7]; s = [1, 2, 3]; // throws error, trying to assign a const s[2] = 45; // works just as it would with an array declared with var or let console.log(s); // returns [5, 6, 45]

What is the problem with declaring variables with the var keyword?

One of the biggest problems with declaring variables with the var keyword is that you can overwrite variable declarations without an error. var camper = 'James'; var camper = 'David'; console.log(camper); // logs 'David'

What are the 3 states of a promise?

Pending, fulfilled and rejected

What is the purpose of the promise method .then()?

Promises are most useful when you have a process that takes an unknown amount of time in your code (i.e. something asynchronous), often a server request. When you make a server request it takes some amount of time, and after it completes you usually want to do something with the response from the server. This can be achieved by using the then method. The then method is executed immediately after your promise is fulfilled with resolve. Here's an example: myPromise.then(result => { // do something with the result. }); result comes from the argument given to the resolve method.

How would you import everything from another file?

Suppose you have a file and you wish to import all of its contents into the current file. This can be done with the import * as syntax. Here's an example where the contents of a file named math_functions.js are imported into a file in the same directory: import * as myMathModule from "./math_functions.js"; The above import statement will create an object called myMathModule. This is just a variable name, you can name it anything. The object will contain all of the exports from math_functions.js in it, so you can access the functions like you would any other object property. Here's how you can use the add and subtract functions that were imported: myMathModule.add(2,3); myMathModule.subtract(5,3);

What can you omit from an ES6 function when you are only passing in one param?

The parenthesis around the param const increment = number => number + 1;

What can you use to freeze an objects mutability?

To ensure your data doesn't change, JavaScript provides a function Object.freeze to prevent data mutation. Once the object is frozen, you can no longer add, update, or delete properties from it. Any attempt at changing the object will be rejected without an error. Object.freeze(objectYouWantFrozen)

How do you import a default export?

To import a default export, you need to use a different import syntax. In the following example, add is the default export of the math_functions.js file. Here is how to import it: import add from "./math_functions.js"; The syntax differs in one key place. The imported value, add, is not surrounded by curly braces ({}). add here is simply a variable name for whatever the default export of the math_functions.js file is. You can use any name here when importing a default.

What is an implicit return?

When there is no function body, and only a return value, arrow function syntax allows you to omit the keyword return as well as the brackets surrounding the code. This helps simplify smaller functions into one-line statements: const myFunc = () => "value"; This code will still return value by default.

What is the difference in scope between the var and let keywords?

When you declare a variable with the var keyword, it is declared globally, or locally if declared inside a function. The let keyword behaves similarly, but with some extra features. When you declare a variable with the let keyword inside a block, statement, or expression, its scope is limited to that block, statement, or expression.

How would you destructure nested objects and also assign them new variable names?

You can use the same principles from the previous two lessons to destructure values from nested objects. const user = { johnDoe: { age: 34, email: '[email protected]' } }; Here's how to extract the values of object properties and assign them to variables with the same name: const { johnDoe: { age, email }} = user; And here's how you can assign an object properties' values to variables with different names: const { johnDoe: { age: userAge, email: userEmail }} = user; Another Example: const LOCAL_FORECAST = { yesterday: { low: 61, high: 75 }, today: { low: 64, high: 77 }, tomorrow: { low: 68, high: 80 } }; const {today: {low: lowToday, high: highToday}} = LOCAL_FORECAST; console.log(lowToday); // should be 64 console.log(highToday); // should be 77

How would you use the promise .catch() method?

catch is the method used when your promise has been rejected. It is executed immediately after a promise's reject method is called. Here's the syntax: myPromise.catch(error => { // do something with the error. }); error is the argument passed in to the reject method. Note: the then and catch methods can be chained to the promise declaration if you choose.

What is the class syntax for a constructor function?

class SpaceShuttle { constructor(targetPlanet) { this.targetPlanet = targetPlanet; } } const zeus = new SpaceShuttle('Jupiter'); It should be noted that the class keyword declares a new function, to which a constructor is added. This constructor is invoked when new is called to create a new object.

What is the syntax for exporting code blocks?

const add = (x, y) => { return x + y; } export { add }; When you export a variable or function, you can import it in another file and use it without having to rewrite the code. You can export multiple things by repeating the first example for each thing you want to export, or by placing them all in the export statement of the second example, like this: export { add, subtract };

What is a default parameter?

const greeting = (name = "Anonymous") => "Hello " + name; console.log(greeting("John")); // Hello John console.log(greeting()); // Hello Anonymous The default parameter kicks in when the argument is not specified (it is undefined). As you can see in the example above, the parameter name will receive its default value "Anonymous" when you do not provide a value for the parameter. You can add default values for as many parameters as you want.

What is the const keyword?

const has all the features that let has, with the added bonus that variables declared using const are read-only. They are a constant value, which means that once a variable is assigned with const, it cannot be reassigned. Example: "use strict"; const FAV_PET = "Cats"; FAV_PET = "Dogs"; // returns error

What is the syntax for an ES6 arrow function?

const myFunc = function() { const myVar = "value"; return myVar; } ES6 provides us with the syntactic sugar to not have to write anonymous functions this way. Instead, you can use arrow function syntax: const myFunc = () => { const myVar = "value"; return myVar; }

What is the syntax for writing a function within an object?

const person = { name: "Taylor", sayHello() { return `Hello! My name is ${this.name}.`; } };

What is the syntax for an interpolated string?

const person = { name: "Zodiac Hasbro", age: 56 }; // Template literal with multi-line and string interpolation const greeting = `Hello, my name is ${person.name}! I am ${person.age} years old.`; console.log(greeting); // prints // Hello, my name is Zodiac Hasbro! // I am 56 years old.

How would you use destructuring to extract values from an object?

const user = { name: 'John Doe', age: 34 }; const name = user.name; // name = 'John Doe' const age = user.age; // age = 34 Here's an equivalent assignment statement using the ES6 destructuring syntax: const { name, age } = user; // name = 'John Doe', age = 34 Here, the name and age variables will be created and assigned the values of their respective values from the user object. You can see how much cleaner this is. You can extract as many or few values from the object as you want.

How would you import something?

import { add } from './math_functions.js'; Here, import will find add in math_functions.js, import just that function for you to use, and ignore the rest. The ./ tells the import to look for the math_functions.js file in the same folder as the current file. The relative file path (./) and file extension (.js) are required when using import in this way. You can import more than one item from the file by adding them in the import statement like this: import { add, subtract } from './math_functions.js';

What is the purpose of the let variable keyword?

let was introduced in ES6 to solve this potential issue with the var keyword. let camper = 'James'; let camper = 'David'; // throws an error So unlike var, when using let, a variable with the same name can only be declared once.

What is the purpose of the resolve and reject params of a promise?

resolve is used when you want your promise to succeed, and reject is used when you want it to fail. These are methods that take an argument, as seen below. const myPromise = new Promise((resolve, reject) => { if(condition here) { resolve("Promise was fulfilled"); } else { reject("Promise was rejected"); } }); The example above uses strings for the argument of these functions, but it can really be anything. Often, it might be an object, that you would use data from, to put on your website or elsewhere.


Related study sets

Human Development: A Life-span View 7th Sample Test for Ch. 5

View Set

APHG - Where is Agriculture Distributed?

View Set

African American History Study Guide

View Set

Found questions/self assess right answers

View Set

Management Final Exam: Quiz Questions

View Set

Module 13 Professional Models of Practice, delegation, and evaluating quality of care

View Set

Maternal Child EAQ Exam Medications

View Set

Chapter 9 - Section Review Quizzes

View Set