"ECMAScript is a standardized version of JavaScript with the goal of unifying the language's specifications and features. As all major browsers and JavaScript-runtimes follow this specification, the term <i>ECMAScript</i> is interchangeable with the term <i>JavaScript</i>.<br><br>Most of the challenges on freeCodeCamp use the ECMAScript 5 (ES5) specification of the language, finalized in 2009. But JavaScript is an evolving programming language. As features are added and revisions are made, new versions of the language are released for use by developers.<br><br>The most recent standardized version is called ECMAScript 6 (ES6), released in 2015. This new version of the language adds some powerful features that will be covered in this section of challenges, including:<br><br><ul><li>Arrow functions</li><li>Classes</li><li>Modules</li><li>Promises</li><li>Generators</li><li><code>let</code> and <code>const</code></li></ul><br><br><strong>Note</strong><br>Not all browsers support ES6 features. If you use ES6 in your own projects, you may need to use a program (transpiler) to convert your ES6 code into ES5 until browsers support ES6.",
"One of the biggest problems with declaring variables with the <code>var</code> keyword is that you can overwrite variable declarations without an error.",
"In a small application, you might not run into this type of problem, but when your code becomes larger, you might accidently overwrite a variable that you did not intend to overwrite. Because this behaviour does not throw an error, searching and fixing bugs becomes more difficult.",
"Another problem with the <code>var</code> keyword is that it is hoisted to the top of your code when it compiles. This means that you can use a variable before you declare it.",
"<ol><li>The variable <code>camper</code> is declared as undefined.</li><li>The value of <code>camper</code> is logged.</li><li>David is assigned to <code>camper</code>.</li></ol>",
"This code will run without an error.",
"A new keyword called <code>let</code> was introduced in ES6 to solve the problems with the <code>var</code> keyword. With the <code>let</code> keyword, all the examples we just saw will cause an error to appear. We can no longer overwrite variables or use a variable before we declare it. Some modern browsers require you to add <code>\"use strict\";</code> to the top of your code before you can use the new features of ES6.",
"Let's try using the <code>let</code> keyword.",
"<hr>",
"Fix the code so that it only uses the <code>let</code> keyword and makes the errors go away.",
"<strong>Note</strong><br>Remember to add <code>\"use strict\";</code> to the top of your code."
"When you declare a variable with the <code>var</code> keyword, it is declared globally, or locally if declared inside a function.",
"The <code>let</code> keyword behaves similarly, but with some extra features. When you declare a variable with the <code>let</code> keyword inside a block, statement, or expression, its scope is limited to that block, statement, or expression.",
"<blockquote>var numArray = [];<br>for (var i = 0; i < 3; i++) {<br> numArray.push(i);<br>}<br>console.log(numArray);<br>// returns [0, 1, 2]<br>console.log(i);<br>// returns 3</blockquote>",
"With the <code>var</code> keyword, <code>i</code> is declared globally. So when <code>i++</code> is executed, it updates the global variable. This code is similiar to the following:",
"<blockquote>var numArray = [];<br>var i;<br>for (i = 0; i < 3; i++) {<br> numArray.push(i);<br>}<br>console.log(numArray);<br>// returns [0, 1, 2]<br>console.log(i);<br>// returns 3</blockquote>",
"This behavior will cause problems if you were to create a function and store it for later use inside a for loop that uses the <code>i</code> variable. This is because the stored function will always refer to the value of the updated global <code>i</code> variable.",
"As you can see, <code>printNumTwo()</code> prints 3 and not 2. This is because the value assigned to <code>i</code> was updated and the <code>printNumTwo()</code> returns the global <code>i</code> and not the value <code>i</code> had when the function was created in the for loop. The <code>let</code> keyword does not follow this behavior:",
"<blockquote>'use strict';<br>let printNumTwo;<br>for (let i = 0; i < 3; i++) {<br> if (i === 2) {<br> printNumTwo = function() {<br> return i;<br> };<br> }<br>}<br>console.log(printNumTwo());<br>// returns 2<br>console.log(i);<br>// returns \"i is not defined\"</blockquote>",
"<code>i</code> is not defined because it was not declared in the global scope. It is only declared within the for loop statement. <code>printNumTwo()</code> returned the correct value because three different <code>i</code> variables with unique values (0, 1, and 2) were created by the <code>let</code> keyword within the loop statement.",
"Fix the code so that <code>i</code> declared in the if statement is a separate variable than <code>i</code> declared in the first line of the function. Be certain not to use the <code>var</code> keyword anywhere in your code.",
"<strong>Note</strong><br>Remember to add <code>\"use strict\";</code> to the top of your code.",
"This exercise is designed to illustrate the difference between how <code>var</code> and <code>let</code> keywords assign scope to the declared variable. When programming a function similar to the one used in this exercise, it is often better to use different variable names to avoid confusion."
"// TEMPORARILY COMMENTED OUT: assert(!/var/g.test(code) && /let/g.test(code), 'message: The <code>var</code> keyword should be replaced with <code>let</code>. (This test is temporarily disabled)');",
"assert(code.match(/(i\\s*=\\s*).*\\s*.*\\s*.*\\1('|\")block\\s*scope\\2/g), 'message: The variable <code>i</code> declared in the if statement should equal \"block scope\".');",
"assert(checkScope() === \"function scope\", 'message: <code>checkScope()</code> should return \"function scope\"');"
"<code>let</code> is not the only new way to declare variables. In ES6, you can also declare variables using the <code>const</code> keyword.",
"<code>const</code> has all the awesome features that <code>let</code> has, with the added bonus that variables declared using <code>const</code> are read-only. They are a constant value, which means that once a variable is assigned with <code>const</code>, it cannot be reassigned.",
"As you can see, trying to reassign a variable declared with <code>const</code> will throw an error. You should always name variables you don't want to reassign using the <code>const</code> keyword. This helps when you accidentally attempt to reassign a variable that is meant to stay constant. A common practice is to name your constants in all upper-cases and with an underscore to separate words (e.g. <code>EXAMPLE_VARIABLE</code>).",
"<hr>",
"Change the code so that all variables are declared using <code>let</code> or <code>const</code>. Use <code>let</code> when you want the variable to change, and <code>const</code> when you want the variable to remain constant. Also, rename variables declared with <code>const</code> to conform to common practices.",
"<strong>Note</strong><br>Don't forget to add <code>\"use strict\";</code> to the top of your code."
"The <code>const</code> declaration has many use-cases in modern JavaScript.",
"Some developers prefer to assign all their variables using <code>const</code> by default, unless they know they will need to reassign the value. Only in that case, they use <code>let</code>.",
"However, it is important to understand that objects (including arrays and functions) assigned to a variable using <code>const</code> are still mutable. Using the <code>const</code> declaration only prevents reassignment of the variable identifier.",
"<blockquote>\"use strict\";<br>const s = [5, 6, 7];<br>s = [1, 2, 3]; // throws error, trying to assign a const<br>s[7] = 45; // works just as it would with an array declared with var</blockquote>",
"As you can see, you can mutate the object (<code>[5, 6, 7]</code>) itself and the variable identifier (<code>s</code>) will still point to the altered array. Like all arrays, the array assigned to <code>s</code> is mutable, but because <code>const</code> was used, you cannot use the variable identifier, <code>s</code>, to point to a different array using the assignment operator.",
"To make an object immutable, you can use <code>Object.freeze()</code>.",
"<hr>",
"An array is delcared as <code>const s = [5, 7, 2]</code>. Change the array to <code>[2, 5, 7]</code>.",
"<strong>Note</strong><br>Don't forget to add <code>\"use strict\";</code> to the top of your code."
"In JavaScript, we often don't need to name our functions, especially when passing a function as an argument to another function. Instead, we create inline functions. We don't need to name these functions because we do not reuse them anywhere else.",
"To achieve this, we often use the following syntax:",
"ES6 provides us with the syntactic sugar to not have to write anonymous functions this way. Instead, you can use <strong>arrow function syntax</strong>:",
"When there is no function body, and only a return value, arrow function syntax allows you to omit the keyword <code>return</code> as well as the brackets surrounding the code. This helps simplify smaller functions into one-line statements:",
"This code will still return <code>value</code> by default.",
"<hr>",
"Rewrite the function assigned to the variable <code>magic</code> which returns a new <code>Date()</code> to use arrow function syntax. Also make sure nothing is defined using the keyword <code>var</code>.",
"Just like a normal function, you can pass arguments into arrow functions.",
"<blockquote>// doubles input value and returns it<br>const doubler = (item) => item * 2;</blockquote>",
"You can pass more than one argument into arrow functions as well.",
"<hr>",
"Rewrite the <code>myConcat</code> function which appends contents of <code>arr2</code> to <code>arr1</code> so that the function uses arrow function syntax.",
"It's time we see how powerful arrow functions are when processing data.",
"Arrow functions work really well with higher order functions, such as <code>map()</code>, <code>filter()</code>, and <code>reduce()</code>, that take other functions as arguments for processing collections of data.",
"We have written this with <code>filter()</code> to at least make it somewhat readable. Now compare it to the following code which uses arrow function syntax instead:",
"This code is more succinct and accomplishes the same task with fewer lines of code.",
"<hr>",
"Use arrow function syntax to compute the square of only the positive integers (fractions are not integers) in the array <code>realNumberArray</code> and store the new array in the variable <code>squaredIntegers</code>.",
"The default parameter kicks in when the argument is not specified (it is undefined). As you can see in the example above, the parameter <code>name</code> will receive its default value <code>\"Anonymous\"</code> when you do not provide a value for the parameter. You can add default values for as many parameters as you want.",
"<hr>",
"Modify the function <code>increment</code> by adding default parameters so it will always return a valid number and it will add 1 to <code>number</code> if <code>value</code> is not specified.",
"<strong>Note</strong><br>Don't forget to use strict mode."
"In order to help us create more flexible functions, ES6 introduces the <dfn>rest operator</dfn> for function parameters. With the rest operator, 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.",
"<blockquote>function howMany(...args) {<br> return \"You have passed \" + args.length + \" arguments.\";<br>}<br>console.log(howMany(0, 1, 2)); // You have passed 3 arguments<br>console.log(howMany(\"string\", null, [1, 2, 3], { })); // You have passed 4 arguments.</blockquote>",
"The rest operator eliminates the need to check the <code>args</code> array and allows us to apply <code>map()</code>, <code>filter()</code> and <code>reduce()</code> on the parameters array.",
"<hr>",
"Modify the function <code>sum</code> so that is uses the rest operator and it works in the same way with any number of parameters.",
"<strong>Note</strong><br>Don't forget to use strict mode."
"ES6 introduces the <dfn>spread operator</dfn>, which allows us to expand arrays and other expressions in places where multiple parameters or elements are expected.",
"The ES5 code below uses <code>apply()</code> to compute the maximum value in an array:",
"We had to use <code>Math.max.apply(null, arr)</code> because <code>Math.max(arr)</code> returns <code>NaN</code>. <code>Math.max()</code> expects comma-separated arguments, but not an array.",
"The spread operator makes this syntax much better to read and maintain.",
"We earlier saw how spread operator can effectively spread, or unpack, the contents of the array.",
"We can do something similar with objects as well. <dfn>Destructuring assignment</dfn> is special syntax for neatly assigning values taken directly from an object to variables.",
"Consider the following ES5 code:",
"<blockquote>const voxel = {x: 3.6, y: 7.4, z: 6.54 };<br>const x = voxel.x; // x = 3.6<br>const y = voxel.y; // y = 7.4<br>const z = voxel.z; // z = 6.54</blockquote>",
"Here's the same assignment statement with ES6 destructuring syntax:",
"<blockquote>const { x, y, z } = voxel; // x = 3.6, y = 7.4, z = 6.54</blockquote>",
"If instead you want to store the values of <code>voxel.x</code> into <code>a</code>, <code>voxel.y</code> into <code>b</code>, and <code>voxel.z</code> into <code>c</code>, you have that freedom as well.",
"<blockquote>const { x : a, y : b, z : c } = voxel // a = 3.6, y = 7.4, z = 6.54</blockquote>",
"You may read it as \"get the field <code>x</code> and copy the value into <code>a</code>,\" and so on.",
"<hr>",
"Use destructuring to obtain the length of the string <code>greeting</code>"
"ES6 makes destructuring arrays as easy as destructuring objects.",
"One key difference between the spread operator and array destructuring is that the spread operator unpacks all contents of an array into a comma-separated list. Consequently, you cannot pick and choose which elements or you want to assign to variables.",
"Use destructuring assignment to swap the values of <code>a</code> and <code>b</code> so that <code>a</code> receives the value stored in <code>b</code>, and <code>b</code> receives the value stored in <code>a</code>."
"The variable a assumes first value, and b takes the second value from the array.",
"You can also destructure in a way, that you can pick up values from any other array index position. You simply have to use commas (,).",
"Instructions.",
"Use destructuring to swap the variables a, b. Swapping is an operation, after which, a gets the value stored in b, and b receives the value stored in a"
"assert(a === 6, 'message: Value of <code>a</code> should be 6, after swapping.');",
"assert(b === 8, 'message: Value of <code>b</code> should be 8, after swapping.');",
"// assert(/\\[\\s*(\\w)\\s*,\\s*(\\w)\\s*\\]\\s*=\\s*\\[\\s*\\2\\s*,\\s*\\1\\s*\\]/g.test(code), 'message: Use array destructuring to swap a and b.');"
"Variables <code>a</code> and <code>b</code> take the first and second values from the array. After that, because of rest operator's presence, <code>arr</code> gets rest of the values in the form of an array.",
"The rest element only works correctly as the last variable in the list. As in, you cannot use the rest operator to catch a subarray that leaves out last element of the original array.",
"<hr>",
"Use destructuring assignment with the rest operator to perform an effective <code>Array.prototype.slice()</code> so that <code>arr</code> is a sub-array of the original array <code>source</code> with the first two elements ommitted."
"In some cases, you can destructure the object in a function argument itself.",
"Consider the code below:",
"<blockquote>const profileUpdate = (profileData) => {<br> const { name, age, nationality, location } = profileData;<br> // do something with these variables<br>}</blockquote>",
"This effectively destructures the object sent into the function. This can also be done in-place:",
"<blockquote>const profileUpdate = ({ name, age, nationality, location }) => {<br> /* do something with these fields */<br>}</blockquote>",
"This removes some extra lines and makes our code look neat.",
"This has the added benefit of not having to manipulate an entire object in a function; only the fields that are needed are copied inside the function.",
"<hr>",
"Use destructuring assignment within the argument to the function <code>half</code> to send only <code>max</code> and <code>min</code> inside the function."
"A new feature of ES6 or ES2015, is that it allows you to use string interpolation with back-ticks.",
"Consider the code below",
"<code>const text = 'Hello World';</code>",
"<code>// string interpolation</code>",
"<code>const divText = `</code>",
"<code><div></code>",
"<code> ${text}</code>",
"<code></div></code>",
"<code>console.log(divText); // prints </code>",
"<code>//<div></code>",
"<code>// Hello World</code>",
"<code>//</div></code>",
"A lot of thing happened in there.",
"First, the ${variable} syntax. It's a template literal. Basically, you won't have to use concatenation with + anymore. Just drop the variable in your string, wrapped with ${ and }.",
"Second, we used backticks, not quotes, to wrap around the string. Notice that the string is multi-line.",
"In ES6, back-ticks give you more robust string creation ability.",
"Instructions",
"Use proper template literal syntax with backticks.",
"The expected output is each entry of result object's failure array, wrapped inside an <li> element, with class attribute text-warning.",
"If you have trouble finding backticks, it's the ` key, to the left of your 1; and has ~ on it."
"It's a simple function that returns an object, which has two fields.",
"ES6 provides a syntactic sugar to remove the redundancy from having to write x: x. You can simply write x once, and it would convert that to x : x (or some equivalent of it) under the hood.",
"ES6 provides a new syntax to help create objects, using the keyword class.",
"This is to be noted, that the class syntax is just a syntax, and not a full-fledged class based implementation of object oriented paradigm, unlike in languages like Java, or Python, or Ruby etc.",
"In ES5, we usually define a constructor function, and use the new keyword to instantiate an object.",
"<code> var spaceShuttle = function(targetPlanet){</code>",
"<code>const zeus = new spaceShuttle('Jupiter');</code>",
"Notice that the class keyword declares a new function, and a constructor was added, which would be invoked when new is called - to create a new object.",
"Instructions",
"Use class keyword and write a proper constructor to create the vegetable class.",
"The Vegetable lets you create a vegetable object, with a property name, to be passed to constructor."
],
"challengeSeed":[
"/* Alter code below this line */",
"const Vegetable = undefined;",
"/* Alter code above this line */",
"const carrot = new Vegetable('carrot')",
"console.log(carrot.name); // => should be 'carrot'"
],
"tests":[
"// Test the Vegetable is a class",
"// Test that class keyword was used",
"// Test that other objects could be created with the class"
"You can obtain values from an object, and set a value of a property within an object.",
"These are classically called getters and setters.",
"Getter functions are meant to simply return (get) the value of an object's private variable to the user without the user directly accessing the private variable.",
"Setter functions are meant to modify (set) the value of an object's private variable based on the value passed into the setter function. This change could involve calculations, or even overwriting the previous value completely.",
"<code>class Book {</code>",
"<code> constructor(author) {</code>",
"<code> this._author = author;</code>",
"<code> }</code>",
"<code> // getter</code>",
"<code> get writer(){</code>",
"<code> return this._author;</code>",
"<code> }</code>",
"<code> // setter</code>",
"<code> set writer(updatedAuthor){</code>",
"<code> this._author = updatedAuthor;</code>",
"<code> }</code>",
"<code>}</code>",
"<code>const lol = new Book('anonymous');</code>",
"<code>console.log(lol.writer);</code>",
"<code>lol.writer = 'wut';</code>",
"<code>console.log(lol.writer);</code>",
"Notice the syntax we are using to invoke the getter and setter - as if they are not even functions.",
"Getters and setters are important, because they hide internal implementation details.",
"Instructions",
"Use class keyword to create a Thermostat class. The constructor accepts Farenheit temperature.",
"Now create getter and setter in the class, to obtain the temperature in Celsius scale.",
"Remember that <code>F = C * 9.0 / 5 + 32</code>, where F is the value of temperature in Fahrenheit scale, and C is the value of the same temperature in Celsius scale",
"Note",
"When you implement this, you would be tracking the temperature inside the class in one scale - either Fahrenheit or Celsius.",
"This is the power of getter or setter - you are creating an API for another user, who would get the correct result, no matter which one you track.",
"In other words, you are abstracting implementation details from the consumer."
],
"challengeSeed":[
"/* Alter code below this line */",
"const Thermostat = undefined;",
"/* Alter code above this line */",
"const thermos = new Thermostat(76); // setting in Farenheit scale",
"let temp = thermos.temperature; // 24.44 in C",
"thermos.temperature = 26;",
"temp = thermos.temperature; // 26 in C"
],
"tests":[
"// Test the Thermostat is a class",
"// Test that class keyword was used",
"// Test that other objects could be created with the class"
"title":"Import vs. Require: What's the difference?",
"description":[
"In the past, the function require() would be used to import the functions and code in external files and modules. While handy, this presents a problem: some files and modules are rather large, and you may only need certain code from those external resources.",
"ES6 gives us a very handy tool known as import. With it, we can choose which parts of a module or file to load into a given file, saving time and memory.",
"Consider the following example. Imagine that math_array_functions has about 20 functions, but I only need one, countItems, in my current file. The old require() approach would force me to bring in all 20 functions. With this new import syntax, I can bring in just the desired function, like so:",
"<code>import { countItems } from \"math_array_functions\"</code>",
"A description of the above code:",
"<code>import { function } from \"file_path_goes_here\"</code>",
"//We can also import variables the same way! ",
"There are a few ways to write an import statement, but the above is a very common use-case. Note: the whitespace surrounding the function inside the curly braces is a best practice-it makes it easier to read the import statement.",
"Note: The lessons in this section handle non-browser features. Import, and the statements we introduce in the rest of these lessons, won't work on a browser directly, However, we can use various tools to create code out of this to make it work in browser.",
"Instructions",
"Add the appropriate import statement that will allow the current file to use the capitalizeString function. The file where this function lives is called \"string_functions,\" and it is in the same directory as the current file."
"In the previous challenge, you learned about import and how it can be leveraged to import small amounts of code from large files. In order for this to work, though, we must utilize one of the statements that goes with import, known as export. When we want some code-a function, or a variable-to be usable in another file, we must export it in order to import it into another file. Like import, export is a non-browser feature.",
"The following is what we refer to as a named export. With this, we can import any code we export into another file with the import syntax you learned in the last lesson. Here's an example:",
"Below are two variables that I want to make available for other files to use. Utilizing the first way I demonstrated export, export the two variables."
"You may use any name following the import * as portion of the statement. In order to utilize this method, it requires an object that receives the imported values. From here, you will use the dot notation to call your imported values.",
"Instructions",
"The code below requires the contents of a file, \"capitalize_strings\", found in the same directory as it, imported. Add the appropriate import * statement to the top of the file, using the object provided."
"In the export lesson, you learned about the syntax referred to as a named export. This allowed you to make multiple functions and variables available for use in other files.",
"There is another export syntax you need to know, known as export default. Usually you will use this syntax if only one value is being exported from a file. It is also used to create a fallback value for a file or module.",
"There is a one major feature of export default you must never forget-since it 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.",
"Instructions",
"The following function should be the fallback value for the module. Please add the necessary code to do so."
"In the last challenge, you learned about export default and its uses. It is important to note that, to import a default export, you need to use a different import syntax.",
"In the following example, we have a function, add, that is the default export of a file, \"math_functions\". Here is how to import it:",
"<code>import add from \"math_functions\";</code>",
"<code>add(5,4); //Will return 9</code>",
"The syntax differs in one key place-the imported value, add, is not surrounded by curly braces, {}. Unlike exported values, the primary method if importing a default export is to simply write the value's name after import.",
"Instructions",
"In the following code, please import the default export, subtract, from the file \"math_functions\", found in the same directory as this file."