Important JavaScript Functions You Need to Know About
Dynamic web applications came into existence after the birth of Web Development]. With the rising popularity of the web applications, JavaScript has become one of the most important languages in today’s world. This JavaScript Function article will explain the different ways to define functions in JavaScript.
Introduction to JavaScript
JavaScript is a high level , interpreted, programming language used to make web pages more interactive. It is a very powerful client-side scripting language which makes your webpage more lively and interactive.
It is a programming language that helps you to implement a complex and beautiful design on web pages. If you want your web page to look alive and do a lot more than just gawk at you, JavaScript is a must.
Fundamentals of JavaScript
If you are new to the language, you need to know some of the fundamentals of JavaScript that will help you start writing your code. The basics include:
JavaScript Function
A JavaScript function is a block of code that is designed to perform any particular task. You can execute a function by calling it. This is known as invoking or calling a function.
To use a function, you have to define it somewhere in the scope from which you wish to call it. The idea is to put some commonly performed task together and make a function so that instead of writing the same code again and again for different inputs, we can call that particular function.
The basic syntax to create a function in JavaScript is as follows:
function functionName(Parameter1, Parameter2, ..)
{
// Function body
}
JavaScript consists of various built-in or predefined functions. But, it also allows us to create user-defined functions. So let’s move ahead and have a look at some of the commonly used predefined functions.
Predefined Functions
JavaScript has several top-level built-in functions. Let’s have a look at some of the functions that are built into the language.
Let’s take an example and see how these predefined functions work in JavaScript:
var x = 10;
var y = 20;
var a = eval("x * y") // Eval
var b = parseInt("10.00") // ParseInt
var c = parseFloat("10") // ParseFloat
escape("Welcome to Edureka") // Escape
unescape("Welcome to Edureka") // Unescape
Different ways to define JavaScript Function
A function can be defined using various ways. It is important to check how the function interacts with the external components and the invocation type. The different ways include:
Function Declaration
A function declaration consists of a function keyword , an obligatory function name, a list of parameters in a pair of parenthesis and a pair of curly braces that delimits the body code.
It is defined as:
// function declaration
function isEven(num) {
return num % 2 === 0;
}
isEven(24); // => true
isEven(11); // => false
Function isEven(num) is a function declaration that is used to determine if a number is even.
Function Expression
A function expression is determined by a function keyword , followed by an optional function name, a list of parameters in a pair of parenthesis and a pair of curly braces that delimits the body code.
It is defined as:
const count = function(array) { // Function expression
return array.length;
}
const methods = {
numbers: [2, 5, 8],
sum: function() { // Function expression
return this.numbers.reduce(function(acc, num) { // func. expression
return acc + num;
});
}
}
count([1, 7, 2]); // => 3
methods.sum(); // => 15
The function expression creates a function object that can be used in various situations like:
- It can be assigned to a variable as an object: count = function(…) {…}
- Create a method on an object sum: function() {…}
- Use the function as a callback: .reduce(function(…) {…})
Shorthand Method Definition
Shorthand method definition is used in a method declaration on object literals and ES6 classes. You can define them using a function name , followed by a list of parameters in a pair of parenthesis and a pair of curly braces that delimits the body statements.
The following example uses shorthand method definition in an object literal:
const collection = {
items: [],
add(...items) {
this.items.push(...items);
},
get(index) {
return this.items[index];
}
};
collection.add('edureka','Online', 'JavaScript');
collection.get(1) // => 'edureka'
The shorthand approach has several benefits over traditional property definition such as:
- It has a shorter syntax which makes it easier to read and write.
- This creates named functions, contrary to a function expression. It is useful for debugging.
Arrow Function
An arrow function is defined using a pair of parenthesis that contains the list of parameters, followed by a fat arrow (=>) and a pair of curly braces that delimits the body statements.
The following example shows the basic usage of arrow function:
const absValue = (number) => {
if (number < 0) { return -number; } return number; } absValue(-21); // => 21
absValue(7); // => 7
Here, absValue is an arrow function that calculates the absolute value of a number.
Generator Function
The generator function in JavaScript returns a Generator object. The syntax is similar to function expression, function declaration or method declaration. But it requires a star character (*).
The generator function can be declared in the following forms:
- Function declaration form function* <name>():
function* indexGenerator(){
var index = 0;
while(true) {
yield index++;
}
}
const g = indexGenerator();
console.log(g.next().value); // => 0
console.log(g.next().value); // => 1
- Function expression form function* ():
const indexGenerator = function* () {
let index = 0;
while(true) {
yield index++;
}
};
const g = indexGenerator();
console.log(g.next().value); // => 0
console.log(g.next().value); // => 1
- Shorthand method definition form *<name>():
const obj = {
*indexGenerator() {
var index = 0;
while(true) {
yield index++;
}
}
}
const g = obj.indexGenerator();
console.log(g.next().value); // => 0
console.log(g.next().value); // => 1
The generator function returns the object g in all three cases. Then it is used to generate a series of incremented numbers.
Function Constructor
When Function is invoked as a constructor, a new function is created. The arguments that are passed to constructor become the parameter names for the new function. Here, the last argument is used as the function body code.
For Example:
function sum1(a, b) {
return a + b;
}
const sum2 = function(a, b) {
return a + b;
}
const sum3 = (a, b) => a + b;
console.log(typeof sum1 === 'function'); // => true
console.log(typeof sum2 === 'function'); // => true
console.log(typeof sum3 === 'function'); // => true
These were some of the different methods to define functions in JavaScript. With this, we have come to the end of our article. I hope you understood what are JavaScript functions and the different methods to define them.
Got a question for us? Please mention it in the comments section of “JavaScript Function” and we will get back to you.