Functions

·

1 min read

functions are used to automate repetitive tasks. functions can only be executed when someone invokes it (calls it). you can use functions anywhere inside of code just like variables.

Syntax:

functions are declared by using the function keyword, followed by the function name, followed by parentheses.

function functionName() {
//block of code to be executed 
}
functionName()

Example:

function greet(){
console,log("Hello World!")
}
greet()

Functions with parameters:

You can also pass parameters to function. parameters are local variables given inside the function. you can consider parameters as placeholders for arguments. arguments are the real values passed to the function. Parameters are initialized to the values of the arguments supplied. functions can have multiple parameters.

Syntax:

function functionName(parameter1){
// block of code to be executed using parameters
}
functionName(argument1)

Example:

function greetUser(username){
console.log("Welcome to the ***** **** "+ username)
}
greetUser("Tyler")

Arrow functions:

arrow functions are used to reduce the syntax of a function and if you want to create a temporary function with no name you can use arrow functions.

Example:

//it won't print anything unless we console log variable hello. 
let hello = () => "Hello World!";