Hello everyone, welcome to nkcoderz.com. In this article we will going to discuss about Functions In JavaScript.
Table of Contents
Functions In JavaScript
JavaScript functions are blocks of code that can be executed when they are called. They are an essential part of the language, and they are used to create reusable and modular code.
Functions can be defined using the “function” keyword, followed by the function name, a set of parentheses, and a set of curly braces. The code inside the curly braces is the body of the function, and it is executed when the function is called. Here is an example of a simple function in JavaScript:
Code For Simple Function In JavaScript
function greet() {
console.log("Hello, World!");
}
greet();
Output
Hello, World!
Functions can also accept parameters, which are values that are passed into the function when it is called. These parameters are then used inside the function to perform calculations or other operations. Here is an example of a function that takes two parameters, “a” and “b”, and returns their sum:
function add(a, b) {
return a + b;
}
console.log(add(1, 2));
console.log(add(5, 10));
Output
3
15
JavaScript functions can also have default parameters. Default parameters are used when the values passed to the function are not defined or are undefined. This can be set using the assignment operator (=) while defining the function.
Code For Default Parameters Functions
function add(a = 0, b = 0) {
return a + b;
}
console.log(add());
Output
0
Functions can also be assigned to variables, in this way we can use this variable as a function. This is also known as function expressions.
Code For Function Expressions
let greet = function() {
console.log("Hello, World!");
}
greet();
Output
Hello, World!
JavaScript also allows arrow functions (also known as fat arrow functions) which are a shorthand notation for defining functions. Here is an example of the same add function defined using an arrow function:
Code For Arrow Function
let add = (a, b) => a + b;
console.log(add(1, 2));
Output
3
JavaScript functions can also be used in object-oriented programming. They can be used as methods of objects, and they can be used to create constructors for creating objects.
Conclusion
In conclusion, JavaScript functions are a powerful and versatile feature of the language. They are essential for creating reusable and modular code, and they are used in a wide variety of situations, from simple calculations to more complex object-oriented programming.
If you liked this post, then please share this with your friends and make sure to bookmark this website for more awesome content.