DEV Community

Guna Ramesh
Guna Ramesh

Posted on

Function

In JavaScript, a function is a block of code designed to perform a specific task. It runs when it is called (invoked).
Function Declaration
A Function Declaration is a way of creating a function in JavaScript using the function keyword followed by the function name. It defines a reusable block of code that performs a specific task whenever the function is called.

code
function name(){
console.log("Gunalan")
}
name()
output
Gunalan
How to receive and give the arguments in function?
function name(name1,name2){
console.log("Gunalan")
console.log(name1,name2)
}
name("guna","ramesh")
I created a function named name.
The function has two parameters, name1 and name2.
Parameters are used to receive values when the function is called.
When I call the function using name("guna", "ramesh"), the values "guna" and "ramesh" are called arguments.
The first argument ("guna") is assigned to name1.
The second argument ("ramesh") is assigned to name2.
Then the function executes its code and prints:

Gunalan
guna ramesh

example 2 add two values in function
function name(val1,val2){
console.log("Gunalan")
console.log(val1+val2)
}
name(90,87)
output
Gunalan
177
when use return in function
Use return when you want a function to send a value back to where it was called.
function name(val1,val2){
console.log("Gunalan")
console.log(val1+val2)
return val1-val2
}
let result=name(90,87)
console.log(result)

output
Gunalan
177
3
Function Expression
A function expression means storing a function inside a variable.
const name=function(){
console.log("gunalan")
}
name()
output
gunalan

if you call before function expression its show error because its stored one variable.So dont call previously.
name()
const name=function(){
console.log("gunalan")
}
output
ReferenceError: Cannot access 'name' before initialization

Top comments (0)