freeCodeCamp/curriculum/challenges/english/02-javascript-algorithms-and-data-structures/es6/write-concise-declarative-functions-with-es6.english.md
Tom 17a55c6e18
fix(curriculum): Consolidated comments for JavaScript Algorithms and Data Structures challenges - part 1 of 4 (#38258)
* fix: consolidate/remove comments

* fix: remove => from comment

* fix: reverted changes to add same changes to another PR

* fix: removed 'the' from sentence

Co-Authored-By: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>

* fix: removed 'the' from the sentence

Co-Authored-By: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>

Co-authored-by: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>
2020-03-04 13:08:54 -06:00

2.0 KiB

id, title, challengeType, forumTopicId
id title challengeType forumTopicId
587d7b8b367417b2b2512b50 Write Concise Declarative Functions with ES6 1 301224

Description

When defining functions within objects in ES5, we have to use the keyword function as follows:
const person = {
  name: "Taylor",
  sayHello: function() {
    return `Hello! My name is ${this.name}.`;
  }
};

With ES6, You can remove the function keyword and colon altogether when defining functions in objects. Here's an example of this syntax:

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

Instructions

Refactor the function setGear inside the object bicycle to use the shorthand syntax described above.

Tests

tests:
  - text: Traditional function expression should not be used.
    testString: getUserInput => assert(!removeJSComments(code).match(/function/));
  - text: <code>setGear</code> should be a declarative function.
    testString: assert(typeof bicycle.setGear === 'function' && code.match(/setGear\s*\(.+\)\s*\{/));
  - text: <code>bicycle.setGear(48)</code> should change the <code>gear</code> value to 48.
    testString: assert((new bicycle.setGear(48)).gear === 48);

Challenge Seed

// Only change code below this line
const bicycle = {
  gear: 2,
  setGear: function(newGear) {
    this.gear = newGear;
  }
};
// Only change code above this line
bicycle.setGear(3);
console.log(bicycle.gear);

After Test

const removeJSComments = str => str.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, '');

Solution

const bicycle = {
  gear: 2,
  setGear(newGear) {
    this.gear = newGear;
  }
};
bicycle.setGear(3);