7 Techniques for JavaScript Function Declarations

7 Techniques for JavaScript Function Declarations

Function declarations can be difficult to understand or seem quite daunting If you are getting started with JavaScript. While there might be more than one way to declare a function in this language, not all approaches will work the same way. As such, you must learn about the different ways of function declarations in JavaScript so that you know how to use them correctly when needed.

In this article, we’ll cover some frequently asked questions about function declarations in JavaScript. such as “How many ways can you declare a function in JavaScript? Function declarations in Javascript examples. What is the syntax for declaring?”.

Introduction to JavaScript Functions

The function declaration in JavaScript is made up of two parts. First is the function’s type (function name and parameter types) and second is its body. A function declaration format looks like this: function function_name() { body }. The body is the expression that evaluates the value of the function, or in other words, what you want your program to do.

Functions are useful because they encapsulate reusable logic, which makes them easier to maintain and reuse. This can be especially important when writing large programs where multiple components need to interact with each other in some way (e.g., user interfaces). By separating this functionality into functions, you can separate these interactions so that they only affect specific parts of our program rather than all at once.

Fundamentals of JavaScript

JavaScript is a high-level, open-source, dynamic programming language. It is used on the web and within client-side applications such as games, interactive websites and mobile apps, is also increasingly being used by server-side applications such as Node.js (JavaScript on the Server).

Predefined Functions 

These are some predefined or inbuilt or helper methods in javascript, you are most likely to use:

  • Math.random()
  • Math.floor()
  • Math.ceil()
  • Math.round()
console.log(Math.random());
console.log(Math.round(253.369));
console.log(Math.floor(253.369));
console.log(Math.ceil(253.369));
Code language: JavaScript (javascript)

Output

0.29313149879913536
253
253
254Code language: JavaScript (javascript)

Types of Functions

The function declaration is the most basic form of a JavaScript function. It is used to declare that a function will be created and its parameters will be passed in when it’s called.

The following example illustrates this:

//function declaration
function myFunc(a, b) { return a + b; };
console.log(myFunc(2, 3));
Code language: JavaScript (javascript)

Output

5Code language: JavaScript (javascript)

Regular Function

A regular function declaration is a statement that declares the name of the function and its parameters. You can also use it to create anonymous functions or recursion, which are useful when you want to pass variables into your code.

A regular function expression is simply a lambda expression with no body (i.e., no curly braces). You can also use it for creating anonymous functions that take one or more arguments as well as other things like closures and lambdas.

//recursion
function fact(x){
    if(x==0){
    return 1;
    }
    return x * fact(x-1);
}
console.log(fact(6));
console.log(fact(5));
Code language: JavaScript (javascript)

Output

720
120Code language: JavaScript (javascript)

A recursive call is being made inside fact() using the variable that holds the function: x*fact(x-1).

Function Declaration

If you define a function before it is used, then it is known as a function declaration. When you need to define functions in a single line, or need to describe and then call the function, then it can be useful to use a function declaration.

The following example shows how you could declare a new variable and assign it an empty function:

> function functionName(parameters){
// body of the function
};
// no need to use (const,=) as in function expression.
Code language: JavaScript (javascript)
// example
function tempFunction(a,b){return a*b};
function tempfunc(x,y){let z = x*x; return z+y};

console.log(tempFunction(2,3));
console.log(tempfunc(2,3));
Code language: JavaScript (javascript)

Output

6
7Code language: JavaScript (javascript)

function myFunction(a,b){....} is the function declaration that defines the myFunction which returns the product of given numbers.

The hoisting mechanism is another feature that makes it different from function expression. Hoisting enables to use of a function before its declaration.

// Example of hoisting mechanism
console.log(namaste("India"));

// Now name the function
console.log(namaste.name);
console.log(typeof Namaste);

//function declaration at the end
function namaste(name){
    return `Namaste ${name}!`;
}
Code language: JavaScript (javascript)

Output

Namaste India!
namaste
functionCode language: JavaScript (javascript)

Function Expression

In JavaScript, if you define a function within a variable that is called a Function Expression. It cannot be hoisted, but it can be assigned to a variable. Instead, it has its function declaration. Hoisting refers to the process of moving function declarations or variables to the top, before code execution.

The syntax for declaring a new function is:

```// Declare our first function 
const myFunction = function (){ 
    // Function body goes here
    }; ```
Code language: PHP (php)

Shorthand method function

