A function is a bit of re-usable code. Just how we like to re-use CSS classes, we love to re-use code. Let’s start with an example:
function addTwo(number) { return number + 2; }
const finalAnswer = addTwo(5); console.log(finalAnswer);
Let’s make a something a bit more useful.
function greet(firstName, lastName, honorific, greeting) { return `${greeting} ${honorific} ${lastName}! I’m extremely pleased you could join us, ${firstName}! I hope you enjoy your stay, ${honorific} ${lastName}.`; }
console.log(greet("Pratyaksh", "Saini", "Lord", "Salutations")); console.log(greet("Jack", "Sparrow", "Captain", "A-hoy"));
Every time you call a function, it has its own scope. Other things can’t peek into it; it just has its own little workspace for it work with. Once its done, any variable that you haven’t explicitly held on to or returned at the end is discarded.
function addFive(number) { const someVariable = "you can't see me outside this function"; return number + 5; }
addFive(10); console.log(someVariable);
Lots of functions already exist for you! Smart people have created this commonly-used functions for things we often need. For example, say you have a string and you want to make everything lowercase, you can do this:
const sentence = "ThIs HaS wEiRd CaSiNg On It";
console.log(sentence.toLowerCase());
console.log(Math.round(5.1));
const name = "Pratyaksh Saini"; console.log(name.substr(10, 5));