In Javascript, functions and methods are blocks of reusable code that can be defined and called to perform a specific task.
There are two primary ways to declare functions in Javascript: Regular function expressions and Arrow function expressions.
function functionName(parameters) { // Function body // Code to be executed return value; // Optional, used to return a value }
The `multiple` function takes two parameters (num1 and num2) and returns their multiplication.
function multiple(num1, num2) { return num1 * num2; } let result = multiple(5, 8); console.log(result); // Output: 40
Arrow functions provide a more concise syntax and have a shorter function declaration.
They were introduced in ECMAScript 6 (ES6).
let multiple = (num1, num2) => num1 * num2; let result = multiple(5, 8); console.log(result); // Output: 40
Arrow functions are often used for short, one-liner functions. They have some differences compared to regular functions:
// Regular Function function regularFunction() { console.log("Regular Function"); } // Arrow Function let arrowFunction = () => { console.log("Arrow Function"); }; regularFunction(); // Output: "Regular Function" arrowFunction(); // Output: "Arrow Function"
`Arrow functions` do not have their own `this` bindings. They inherit them from the enclosing scope. while `Regular functions` have `this` binding.
`Arrow functions` cannot be used as constructors with the `new` keyword. while `Regular functions` can be used as constructors with the `new` keyword to create new instances of objects.
`Arrow functions` cannot be named (they are anonymous functions). while `Regular functions` have `functionName` followed by the function keyword.
A method is a function that is associated with an object. In Javascript, methods are properties of objects that are function values.
let objName = { variableName: "some string value", methodName(parameters) { // Method body // Code to be executed return value; // Optional, used to return a value } };
let employeeObject = { firstName: "Alice", lastName: "Collin", getFullName() { return this.firstName + " " + this.lastName; } }; console.log(employeeObject.getFullName()); // Output: Alice Collin