DEV Community

Cover image for Javascript Functions. A quick guide..
faozziyyah
faozziyyah

Posted on

Javascript Functions. A quick guide..

Functions are often used in JavaScript by developers. In fact, it's used in other programming languages like python as well. But in this article, we'll focus on using functions in Javascript.

Definition of a Function:
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).

There are two types of functions.
✔️ In-built functions
✔️ User defined functions.

🌟 In-built functions are special functions used to perform special tasks.
An example is the .to precision() function, this is used on number data type and it returns a string of that number but to a certain significant figures based on the argument passed into it.
We also have the .toUpperCase and .to lowercase In-built functions and many other examples.

🌟 Javascript user defined functions are functions created by the user to perform tasks as well like the example below:
function name(){
alert("this is my name!");
}
In the example above, name() is a user defined function.

✔️ Function parameters: These are the names listed in the function's definition. For example;
function sayHello(name){
alert("Hi," + name);
}
sayHello("David");

Taking a look at this example, the parameter in this function is "name". While the expression sayHello("David") is known as calling the function.

📌 Therefore, note that for a function to be executed, it has to be called just like in the example above.

✔️ Multiple parameters: They can be defined with comma separating them. They're the names listed in the function definition. For example;
function sayHello(name,age){
document.write(name + "is" + age + "years old");
}
sayHello("John", 20);

✔️ Function Return: This is used to return a value from the function e.g when making calculation that require a result. For example
function addNumbers(a,b){
return a+b;
}
addNumbers(5,6);

✔️ Anonymous Function: Also known as function expression. This is a function assigned to a variable. For example
var sayBye = function (){
console.log("Bye");
}
sayBye();
To read more on Javascript functions, you can go through this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
I hope you learnt something new today.
Thank you for reading.

Top comments (0)