0

Im new to js and its sometimes hard for me to get used to its code conventions. So i have a question, how i should declare function expression? Look at my code, is it right how i did it, or there are better practices?

function onAddButtonClick() { var engWord = document.getElementById('engWord'), japWord = document.getElementById('japWord'), engVal = engWord.value, japVal = japWord.value, engExpr = (engVal !== ""), japExpr = (japVal !== ""), duplicateNum, checkImg, numOfWords; duplicateNum = (function () { var i, pair; for (i = 0; i < dictionary.length; i++) { pair = dictionary[i]; if (pair.eng === engVal && pair.jap === japVal) { return 3; } else if (pair.jap === japVal) { return 2; } else if (pair.eng === engVal) { return 1; } } return 0; }()); //remove focus from inputs engWord.blur(); japWord.blur(); ... } 

Thanks in advance.

1 Answer 1

1

You did fine. Using the opening ( is not syntactically required in this context, but it makes a great warning to the human reader of the code about what is going on. The convention helps.

At the end, the invoking parens () can go inside, or outside, the closing ). Doug Crawford recommends inside and many linters check for this. Despite his claims of dog balls1, it really doesn't matter.

By the way, the idea of function expression being declared and then immediately running is called an IFFE -- Immediately Invoked Function Expression

Sign up to request clarification or add additional context in comments.

2 Comments

Thx for your answer. What about mixing variable declarations and initialization, but putting 'function expression' initialization apart, like in my case?
Comes down to specific cases for me. I use a lot of IFFEs, but I'm also known to move all of my functions and give them specific names at times. Named functions have the advantage that the name can be the documentation for what the function does.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.