JavaScript Functions: The Ultimate Guide For Web Developers To Enhance Code Efficiency

JavaScript Functions: The Ultimate Guide For Web Developers To Enhance Code Efficiency

Welcome to my other blog about this JavaScript Blog Course. You can find it here↗️

In this blog, we are going to learn JavaScript Switch Statements.

What to wait?

lets-get-started-ignace-aleya.gif (200×200)

It is pretty often that sometimes, we need to perform a similar task in many places of the script.

For Example:

We greet Welcome to users log in or Signing In

Functions allow the code to be called many times without repetition.

Some already built-in functions are:
alert(message), prompt(message, default) and confirm(question)

Function Declaration

We need to declare function

function showMessage() {
  alert( 'Welcome Everyone!' );
}

Also,

function name(parameter1, parameter2, ... parameterN) {
 // body
}

The compiler reads function first, getting it a function, then functionName ( name of the function), then parameters of the function, then the statements of the function.

Our new function can be called by its name: showMessage().

For instance:

function showMessage() {
  alert( 'Hello everyone!' );
}

showMessage();
showMessage();

The function's code is run by the call showMessage(). Here, the message will appear twice.

This illustration well illustrates one of the primary goals of functions, which is to prevent code duplication.

The function that outputs the message can be changed in one location in the code if the message or the manner it is shown ever needs to be changed.

Local variables

The variable which is declared inside a function or block is called a local variable.
Example:

function showMessage() {
  let message = "Hello"; // local variable

  alert( message );
}

showMessage(); // Hello
alert( message );

Outer Variables

A function can access an outer variable as well, for example:

let userName = 'John';

function showMessage() {
  let message = 'Hello, ' + userName;
  alert(message);
}

showMessage(); // Hello, John

Parameters

Arbitrary data can be passed to a function using parameters.

Example:

function showMessage(a, b) { 
  alert(a + ': ' + b);
}

showMessage('Aryan', 'Hello!');  // Aryan Hello!'
showMessage('Aryan', "What's up?"); // Aryan What's up?

When we call showMessagefunction and give parameters to it, the function uses the value.

Default values

If a function is called, but an argument is not provided, then the corresponding value becomes undefined.

It can also be called with a single argument.

Alternative default parameters

In some cases, following the function declaration, it makes useful to set default values for parameters.

By comparing it to undefined, we can determine whether the parameter was supplied during the execution of the function:

function showMessage(text) {

if (text === undefined) {
  }
  alert(text);
}
showMessage();

Returning a value

A function can return a value back into the calling code as a result.

Example:

function sum(a, b) {
  return a + b;
}

let add = sum(3, 4);
alert( add ); // 7

return can be used in any place of the function, when execution reaches it, it stops working and the value is returned to the calling code.

There may be more than one occurrence return in a single function.

For Example:

function checkAge(age) {
  if (age >= 18) {
    return true;
  } else {
    return confirm('Do you have permission from your parents?');
  }
}

let age = prompt('How old are you?', 18);

if ( checkAge(age) ) {
  alert( 'Access granted' );
} else {
  alert( 'Access denied' );
}

A function with an empty return or without it returns undefined

If a function does not return a value, it is the same as if it returns undefined:

function doNothing() { /* empty */ }

alert( doNothing() === undefined ); // true

An empty return is also the same as return undefined:

function doNothing() {
  return;
}

alert( doNothing() === undefined ); // true

Never add a newline between return and the value

For a long-expression in return, it might be tempting to put it on a separate line, like this:

return
 (some + long + expression + or + whatever * f(a) + f(b))

That doesn’t work, because JavaScript assumes a semicolon after return. That’ll work the same as:

return;
 (some + long + expression + or + whatever * f(a) + f(b))

So, it effectively becomes an empty return.

If we want the returned expression to wrap across multiple lines, we should start it at the same line as return. Or at least put the opening parentheses there as follows:

return (
  some + long + expression
  + or +
  whatever * f(a) + f(b)
  )

And it will work just as we expect it to.

Naming a function

Activities are functions. Their name is typically a verb, then. To give someone viewing the code an idea of what the function performs, it should be succinct, accurate, and convey what the function does.

Example:
A function that is used to swap numbers,
the functionName probable might be swapNumbers or swap , etc.

There might be some prefixes with function, which is used to direct the actual action to be done by the function.
For instance, functions that start with "show" usually show something.

Function starting with…

  • "get…" – return a value,

  • "calc…" – calculate something,

  • "create…" – create something,

  • "check…" – check something and return a boolean, etc.

Functions == Comments

A function should be short and do exactly one thing at a time. It might be worthwhile to divide the function into a few smaller functions if that thing is large.

For instance, compare the two functions showPrimes(n) below. Each one output prime numbers up to n.

The first variant uses a label:

function showPrimes(n) {
  nextPrime: for (let i = 2; i < n; i++) {

    for (let j = 2; j < i; j++) {
      if (i % j == 0) continue nextPrime;
    }

    alert( i ); // a prime
  }
}

The second variant uses an additional function isPrime(n) to test for primality:

function showPrimes(n) {

  for (let i = 2; i < n; i++) {
    if (!isPrime(i)) continue;

    alert(i);  // a prime
  }
}

function isPrime(n) {
  for (let i = 2; i < n; i++) {
    if ( n % i == 0) return false;
  }
  return true;
}

The second variant is easier to understand, isn’t it? Instead of the code piece, we see the name of the action (isPrime). Sometimes people refer to such code as self-describing.

meme on functions

I hope you loved the blog💝

Show support by following me!!

Have a wonderful day my friend🤝
See you soon...

Don't forget to follow me on Twitter & LinkedIn