DevNotes

DevNotes

@devnotes ·

JavaScript Part 5: Functions

A function is a named piece of code you can run whenever you need it. You write it once, and when it needs fixing, you fix it in one place.

Writing one and calling it

JavaScript
function greet(name) {  return `Hi ${name}, welcome back!`;}
console.log(greet("Asha"));  // "Hi Asha, welcome back!"console.log(greet("Ravi"));  // "Hi Ravi, welcome back!"
  • name is a parameter: a placeholder for the value you'll pass in.
  • "Asha" is the argument: the actual value for this call.
  • return sends a value back to wherever the function was called.

Writing a function doesn't run it. The code inside only runs when you call the function, with brackets: greet("Asha").

return ends the function

JavaScript
function discount(total) {  if (total < 500) {    return 0;  }  return total * 0.1;}
discount(300);   // 0discount(1000);  // 100

The moment a return runs, the function stops. A function with no return gives back undefined. It's an easy bug to write: you work out the answer, forget to return it, and get undefined.

Default values

JavaScript
function welcome(name = "friend") {  return `Hi ${name}!`;}
welcome();        // "Hi friend!"welcome("Neha");  // "Hi Neha!"

Arrow functions

A shorter way to write a function, and the style you'll see most in modern code and in React:

JavaScript
const square = (n) => n * n;
const add = (a, b) => {  const sum = a + b;  return sum;};

When a single expression follows the arrow, its value is returned automatically, without return or braces. With braces, you write the return yourself, as usual.

Scope: what a function can see

JavaScript
const shop = "Ravi Stores";
function receipt(amount) {  const tax = amount * 0.18;  return `${shop}: ${amount + tax}`;}
console.log(tax); // ReferenceError: tax is not defined

A variable made inside a function exists only inside that function. The function can see variables outside it, like shop, but the outside can't see in. That's a good thing: each function's variables stay out of every other function's way.

Functions as values

In JavaScript, a function is a value like any other. You can store it in a variable, or pass it into another function:

JavaScript
function twice(action) {  action();  action();}
twice(() => console.log("Hello"));  // prints Hello, twice

Passing functions around is everywhere in JavaScript: click handlers, array methods, timers. You'll see it in every part from here on.

Keep them small

A good function does one job, and its name says which: calculateTotal, isValidEmail, formatDate. If you can't think of a name, it's probably doing two jobs. Split it.

Try it

Write isEven(n), which returns true or false, and celsiusToFahrenheit(c), which multiplies by 9, divides by 5 and adds 32. Test both in the console with a few values, including 0 and a negative number.


Next: JavaScript Part 6: Arrays

javascriptwebdevbeginners

Join WIK to like and reply to DevNotes and see more like this.