What is A Function in Javascript?
AdelabuAderonke
Posted on June 14, 2020
A JavaScript function is a block of code designed to perform a particular task. A block of reusable code which helps prevent repetition.
Function Definition
You need to define a function in javascript before using it. We define a function in javascript by writing the Function keyword followed by Function Name(which can contain letters,numbers,same rules for naming variables also affect it) and bracket which might be empty or contain one or more parameters and statement codes which are surrounded by curly braces.
Basic syntax for function
function function Name(){
*//statement of codes
}
The above syntax will not work except you call the function
Function Invocation
To invoke a function or call a function to execute a statement of codes. You simply write the function name with a pair of brackets outside the curly braces.
let's write a function to greet a user.
function greet(){
console.log("Hello!!");
}
greet(); *//function invocation
Output
Hello!!
Function Parameter & Argument
We have successfully run a code without including a parameter, it is time to explore parameters and arguments. once you use a parameter for function declaration, you have to use a corresponding argument for the function invocation.
let's update the code above by adding name and age to the function
function greet(name, age){
console.log("Hello!!"+ name + "you are"+ age +"Years old.");
}
greet("John", 14);
Output
** Hello!! John you are 14 years old.
Awesome we have been able to cover the basics of function. You can simply reuse the code by calling the function multiple times.
You can try this out on your own by using different ages and names for the above like this:
*greet("Ali", 10);
*greet("Sam", 9);
Posted on June 14, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024