JavaScript Functions
Understanding Functions in JavaScript
Functions are reusable blocks of code that perform a specific task. They can take inputs, called parameters, and can return outputs. Functions help organize code and make it more modular.
Example 1: Basic Function
function myFun() {
console.log("hello")
console.log("DeathCode")
}
myFun()
This is a simple function named myFun
that logs two messages to the console. It is invoked by calling myFun()
.
Example 2: Function with Return Value
function add5and6(){
let sum = 5 + 6
return sum
}
console.log(add5and6())
The add5and6
function calculates the sum of 5 and 6 and returns the result. The returned value is then logged to the console.
Example 3: Function with Parameters
function addTwoNumbers(a, b){
let sum = a + b;
console.log(sum)
}
addTwoNumbers(5, 7);
addTwoNumbers(6, 7);
This function takes two parameters, a
and b
, calculates their sum, and logs it to the console. It is called multiple times with different arguments.
Example 4: Returning Values from Functions
function addTwoNumbers(a, b){
return a + b;
}
console.log(addTwoNumbers(14, 78));
console.log(addTwoNumbers(45, 34));
In this example, the function addTwoNumbers
returns the sum of its parameters. The returned values are logged to the console.
Example 5: Function with Rest Parameters
function addNumbers(...numbers){
let sum = 0;
for(let i = 0; i < numbers.length; i++){
sum += numbers[i];
}
return sum;
}
console.log(addNumbers(1, 2, 3, 298374, 238, 238947));
This function uses the rest parameter syntax (...numbers
) to accept an arbitrary number of arguments. It calculates the sum of all provided numbers and returns the result.
Example 6: Modifying Objects
function myFun3(o){
o.email = "example@example.com"
}
let user = {
name: "John",
age: 30,
email: "john@example.com",
}
console.log(user);
myFun3({...user});
console.log("After calling Function: ", user);
This example demonstrates how functions can modify objects. The function myFun3
attempts to change the email
property of the user
object. However, since a new object is created using the spread operator ({...user}
), the original user
object remains unchanged.
Conclusion
In this document, we explored the fundamentals of functions in JavaScript, including how to define, invoke, and return values from functions. We also examined the use of parameters and the spread operator to manipulate objects. Understanding functions is crucial for writing efficient and organized code in JavaScript.