#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:
-
name
Property: Returns the name of the function.function greet() {} console.log(greet.name); // "greet"
-
length
Property: Returns the number of parameters the function expects.function add(a, b) {} console.log(add.length); // 2
-
call()
Method: Calls a function with a specificthis
value 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 specificthis
value 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
this
keyword refers to the context in which a function is executed. Its value depends on how the function is called:- In a method,
this
refers to the object that owns the method. - In a function,
this
refers to the global object (window
in browsers,global
in Node.js) orundefined
in strict mode. - In an arrow function,
this
is lexically scoped and retains the value ofthis
from 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: