0
0
Javascriptprogramming~5 mins

Function execution flow in Javascript

Choose your learning style9 modes available
Introduction

Functions help organize code into small tasks. Understanding how they run step-by-step makes your programs work correctly.

When you want to run a set of instructions multiple times.
When you need to break a big problem into smaller parts.
When you want to reuse code without rewriting it.
When you want to control the order in which your code runs.
When you want to get a result back from a set of instructions.
Syntax
Javascript
function functionName(parameters) {
  // code to run
  return value; // optional
}

// calling the function
functionName(arguments);

The function code runs only when you call it.

Parameters are inputs; arguments are the actual values you give.

Examples
This function prints a greeting when called.
Javascript
function greet() {
  console.log('Hello!');
}
greet();
This function adds two numbers and returns the result.
Javascript
function add(a, b) {
  return a + b;
}
let sum = add(3, 4);
console.log(sum);
This function checks if a number is positive and returns a message.
Javascript
function checkNumber(num) {
  if (num > 0) {
    return 'Positive';
  } else {
    return 'Not positive';
  }
}
console.log(checkNumber(5));
Sample Program

This program shows the order in which the function runs and how the program continues after the function call.

Javascript
function multiply(x, y) {
  console.log('Start multiply');
  let result = x * y;
  console.log('Result is', result);
  return result;
}

console.log('Before calling multiply');
multiply(4, 5);
console.log('After calling multiply');
OutputSuccess
Important Notes

Code inside a function runs only when you call the function.

After the function finishes, the program continues from where it left off.

Return sends a value back and stops the function immediately.

Summary

Functions run their code only when called.

The program pauses at the function call, runs the function, then continues.

Return values let functions give back results.