DEV Community

Mark Tony
Mark Tony

Posted on

JS - Functions

Function
Functions are reuseable code blocks that are used for particular task. It is executed when the particular function is called. Functions are fundamental in all programming languages.

  • A function can be created with the function keyword, a name, and parentheses.
  • The code to run is written inside curly brackets.
  <script>         
     function sayHello() {
    return "Hello World";

}
let greeting = sayHello();   

console.log(sayHello());


      </script>
Enter fullscreen mode Exit fullscreen mode

A function can be used many times,

function add(a, b) {
  return a + b;
}

let sum1 = add(5, 5);
let sum2 = add(50, 50);
Enter fullscreen mode Exit fullscreen mode

Local Variables

  • Variables declared within a JavaScript function, become LOCAL to the function.
  • Local variables can only be accessed from within the function.
// code here can NOT use ActorName

function myFunction() {
  let ActorName = "Surya";
  // code here CAN use ActorName
}

// code here can NOT use ActorName
Enter fullscreen mode Exit fullscreen mode

Local variables are created when a function starts, and deleted when the function is completed.

Function Input and Output

  1. Parameters - some values are sent to the function
  2. Arguments - some values are received by the function
  3. Function Code - some work is done inside the function
  4. Return Output - some value is returned from the function

The working flow of the Function:

1
The function returns the value "Hello world". But it will not run the code.

function sayHello() {
  return "Hello World";
}
Enter fullscreen mode Exit fullscreen mode

2
The code below will call the function; but it will not use the result.

function sayHello() {
  return "Hello World";
}

sayHello();
Enter fullscreen mode Exit fullscreen mode

3
When a function returns a value, you can store the value in a variable.

function sayHello() {
  return "Hello World";
}

let greeting = sayHello();
Enter fullscreen mode Exit fullscreen mode

4
Display the result

function sayHello() {
  return "Hello World";
}

console.log(sayHello());
Enter fullscreen mode Exit fullscreen mode

Top comments (0)