Javascript Functions and its methods
JavaScript functions are reusable code blocks that let you carry out particular actions, computations, or tasks. They are essential to the organization and structure of JavaScript programs.
We have already seen the Javascript Objects Methods that are essential to know.
1.Declaring a Function
There are various methods for declaring functions. Using the function keyword is the most popular method.
function greet(name) {
return "Hello, " + name + "!";
}
To explain, use the function greet(name). This defines the greet function, which accepts the single parameter name.
return name + “!” + “Hello, “: “Hello, ” is combined with the name parameter in this line to create a greeting message, which is then returned as the function’s output.
2.Calling the Function
console.log(greet("Alice")); // Output: "Hello, Alice!"
In this case, greet(“Alice”) invokes the function with “Alice” as an argument, replacing name and returning the greeting string.
3.Function Methods
JavaScript functions have attributes and methods. Here are some important ones:
3.1.call()
Method
A function can be called with precise arguments and context thanks to the call() method.
function introduce(greeting) {
return greeting + ", I am " + this.name;
}
const person = { name: "Alice" };
console.log(introduce.call(person, "Hello")); // Output: "Hello, I am Alice"
Introduction.call(person, “Hello”): An explanation Introduce may access person.name (“Alice”) by using the call() function to launch introduce with person as this.
3.2.apply()
Method
Although it accepts parameters as an array, the apply() method functions similarly to call().
function introduce(greeting) {
return greeting + ", I am " + this.name;
}
const person = { name: "Bob" };
console.log(introduce.apply(person, ["Hi"])); // Output: "Hi, I am Bob"
introduce.apply(person, ["Hi"])
: apply()
passes "Hi"
as an array argument, achieving the same result as call()
.
3.3.bind()
Method
A new function is created with a specific context using the bind() technique.
function introduce(greeting) {
return greeting + ", I am " + this.name;
}
const person = { name: "Eve" };
const boundIntroduce = introduce.bind(person);
console.log(boundIntroduce("Hey")); // Output: "Hey, I am Eve"
introduce.bind(person): Use this bound to person to create a new function called boundIntroduce.boundIntroduce(“Hey”): This maintains this context by calling the bound function.
3.4.Arrow Functions
Arrow functions (=>
) offer a shorter syntax and do not have their own this
context.
const add = (a, b) => a + b;
console.log(add(2, 3)); // Output: 5
const add = (a, b) => a + b;: This uses arrow syntax to declare a function that implicitly returns a + b.
add (2, 3): uses parameters 2 and 3 to invoke the function.
4.Limitations:
Arrow functions do not have their own this
and cannot be used as constructors.