DEV Community

Cover image for JavaScript Functions(Part 3): Your Magic Spells
Chandan Singh
Chandan Singh

Posted on

JavaScript Functions(Part 3): Your Magic Spells

In our last magical seminar, we delved deep into the intricate world of JavaScript functions, learning the spells and chants that shape our world. The spell book was opened, and secrets were revealed. But like every great wizard knows, the depth of magic is vast, and our journey has just begun.

Today, we venture further into this enchanted forest of functions, unearthing more potent spells and understanding the legacy of ancient code mages.

๐Ÿช„ Closures: The Enchanted Lockets

In the magical world of JavaScript, a closure is like an enchanted locket, preserving memories (variables) from disappearing even after the spell (function) has been cast.

Imagine casting a spell to create a magical barrier. This barrier remembers the strength at which you cast it and can adjust itself accordingly in the future.


function magicalBarrier(strength) {
    let barrierStrength = strength;
    return function() {
        barrierStrength++;
        console.log("Barrier's current strength: " + barrierStrength);
    }
}
let enhanceBarrier = magicalBarrier(5);
enhanceBarrier();  // Outputs: "Barrier's current strength: 6"

Enter fullscreen mode Exit fullscreen mode

The inner function, even when invoked outside its containing function, still has access to barrierStrength.

๐ŸŒŒ Higher-Order Functions: Conjuring Magic with Magic

In our realm, some spells can manipulate other spells to create new enchantments. These are known as higher-order functions.

For instance, let's take the ancient spell map, which can transform every item in an array.


const numbers = [1, 2, 3, 4];
const doubledNumbers = numbers.map(function(number) {
    return number * 2;
});
console.log(doubledNumbers);  // Outputs: [2, 4, 6, 8]

Enter fullscreen mode Exit fullscreen mode

The map spell takes another spell (function) and applies it to each item, giving us a new potion (array).

๐Ÿง™โ€โ™‚๏ธ Recursive Functions: The Magic that Calls Upon Itself

Some spells are so mighty that they call upon themselves for added power. These are our recursive functions.

Imagine a mirror that reflects another mirror, which then reflects another, creating an infinite loop of reflections.


function magicalMirror(reflections) {
    if(reflections === 0) return;
    console.log("Another reflection appears!");
    return magicalMirror(reflections - 1);
}
magicalMirror(3);  // Outputs the message three times

Enter fullscreen mode Exit fullscreen mode

Use recursive spells with caution, young mage. For if not controlled, they can spiral out of hand!

๐ŸŒ  Conclusion: The Ever-Expanding Grimoire

The world of JavaScript functions is as expansive as the universe of magic itself. With every page turned in our spell book, we uncover more wonders, more nuances, and greater power.

As we close this chapter of our grimoire, remember: The true magic isn't just in knowing the spells, but in understanding their essence and wielding them with wisdom.

Till our next magical meet, practice these spells, and always remember the first rule of magic - respect the craft!

Sorcererโ€™s Assignments: Test Your Magic

๐Ÿ”ฎ 1. The Enchanted Forest of Closures:

Objective: Venture deep into the world of closures and craft a spell that creates magical creatures. Each creature remembers the number of times it has been summoned.


// Your task: Define the spell createCreature
// Hint: Use closures to make the creature remember its summon count.

let summonDragon = createCreature('Dragon');
summonDragon();  // Should say: "A Dragon has been summoned! Total times summoned: 1"
summonDragon();  // Should say: "A Dragon has been summoned! Total times summoned: 2"

Enter fullscreen mode Exit fullscreen mode

๐ŸŒŒ 2. Mystic Transformations with Higher-Order Spells:

Objective: Use the ancient spell filter to find all the magical artifacts that are older than a thousand years from an array.


const artifacts = [
    { name: 'Enchanted Staff', age: 500 },
    { name: 'Mystic Crystal Ball', age: 1500 },
    { name: 'Ageless Tome', age: 3000 },
    { name: 'Newbie Wand', age: 50 }
];

// Your task: Use the 'filter' spell to find artifacts older than a thousand years.

Enter fullscreen mode Exit fullscreen mode

๐Ÿง™โ€โ™‚๏ธ 3. Mirrors of Recursion:

Objective: Craft a recursive spell that counts down from a number and at the end shouts "Blast off!"

javascriptCopy code
// Your task: Define the spell countdown
// Hint: Don't forget to include the base case to stop the recursion.

countdown(5);
// Should say:
// "5..."
// "4..."
// "3..."
// "2..."
// "1..."
// "Blast off!"

Enter fullscreen mode Exit fullscreen mode

Remember, young mage: Crafting spells is not just about getting them right, but understanding the essence and rhythm within them. Once you've attempted these tasks, share your incantations in the comments. Let's see who's ready for the next level in the world of magic!

Top comments (0)