JAVASCRIPT

Define Functions in JavaScript

Define Functions in JavaScript

  • A Function could be a block of code that completes an action or returns a value.
  • It is a custom code outlined by programmers which are reusable, and may thus create your programs a lot of standards and economical.
  • We can learn many ways that to define a function, call a function and use function parameters in JavaScript.

Defining a Function

  • Functions are defined, or declared, with the function keyword. Below is that the syntax for a operates in JavaScript.
function nameOfFunction() {
    // Code to be executed
}
  • The declaration begins with the operate keyword, followed by the name of the function. Function names follow constant rules as variables — they’ll contain letters, numbers, underscores and dollar signs, and often written in artiodactyl camel case.
  • The name is followed by a collection of parentheses, which might be used for facultative parameters. The code of the function is contained in curly brackets, similar to a for the statement or if statement.
  • We’ll create a function declaration to print a salutation statement to the console.
// Initialize greeting function
function greet() {
    console.log("Hello, World!");
}
  • Here we’ve got the code to print hi, World! to the console contained within the greet() function. However, nothing can happen and no code can execute till we have a tendency to invoke or call the function. You’ll be able to invoke a function by writing the name of the function followed by the parentheses.
// Invoke the function
greet();
  • Now we are going to place those along, shaping our function and invoking it.
greet.js
// Initialize greeting function
function greet() {
    console.log("Hello, World!");
}

// Invoke the function
greet();
  • With the call for greet();, the function can run and that we can receive the hi, World! because of the program’s output.

Output:

Hello, World!
  • Now we’ve got our greet() code contained in a very function and may recycle it as persistently as we wish.
  • Using parameters, we will create the code a lot of dynamic.

Function Parameters

  • In our greet.js file, we have a tendency to created a basic function that prints hi, World to the console. Victimization parameters, we will add further practicality that may create the code a lot of versatile. Parameters square measure input that gets passed into functions as names and behaves as native variables.
  • When a user logs in an application, we have a tendency to might want the program to greet them by name, rather than simply speech communication, “Hello, World!”.
  • We’ll add a parameter into our function, referred to as name, to represent the name of the person being greeted
// Initialize custom greeting function
function greet(name) {
    console.log(`Hello, ${name}!`);
}
  • The name of the function is to greet, and currently, we’ve got one parameter within the parentheses. The name of the parameter follows constant rules as naming a variable. within the function, rather than a static string consisting of hi, World, we’ve got an example literal string containing our parameter, that is currently behaving as an area variable.
  • You’ll notice we’ve not outlined our name parameter anyplace. we have a tendency to assign it a price after we invoke our function. Presumptuous our user is called Sammy, we’ll decide the operate and place the username because of the argument. The argument is that the actual price that gets passed into the function, during this case it’s the string “Sammy”.
// Invoke greet function with "Sammy" as the argument
greet("Sammy");
  • The value of “Sammy” is being passed into the function through the name parameter. Currently on every occasion name is employed throughout the function, it’ll represent the “Sammy” value. Here is that the whole code.
// Initialize custom greeting function
function greet(name) {
    console.log(`Hello, ${name}!`);
}

// Invoke greet function with "Sammy" as the argument
greet("Sammy");
  • When we have a tendency to run the program higher than, we’ll receive the subsequent output.
READ  JAVASCRIPT - Detecting an undefined object property

Output:

Hello, Sammy!
  • Now we’ve got an example of however a function may be reused. in a very universe example, the function would pull the username from a info rather than directly supply the name as the argument value.
  • In addition to parameters, variables may be declared within functions. These variables square measure referred to as native variables, and can solely exist within the scope of their own function block. Variable scope determines variables’ accessibility; variables that square measure outlined within a function don’t seem to be accessible from outside of the function, however, they’ll be used as persistently as their function is employed throughout a program.

Returning Values

  • More than one parameter may be employed in a function. we will pass multiple values into a function and come back a value. We are going to produce a function to search out the sum of 2 values, portrayed by x and y.
// Initialize add function
function add(x, y) {
    return x + y;
}

// Invoke function to find the sum
add(9, 7);
  • In the program higher than, we have a tendency to outlined a function with the parameters x and y, then passed the values of nine and seven to the function. After we run the program, we’ll receive the sum of these numbers because of the output.

Output:

16
  • In this case, with 9 and 7 passed to the sum() function, the program returns 16
  • When the return keyword is employed, the function ceases to execute and also the value of the expression is return Though during this case the browser can show the worth within the console, it’s not constant as victimization console.log() to print to the console. Invoking the function can output the worth specifically wherever the function was invoked. This value may be used directly or placed into a variable.
READ  Java Programming - Word Wrap Problem

Function Expressions

  • In the last section, we have a tendency to used a function declaration to induce the sum of 2 numbers and returns the value. We will conjointly produce a function expression by distribution a function to a variable.
  • Using our same add function example, we will directly apply the return value to a variable, during this case sum.
// Assign add function to sum constant
const sum = function add(x, y) {
    return x + y;
}

// Invoke function to find the sum
sum(20, 5);

Output:

25
  • Now the sum constant could be a function. We will create this expression a lot of grief by turning it into an anonymous function, that is an unidentified function. Currently, our function has the name add, however with function expressions it’s not necessary to call the function and also the name is typically omitted.
anonymousExpression.js
// Assign function to sum constant
const sum = function(x, y) {
    return x + y;
}

// Invoke function to find the sum
sum(100, 3);

Output

103
  • In this instance, we’ve removed the name of the function, add and it turned as an anonymous function. A named function expression can be the accustomed aid in debugging, however, it’s typically omitted.

Arrow Functions

  • We have learned the way to outline functions victimization the function keyword. However, there’s a more recent, a lot of grief methodology of defining a function referred to as arrow function expressions as of ECMAScript6. Arrow functions, as they’re normally famed, denoted by the equal sign followed by a greater than sign: =>.
  • It is an anonymous function and a type of function expression. We will produce a basic example to find a product of 2 numbers
arrowFunction.js
// Define multiply function
const multiply = (x, y) => {
    return x * y;
}

// Invoke function to find product
multiply(30, 4);

Output

120
  • Instead of writing out the keyword function, we specify to use the => arrow to point a function. Otherwise, it works equally to a daily function expression, with some advanced variations that you’ll be able to examine below Arrow Functions on the Mozilla Developer Network.
  • In the case of just one parameter, the parentheses are excluded. During this example, we’re squaring x, that sorely needs one number to be passed as an argument. The parentheses are omitted.
// Define square function
const square = x => {
    return x * x;
}

// Invoke function to find product
square(8);

Output

64

Note: within the case of no parameters, an empty set of parentheses () is needed within the arrow functions.

  • With these explicit examples that solely include a return statement, arrow functions permit the syntax to be reduced even more. If the function is simply single line return, each the curly braces and also the return statement will be omitted, as seen within the example below.
// Define square function
const square = x => x * x;

// Invoke function to find product
square(10);

Output:

100

All 3 of those styles of syntax end in constant output. It’s usually a matter of preference or company writing standards to choose however you may structure your own functions.

READ  Write a function that returns 2 for input 1 and returns 1 for 2

Conclusion

  • In this tutorial, we have enclosed function declarations and expressions, returning values from functions, assign function values to variables, and ES6 arrow functions.
  • Functions are known as blocks of code that returns a value or complete action, creating programs accessible and standard.

About the author

Venkatesan Prabu

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment