முக்கிய உள்ளடக்கத்திற்குச் செல்லவும்
eLearner.app
தொகுதி 4 · பாடம் 1 இன் 4பாடத்திட்டத்தில் 13/32~10 min
தொகுதி பாடங்கள் (1/4)

ஒரு செயல்பாட்டை அறிவிக்கிறது

A function is a reusable piece of code that you give a name to. You call it by passing arguments, it runs its body and can return a value with return.

Classic declaration

The most common form is the function declaration:

JS
function saluta(nome) {
  return `Ciao, ${nome}!`;
}

saluta('Anna'); // 'Ciao, Anna!'
saluta('Marco'); // 'Ciao, Marco!'

Things to note:

  • nome is the parameter (a variable local to the function).
  • 'Anna' is the argument (the value passed at call time).
  • Without return, the function returns undefined.

Function expression

Functions in JS are values: they can be assigned to a variable.

JS
const quadrato = function (n) {
  return n * n;
};

quadrato(4); // 16

The two forms are almost equivalent, with one important difference:

  • function declaration is "hoisted": you can call it even before the line where it appears in the code.
  • function expression follows const/let rules: it exists only after the assignment.

No explicit return

JS
function logga(msg) {
  console.log(`[LOG] ${msg}`);
  // no return → the function returns undefined
}

const r = logga('ciao'); // prints "[LOG] ciao"
r; // undefined

Try it

உடற்பயிற்சி#js.m4.l1.e1
முயற்சிகள்: 0ஏற்றுகிறது…

Declare a function `greet(name)` that returns the string `Ciao, <name>!`. Then call it with 'Anna' and use the result as the last expression.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

function greet(name) { return ... }

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்

Review exercise

உடற்பயிற்சி#js.m4.l1.e2
முயற்சிகள்: 0ஏற்றுகிறது…

Write a function expression `double` that, given a number, returns its double. Call it with 7 as the last expression (expected 14).

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

const double = function (n) { return ... };

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்