#atom
Functions in JavaScript are first-class objects, meaning they can be assigned to variables, passed as arguments, and returned from other functions. They are used to encapsulate reusable code and perform specific tasks.
Ways to Define Functions:
-
Function Declaration:
function greet() { console.log('Hello!'); } -
Function Expression:
const greet = function() { console.log('Hello!'); }; -
Arrow Function (ES6):
const greet = () => { console.log('Hello!'); }; -
Constructor Function:
const greet = new Function('console.log("Hello!")');
Methods and Properties of Functions:
-
nameProperty: Returns the name of the function.function greet() {} console.log(greet.name); // "greet" -
lengthProperty: Returns the number of parameters the function expects.function add(a, b) {} console.log(add.length); // 2 -
call()Method: Calls a function with a specificthisvalue and arguments provided individually.function greet(message) { console.log(`${message}, ${this.name}`); } const person = { name: 'Alice' }; greet.call(person, 'Hello'); // "Hello, Alice" -
apply()Method: Similar tocall(), but arguments are provided as an array.greet.apply(person, ['Hello']); // "Hello, Alice" -
bind()Method: Creates a new function with a specificthisvalue and optional arguments.const greetAlice = greet.bind(person, 'Hello'); greetAlice(); // "Hello, Alice" -
toString()Method: Returns the function's source code as a string.console.log(greet.toString()); // "function greet() { console.log('Hello!'); }"
The this Keyword in Functions:
- The
thiskeyword refers to the context in which a function is executed. Its value depends on how the function is called:- In a method,
thisrefers to the object that owns the method. - In a function,
thisrefers to the global object (windowin browsers,globalin Node.js) orundefinedin strict mode. - In an arrow function,
thisis lexically scoped and retains the value ofthisfrom the enclosing context.
- In a method,
Example:
const person = {
name: 'Alice',
greet: function() {
console.log(`Hello, ${this.name}`);
}
};
person.greet(); // "Hello, Alice"
Connections:
Connections:
Sources: