DEV Community

Discussion on: JavaScript Function Irquiry

Collapse
canderson93 profile image
Carl Anderson

It'll probably be helpful to step away from code here and think of it in terms of spoken language.

In coding, functions are broadly "actions" -- sections of code that do something. In spoken language, this would be a verb.

If you think about verbs, they work with or without an object.

  • Without an object -- "I laugh."
  • With an object -- "I laugh at jokes."

When it comes to functions being verbs, objects are your parameters. Importantly, they change the way the verb works.

function laugh(target) {
    console.log(`HAHAHAHA`);
    if (target) {
        console.log(`That ${target} is very funny`);
    }
}

However, even within a verb taking an object, there are variations. Sometimes a very has to take an object: "I pick" doesn't make sense unless you have an object, like "the apple". Other times, it can't take an object, like "I die".

function pick(target) {
    if (!target) throw new Error("What are you even talking about?");

    console.log(`Now I have a ${target}`);
}

function die() {
    console.log('Et tu?');
}

To ground this in the example you provided about choosing an icon - you can express it like this: I choose the icon for _____

The obvious candidate for a parameter is the weather type we're looking for, and moving the selection code inside of it.

function chooseIcon(type) {
    // There's only two weather conditions, right?
    if (type === 'cloudy') { return 'cloudy.jpg'; }
    else { return 'sunny.jpg' }
}