Functions Flashcards
Function declaration
Function declarations define named functions that can be called later in the code.
function greet(name) {
console.log(“Hello, “ + name + “!”);
}
greet(“John”); // Output: Hello, John!
Function expression
Function expressions assign a function to a variable or a constant. The function can be anonymous or have a name.
const greet = function(name) {
console.log(“Hello, “ + name + “!”);
};
greet(“John”); // Output: Hello, John!
Arrow function
Arrow functions provide a concise syntax for writing functions. They are often used as a shorthand for function expressions.
const greet = name => console.log(“Hello, “ + name + “!”);
greet(“John”); // Output: Hello, John!
IIFE (Immediately Invoked Function Expression):
An IIFE is a function that is immediately executed after its declaration. It helps create a private scope and avoids polluting the global namespace.
(function() {
const message = “Hello!”;
console.log(message);
})();
Generator function
Generator functions are special types of functions that can be paused and resumed during execution using the yield keyword.
function* count() {
let i = 0;
while (true) {
yield i++;
}
}
const counter = count();
console.log(counter.next().value); // Output: 0
console.log(counter.next().value); // Output: 1
Factory functions
A factory function is a function that returns an object. It is used to create and initialize objects with specific properties and methods.
function createPerson(name, age) {
return {
name,
age,
greet() {
console.log(“Hello, my name is “ + this.name + “ and I am “ + this.age + “ years old.”);
}
};
}
const person = createPerson(“John”, 30);
person.greet(); // Output: Hello, my name is John and I am 30 years old.
//In the example above, the createPerson factory function creates and returns an object with name, age, and greet properties.
Constructor functions
A constructor function is used to create objects using the new keyword. It defines a blueprint for creating multiple similar objects with shared properties and methods.
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log(“Hello, my name is “ + this.name + “ and I am “ + this.age + “ years old.”);
};
}
const person = new Person(“John”, 30);
person.greet(); // Output: Hello, my name is John and I am 30 years old.
//In the example above, the Person constructor function is used with the new keyword to create a new person object with name, age, and greet properties.
Factory functions and constructor functions are both used to create objects, but they differ in how the objects are created and initialized. Factory functions explicitly return an object, while constructor functions implicitly return this.