Home > Blockchain >  JavaScript beginner understanding with functions
JavaScript beginner understanding with functions

Time:11-04

// Area of the first rectangle
const width1 = 10;
const height1 = 6;
const area1 =  width1 * height1;
 
// Area of the second rectangle
const width2 = 4;
const height2 = 9;
const area2 =  width2 * height2;
 
// Area of the third rectangle
const width3 = 10;
const height3 = 10;
const area3 =  width3 * height3;

Ok so I am beginner in JavaScript learning and am having a really hard time understanding 'functions' in JavaScript along with its 'return' keyword.

And above is an example for me to understand how exactly function is gonna make that code easy or in fewer steps.

I understand the functions are there as a shortcut or prevention of writing same sort of code for different things over and over again but if someone helps me create a function syntax and convert the above code into it, then that'll be easier for me to understand how function is created.

I want help in undertanding javascript functions and i expect a nice breakdown teaching of it

CodePudding user response:

Define a function with a name you want like myRectangle in my case and give it some parameters like width and height in this function. Then declare an area variable inside the function and assign to it the produit of width and height. Then return back the area.

function myRectangle(width, height) {
    let area = width * height;
    return area;
}

Now, to use the function, you just need to declare a variable and call the function with real arguments

Example:

rectangle1 = myRectangle(4, 3);
console.log(rectangle1); // 12

For more information checkout the MDN docs : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

CodePudding user response:

Functions in javascript are relatively easy. They are blocks that contain meaningful items that carry out your repetitive task. In your case, the area of a rectangle can be implemented in the following way

function CalculateArea(width, length){
const area = width * length
return area;
}

Return statements are the final product of a function and as the name suggests return a value. hence

const area1 = CalculateArea(10, 6); //answer will be 60
const area2 = CalculateArea(4, 9); //answer will be 36
const area1 = CalculateArea(10, 10); //answer will be 100

The area is calculated by a single block that can be recalled with arguments (width and length) and give back the result of the calculation done.

  • Related