cover-img

Javascript functions

8 March, 2023

4

4

0

Contributors

Functions are an essential part of Javascript. They allow you to define reusable blocks of code that can be called and executed whenever needed. Functions are declared using the function keyword, followed by the function name and a set of parentheses that can optionally contain parameters.

Here's an example of a simple function that takes two parameters and returns their sum:

function addNumbers(num1, num2) {
return num1 + num2;
}

In this example, we've declared a function called addNumbers that takes two parameters: num1 and num2. Inside the function, we use the return keyword to return the sum of the two parameters.

To call this function, we simply need to pass in two arguments:

const result = addNumbers(2, 3);
console.log(result); // 5

In this example, we're calling the addNumbers function and passing in the values of 2 and 3 as arguments. The function then returns the sum of these two numbers, which we store in a variable called result.

Functions can also be assigned to variables, which makes them easier to pass around as arguments to other functions. Here's an example:

const addNumbers = function(num1, num2) {
return num1 + num2;
}

In this example, we've declared a function called addNumbers and assigned it to a variable of the same name using the const keyword. We can then call this function just like we did in the previous example:

const result = addNumbers(2, 3);
console.log(result); // 5

One important concept to understand when working with functions in Javascript is scope. Variables declared inside a function are only accessible within that function - they are not visible outside of it. This is known as function scope. Here's an example:

function myFunction() {
const myVariable = "Hello, world!";
console.log(myVariable);
}

myFunction(); // "Hello, world!"
console.log(myVariable); // Error: myVariable is not defined

In this example, we've declared a function called myFunction that declares a variable called myVariable and logs its value to the console. We then call the function, which logs "Hello, world!" to the console.

However, when we try to log myVariable outside of the function, we get an error. This is because myVariable is only visible inside the function - it doesn't exist outside of it.

In summary, functions are a powerful feature of Javascript that allow you to define reusable blocks of code. They can take parameters and return values, and can be assigned to variables. It's important to understand scope when working with functions, as variables declared inside a function are only visible within that function.

4

4

0

ozboware
PHP and Javascript app developer

More Articles