A shorthand way of writing a function expression is the shorthand method function. This function allows a function to be bound to a particular object instance and its return value will be automatically passed back into the parent scope.

A shorthand method function is like a constructor function, except that it is not called using the new keyword. It has this syntax:

const box = {
  collect: [],
  add(x,y,z) {
    this.collect.push(x,y,z);
  },
  getItem(index) {
    return this.collect[index];
  }
};
box.add('apple','orange','guava','banana');
console.log(box.getItem(1));
console.log(box.getItem(3));// undefined in declaration
Code language: JavaScript (javascript)

Output

orange
undefined
Code language: JavaScript (javascript)

Arrow Function 

An arrow function expression is a JavaScript expression that has a shorter syntax compared to a function expression. Arrow functions are anonymous, which means they do not have a name. They also don’t have access to the prototype property of their enclosing scope and thus cannot refer to this outside of their body.

Arrow functions bind their value to their name at the time of declaration. This means you can use it as if it were normal code:

// Prints "hello world!" using arrow notation!
var f = () => {return ( 'hello world!' )}; 
console.log(f());
Code language: JavaScript (javascript)

Output

hello world!Code language: JavaScript (javascript)

Generator Function

A generator function is a special kind of function that returns an array or other iterable object. These functions are often created with the yield keyword, which allows them to be used as iterator functions. They are very similar to the shorthand method function, function expression and function declaration, but only differ with a star(*).

Let’s take a look at an example:

Generate objects using the Shorthand method function

// *functionName()
const object = {
  *add() {
    a = 1;
    while(a<10){
        yield a++;
    }
  }
}
const x = object.add();
console.log(x.next().value);//1
console.log(x.next().value);//2
console.log(x.next().value);//3
Code language: JavaScript (javascript)

Use of Function expression to generate objects

// const functionName = function*(){}
const add = function*() {
    a = 1;
    while(a<10){
        yield a++;
    }
  }

const x = add();
console.log(x.next().value);//1
console.log(x.next().value);//2
console.log(x.next().value);//3
Code language: JavaScript (javascript)

Function declaration – to generate iterable objects

//function* functionName(){}
function* add() {
    a = 1;
    while(a<10){
        yield a++;
    }
  }

const x = add();
console.log(x.next().value);//1
console.log(x.next().value);//2
console.log(x.next().value);//3
Code language: JavaScript (javascript)

In all three methods add function returns the generated objects x. Now you can use x to generate a series of your choice.

Constructor Function 

In JavaScript, the constructor function is used to create objects. It is a special type of function that you can use to construct an object or instance of a class.

A constructor function has access to all the properties and methods of its class, as well as any value in the prototype chain. This allows you to define new methods and properties on your objects by adding them directly to their prototypes (see below).

//create a constructor function
function car(brand,year,model,category){
    this.brandName = brand;
    this.year = year;
    this.model = model;
    this.category = category;
}

// Create 2 car objects
const car1 = new car("Audi", 1992, "100", "Sedan");
const car2 = new car("BMW", 2008, "1 series", "Convertible");

console.log(car1);
console.log(car2);
Code language: JavaScript (javascript)

Output

car { brandName: 'Audi', year: 1992, model: '100', category: 'Sedan' }
car {
  brandName: 'BMW',
  year: 2008,
  model: '1 series',
  category: 'Convertible' }Code language: JavaScript (javascript)

In addition to this, constructor functions have some special features:

  • They have access only to members that are defined in their classes
  • These functions cannot access members from other classes
  • They cannot declare any global variables or functions

Conclusion

As you can see, there are many different ways to define functions in JavaScript. The most common method is the function declaration, but several other options are available.

There is no winner or loser among these techniques when it comes to choosing one method. You can try any one method according to the situation. When it comes to function declaration in javascript, my choice will be the shorthand method function declaration technique.

Tell me in the comment what will be your choice among all options. Do you prefer to use function expression or function declaration?

Frequently ask questions

How many ways can you declare a function in JavaScript?

You can read about it in the article. The number of ways a function can be declared in javascript is function declaration method, function expression method, regular function, arrow function, shorthand method, etc.

Function declaration examples

function product(a,b){return a*b};
console.log(product(2,4));//8Code language: JavaScript (javascript)

What is the syntax for declaring?

The syntax for declaring functions by different methods is already mentioned in the article. please take a look.

for example, function expression syntax is:

const functionName = function(){//body}Code language: JavaScript (javascript)

Sharing is caring

Did you like what Srishti Kumari wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far