Zum Inhalt springen

#1 Funtions in JavaScript

Image description1.JavaScript function is a block of code designed to perform a particular task.

2.A JavaScription function is executed when someone calls it .

Syntax

function name(parameter1, parameter2, parameter3) {
  // code to be executed
}

1.Function keyword followed by function name and paranthesis ‚()‘

2.Paranthesis may include parameters separated by commas.

3.The code to be executed by the function is placed inside the curly brackets {}

4.Function parameters are named placeholders in the function definition.

5.Arguments are actual values passed to the function when it is called.
Function arguments behave like ‚local variables‘.

Let us get to know What are local variables?

1.A variable that is declared within a specific scope such as function or a blcok of code (like if statement, for loop or while loop).

2.The key characteristic of a local variable is limited accesibility. It can be accessed within the code where it was defined .

function calculateSum(num1, num2) {
  // 'sum' is a local variable, accessible only within calculateSum()
  let sum = num1 + num2; 
  console.log(sum); 
}

calculateSum(5, 10); // Output: 15

// Attempting to access 'sum' outside the function will result in an error
// console.log(sum); // ReferenceError: sum is not defined

Function Return

1.A Return statement is used to specify a value that should be returned from a function when it is called .

2.Once a return statement is executed the function stops running and the specified value is sent back to where the function was called .

Example 1:Returning a Value

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

let result = add(3, 4);
console.log(result); // Output: 7

Example 2: Returning Nothing (undefined)

function greet(name) {
    console.log("Hello, " + name);
}

let result = greet("Alice");
console.log(result); // Output: undefined

How to Fix It (if you want a return value):

If you want greet() to return a value instead of just printing it:


function greet(name) {
    return "Hello, " + name;
}

let result = greet("Alice");
console.log(result); // Output: Hello, Alice
Now the function returns a string, and that value is stored in result.

Why Functions?

  1. With Functions you can reuse the code .

  2. Can use the same code with different arguments and get different results.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert