Welcome to the exciting world of JavaScript (JS) Function Invocation! In this lesson, we'll explore how to create, call, and understand functions ā a fundamental concept in programming that allows us to reuse code and make our lives easier. š
Let's start with the basics.
A function is a block of code designed to perform a specific task. It encapsulates code to increase modularity, readability, and reusability.
In JavaScript, you can define a function using the function keyword followed by the function name, parentheses (), and curly braces {}.
function greet(name) {
console.log("Hello, " + name + "!");
}In this example, we've created a function called greet that takes one argument, name. When called, it will display a personalized greeting.
To call a function, we need to invoke it. There are two ways to invoke a function in JavaScript:
greet("Alice"); // Output: Hello, Alice!new keyword
new keyword with a function creates a new object instance and invokes the function as a constructor. This will automatically call the function and execute its code.const alice = new greet("Alice");
// Output: Hello, Alice! (However, the function actually returns undefined)š” Pro Tip: When using the new keyword, the function must return an object or be a constructor function. If the function doesn't return anything explicitly, it will implicitly return undefined.
Functions can take arguments, which are values passed to the function during its invocation. These values can then be used within the function's code.
function calculateArea(width, height) {
const area = width * height;
console.log("The area is: " + area);
}
calculateArea(4, 5); // Output: The area is: 20Functions can also return values, which are the output of the function. The returned value can be assigned to a variable or used in other expressions.
function addNumbers(a, b) {
const sum = a + b;
return sum;
}
const result = addNumbers(3, 5);
console.log("The sum is: " + result); // Output: The sum is: 8In JavaScript, variables have a scope ā a defined area within which they can be accessed. Function scope refers to the variables that are accessible within a function.
function myFunction() {
let x = 10;
console.log(x); // Output: 10 (because x is in the function scope)
}
myFunction();
console.log(x); // Output: ReferenceError: x is not defined (because x is not in the global scope)A callback function is a function passed as an argument to another function, which is then executed inside the outer function. This allows for the reuse and modularization of code.
function greetCallback(callback) {
const name = "Alice";
callback(name);
}
function sayHello(name) {
console.log("Hello, " + name + "!");
}
greetCallback(sayHello); // Output: Hello, Alice!Let's test your understanding!
What is the output of the following code?
What is the output of the following code?