JavaScript Functions Tutorial
What are JavaScript Functions?
- A function in JavaScript is a reusable block of code that performs a specific task.
- Functions help in modularizing code, making it more readable and maintainable.
- They can take inputs, process them, and return an output.
- You've already worked with certain built-in functions in JavaScript, such as the console.log() method and similar ones.
- In a function, you can include variables, loops, data types, and pretty much everything needed to make the code work.
- When you're building an app, there's a good chance you'll have to do the same thing in different parts of it. For instance, you might want to display a message whenever something goes wrong.
- To save yourself from typing out the same code everywhere, you can create a function. This way, you bundle up that code in one place, and you can use it over and over without having to write it again each time.
- You might see a similarity to a loop, but there's a difference. Loops keep going through the code until a specific condition is met, while functions execute the code only when they are called where the part of application needs that function logic.
Creating Functions
- The JavaScript Function declaration is the most straightforward way to create a function.
- It starts with the function keyword, followed by the function name, parameters (if any), and the function body enclosed in curly braces.
function greet() {
console.log("Hello, Everyone!");
}
Calling the Function?
- To call the function, you simply use its name and provide the required arguments.
- Yet, we don't necessarily have to give details when using the parameters.
function greet() {
console.log("Hello, Everyone!");
}
greet(); //output: Hello, Everyone!
A function will continue to print output until it is no longer called.
greet(); //output: Hello, Everyone!
greet(); //output: Hello, Everyone!
greet(); //output: Hello, Everyone!
JavaScript Function Parameters and Arguments
- In a function, parameters are basically the variables mentioned in the function definition. They help define what kind of information the function will get when you use it.
- On the other hand, when you call a function, the values you provide to it are called arguments.
- These arguments get linked to the parameters of the function, and the order matters – the first argument goes to the first parameter, the second to the second, and so on.
Syntax:
function functionName(parameter1, parameter2, ...) {
// function body
}
functionName(argument1, argument2, ...); // Function call
function greet(name, message){
console.log(`Hello, ${name}, ${message}`) ;
}
greet("Alex", "How are You?"); //Output: Hello, Alex, How are You?
greet("Charlie", "Are you Good?"); // Output: Hello, Charlie, Are you Good?
let name = "Jack";
let msg= "how are you?";
greet(name, msg); // Output: Hello, Jack, how are you?
You can also call a function from within another function. This is called function nesting.
function greetAndSayGoodbye(name) {
greet(name);
console.log(`Goodbye, ${name}!`);
}
greetAndSayGoodbye("Alex"); // Outputs:
// Hello, Alex!
// Goodbye, Alex!
Function return values
- A function return value is the value that a function returns to the caller.
- This value can be used by the caller in any way it sees fit. For example, the caller can store the value in a variable, pass it to another function, or print it to the console.
- To return a value from a function, you use the return keyword.
function greet(name){
let greeting = `Hello, ${name}`;
return greeting;
}
let greeting = greet("Alex"); // Storing the return value in a variable
console.log(greeting); // Output: Hello, Alex
console.log(greet("Charlie")) // Directly using the return value.
// Output: Hello, Charlie
Let's see an another JavaScript Function Example on return values.
function calculateTotal(products){
let result = 0;
for(i=0; i<products.length; i++){
result = result + products[i];
}
return result;
}
let priceArray = [980, 879, 970];
let result = calculateTotal(priceArray);
console.log(`The total price is: ${result}`); // Output: The total price is: 2829
Function Scope
- Function scope is the region of a program in which a variable is defined and can be accessed.
- A variable defined inside a function is only accessible within that function and its nested functions.
- Variables defined outside of functions are accessible to all functions in the program.
const name = "Alex"; // Global and access to anywhere in the code
function greet() {
let name = "Alex"; // Local Variable and access withing this function
console.log(`Hello, ${name}!`);
}
greet("Charlie"); // Outputs: Hello, Charlie!
console.log(name); // Outputs: Alex
If the local variable and global variable names are same then it takes the local variable.
Function Expression
- A function expression is another way to define a function. It involves assigning an anonymous function to a variable.
const greet = function(name) {
console.log("Hello, " + name + "!");
};
greet("Alice"); // Output: Hello, Alice!
greet("Bob"); // Output: Hello, Bob!