ReactJS-Function

Functions:

const square = function(x) {

  return x * x;

};

console.log(square(3));


// → 9

Function`s Parameters

A function can have multiple parameters 

const roundTo = function(n, step) {

  let remainder = n % step;

  return n - remainder + (remainder < step / 2 ? 0 : step);

};

console.log(roundTo(23, 10));

// → 20

or no parameters at all

const makeNoise = function() {

  console.log("Pling!");

};

makeNoise();

// → Pling!

Nested functions

const hummus = function(factor) {

  const ingredient = function(amount, unit, name) {

    let ingredientAmount = amount * factor;

    if (ingredientAmount > 1) {

      unit += "s";

    }

    console.log(`${ingredientAmount} ${unit} ${name}`);

  };

  ingredient(1, "can", "chickpeas");

  ingredient(0.25, "cup", "tahini");

  ingredient(0.25, "cup", "lemon juice");

  ingredient(1, "clove", "garlic");

  ingredient(2, "tablespoon", "olive oil");

  ingredient(0.5, "teaspoon", "cumin");

};

console.log(hummus(8));

//

8 cans chickpeas

2 cups tahini
2 cups lemon juice
8 cloves garlic
16 tablespoons olive oil
4 teaspoons cumin
undefined

Arrow functions =>  // note: introduced in ES6


It allows to write shorter codes

the code:

let hello = "";

hello = function() {
  return "Hello World!";
}

document.getElementById("demo").innerHTML = hello();

Same code with arrow *IF it has many statements:


let hello = "";

hello = () => {
  return "Hello World!";
}

Same code with arrow *IF it has one statement:

 
let hello = "";

hello = () => "Hello World!";

document.getElementById("demo").innerHTML = hello();

Same code with arrow *IF it has one statement + multi Parameters:

 
let hello = ""; hello = (val) => "Hello " + val;
document.getElementById("demo").innerHTML = hello("Universe!"); 

Same code with arrow *IF it has one statement + one Parameter :

 
let hello = ""; hello = val => "Hello " + val; document.getElementById("demo").innerHTML = hello("Universe!");


Comments

Popular posts from this blog

Programming- AI, machine learning

Programming -- JS, C, C++, Python

links - Robotic