1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
let a = 5; let b = 3; function sum(a , b) { let c = a + b; console.log(c); } sum(a, b); //8 a = 8; b = 12; sum(a, b); //20 |
1 2 3 4 5 6 7 8 9 10 |
function myFn(a, b) { let c; a = a + 1; c = a + b; return c; } console.dir(myFn); console.log(myFn(5, 10)); // 16 console.log(myFn(a)); // Uncaught ReferenceError: a is not defined |
Scope
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function myFunction1(a, b) { console.log(a, b); } function myFunction2(a, b) { console.log(a, b); } const a = true; const b = null; myFunction1(2, 3); // 2, 3 myFunction2(4, 5); // 4, 5 console.log(a, b); // true, null |
return
1 2 3 4 5 6 7 |
function sum(a, b) { return a + b; } sum(10, 5); // 15 sum("abc", 2); // "abc2" sum(); // NaN (Not a Number) |
1 2 3 4 5 6 7 8 9 |
function myFunction(a) { console.log(a); return a; // function stops HERE console.log(a); const c = 10; console.log(c); // code NOT evaluated } myFunction(10); |
1 2 3 4 5 6 7 8 9 10 11 |
function mult(a, b, c) { const result = a * b * c; console.log(result); } mult(0,3,5); // 0 mult(2,3,5); // 30 mult(2,3,"abc"); // NaN mult(); // NaN console.log(mult(2,3,5)); // 30 is printed inside of the function and function returns "undefined" |
1 2 3 4 5 6 |
function concatenatedStrings(str1, str2) { return str1 + " " + str2; } const str3 = concatenatedStrings("Hello", "World"); console.log(str3); // Hello World |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
function outerFunction(a, b) { function innerFunction(c) { return c * c; } const sum = a + b; const result = innerFunction(sum); console.log(result); } outerFunction(5, 2); // 49 // ...which can be simplified as: function outerFunction(a, b) { function innerFunction(c) { return c * c; } console.log(innerFunction(a + b)); } outerFunction(5, 2); // 49 |
Fonctions anonymes
Function expression assigned to the variable:
=> variable à laquelle est assignée une « function expression »
1 2 3 4 5 6 7 8 |
const myFunction = function(a, b) { let c; a = a + 1; c = a + b; return c; }; myFunction(5, 3); // 9 |
Function expression as argument in the function call
=> callback function
1 2 3 |
setTimeout(function() { console.log("Delayed message"); }, 1000); |
callback function
setTimeout();
1 2 3 4 5 6 7 8 |
/** * CALLBACK FUNCTION * setTimeout */ setTimeout(function() { console.log("Delayed message"); }, 1000); |
setInterval();
1 2 3 |
setInterval(function(){ console.log("Message logged each 1 second"); }, 1000); |
Compteur incrémentiel avec la méthode setInterval()
1 2 3 4 5 |
let i = 1; setInterval(function(){ console.log("Message logged each 1 second " + i); i = i + 1; }, 1000); |
Compteur incrémentiel qui s’arrêt automatiquement à 5 avec les méthodes setInterval(), clearInterval() et setTimeout()
1 2 3 4 5 6 7 8 9 10 11 |
let i = 1; const repeat = setInterval(function() { console.log("Here is message number " + i); i = i + 1; }, 1000); repeat; setTimeout(function(){ clearInterval(repeat); }, 5000); |