freeCodeCamp/curriculum/challenges/english/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-immediately-invoked-function-expression-iife.english.md
Joshua Pelealu a050de56bb
Fix: Running Test with a comment fails test on Understand The immediately invoked function expression iife (#39347)
* Update Regex to test if it's an IIFE instead of checking for a parenthases at the end.

* Second Test will now pass the test

* Escape One Parenthese

* Update Regex to be more structured

Co-authored-by: Randell Dawson <5313213+RandellDawson@users.noreply.github.com>

* Missing regex ending literal

Co-authored-by: Randell Dawson <5313213+RandellDawson@users.noreply.github.com>
2020-09-01 18:48:32 -05:00

1.8 KiB

id, title, challengeType, isHidden, forumTopicId
id title challengeType isHidden forumTopicId
587d7db2367417b2b2512b8b Understand the Immediately Invoked Function Expression (IIFE) 1 false 301328

Description

A common pattern in JavaScript is to execute a function as soon as it is declared:
(function () {
  console.log("Chirp, chirp!");
})(); // this is an anonymous function expression that executes right away
// Outputs "Chirp, chirp!" immediately

Note that the function has no name and is not stored in a variable. The two parentheses () at the end of the function expression cause it to be immediately executed or invoked. This pattern is known as an immediately invoked function expression or IIFE.

Instructions

Rewrite the function makeNest and remove its call so instead it's an anonymous immediately invoked function expression (IIFE).

Tests

tests:
  - text: The function should be anonymous.
    testString: assert(/\((function|\(\))(=>|\(\)){?/.test(code.replace(/\s/g, "")));
  - text: Your function should have parentheses at the end of the expression to call it immediately.
    testString: assert(/\(.*(\)\(|\}\(\))\)/.test(code.replace(/[\s;]/g, "")));

Challenge Seed

function makeNest() {
  console.log("A cozy nest is ready");
}

makeNest();

Solution

(function () {
  console.log("A cozy nest is ready");
})();
(function () {
  console.log("A cozy nest is ready");
}());
(() => {
  console.log("A cozy nest is ready");
})();
(() =>
  console.log("A cozy nest is ready")
)();