Javascript
Functions play a crucial role in organizing and executing code. Let’s start by understanding the basic syntax of a JavaScript function.
A function in JavaScript begins with the function
keyword, followed by the function name and parameters enclosed in parentheses. The code to be executed is enclosed in curly braces.
function functionName(parameter1, parameter2, ...) {
// code to be executed
return result; // optional
}
Let’s dive into a simple example to illustrate how functions work in JavaScript:
function greet(name) {
return `Hello, ${name}!`;
}
const greeting = greet("John");
console.log(greeting);
In this example, the greet
function takes a name
parameter and returns a greeting message. The function is then called with the argument “John,” and the result is printed to the console.
Functions can accept parameters, which act as placeholders for values to be passed when the function is called. These parameters make functions versatile and adaptable to different scenarios.
function addNumbers(a, b) {
return a + b;
}
const sum = addNumbers(5, 7);
console.log(sum); // Output: 12
Here, the addNumbers
function takes two parameters, a
and b
, and returns their sum when called with arguments 5 and 7.
Functions in JavaScript can return values using the return
statement. This allows a function to produce a result that can be used elsewhere in your code.
function multiply(a, b) {
const result = a * b;
return result;
}
const product = multiply(3, 4);
console.log(product); // Output: 12
In this example, the multiply
function returns the product of its two parameters.
Every function in JavaScript is actually an object. This means functions can have properties and methods, just like any other object.
function displayMessage(message) {
console.log(message);
}
console.log(displayMessage.name); // Output: displayMessage
Here, we access the name
property of the displayMessage
function, which returns its name.
()
OperatorThe parentheses ()
operator is used to call a function in JavaScript. It’s a fundamental part of invoking a function and passing arguments if required.
function sayHello() {
console.log("Hello!");
}
sayHello(); // Output: Hello!
In this case, the sayHello
function is called using the ()
operator.
Functions also come with built-in methods that can be applied for various purposes. These methods enhance the functionality and usability of functions in JavaScript.
const myFunction = function() {
// function logic
};
console.log(myFunction.toString()); // Output: function() { // function logic }
Here are some methods of Functions
this
value and arguments provided as an array (or an array-like object).this
value set to a specific value (passed as the first parameter), with a given sequence of arguments.this
value and arguments provided individually.