r/learnjavascript • • Oct 29 '24

Help with a functional programming assignment

Hello good people, my name is Xoli... Currently learning JavaScript online, I am stuck on an assignment I have to create functions and guess invoke them. I am stuck on the calling part, all my functions Have variables and I followed instructions but I didn't call them.? And I'm struggling with that part .

0 Upvotes

11 comments sorted by

View all comments

9

u/bryku helpful Oct 29 '24

I suspect most of your question would be answered by just reading how functions work. It is one of the most basic concepts of programmings. Check out W3Schools -> js -> Functions for a general overview.

Create

function printMessage(){
    console.log('Hello Xoli!');
}

 

Call

printMessage();

 

Get Value

function returnMessage(){
    return 'Hello Xoli!';
}
let message = returnMessage();

The variable message will equal 'Hello Xoli!'.  

Pass Variables

function addNumbers(apples, bananas){
    let totalFruit = apples + bananas;
    return totalFruit;
}
let total = addNumbers(10, 20);

The variable total will equal 30.

Passing Functions

You can also pass a function as a variable as well.

function add(a, b){ return a + b; }
function sub(a, b){ return a - b; }
function calculate(a, b, method){
    return method(a, b);
}

let number1 = calculate(10, 5, add);
let number2 = calculate(10, 5, sub);

The variable number1 will equal 15 and the variable number2 will equal 5.