Programming

JavaScript functions: parameters and return

Write a function, call it, pass a parameter and get the result back with return.

All lessons · JavaScript lessons: learn from scratch

Write a function and call it

A function writes one job once and runs it many times. After function come the name, then () and {}. Writing it does not run it. It runs when you write the name and (). If you forget the parentheses, nothing happens.

function seslen() {
  console.log("Burdayam");
}
seslen();

function yazdir(ad) {
  console.log(ad);
}
yazdir("Əli");

A parameter and return

A parameter is information given to the function. return sends a result back and stops the function on that line. console.log only prints. It does not keep the value. If the second parameter is missing, the result is NaN.

function topla(a, b) {
  return a + b;
}
console.log(topla(4, 6)); // 10

function yoxla(bal) {
  if (bal >= 50) return "Keçdi";
  return "Kəsildi";
}
console.log(yoxla(40));

A function and an array

An array can be a parameter too. Inside, a for loop can find the sum and the largest number. If {} is not closed, you get an error. The line after return does not run.

function massivCemi(ededler) {
  let cem = 0;
  for (let i = 0; i < ededler.length; i++) {
    cem = cem + ededler[i];
  }
  return cem;
}
console.log(massivCemi([1, 2, 3, 4])); // 10

function enBoyuk(ededler) {
  let max = ededler[0];
  for (let i = 1; i < ededler.length; i++) {
    if (ededler[i] > max) max = ededler[i];
  }
  return max;
}

Questions

Why does a function not run by itself? You must call it: seslen(). Writing only the name, without parentheses, is not enough.

What is the difference between console.log and return? console.log shows. return gives the value back so you can keep it somewhere else.

Why does code after return not run? return stops the function. The line after it is not read.

What if I pass one number to a function with two parameters? The second is undefined and the sum is NaN. Pass every parameter.

Author: Nibras Code