pexels.com

JavaScript Functions

PabasaraRathnayake

--

Today I will walk you through a lesson in JavaScript which is functions in a simple and easily understandable way. All you need is to read my whole blog and try out the code blocks I have provided.

Background needed : All you need is a code editor so that you can write your code. I’m using Visual Studio Code and you can use any other text editors such as Sublime, notepad++ you are familiar with. Make sure to save your code with the html extension (.html).

Let’s start!

What is a function?

A Java Script Function is a block of code designed to perform a particular task

Why Functions?

The main advantage of functions is reusability. Once you defined a function, you can call it a number of times according to your requirement providing different parameters giving different results.

Defining a function

To define a function the keyword function is used followed by a name, followed by a set of parentheses (). Inside parentheses parameters are passed. The code to be executed is written inside curly braces {}.

function name(parameter1, parameter2, parameter3) {
// write your code here to be executed
}

Note: Function parameters are explained below.

Calling a function

To execute a function we need to call the function. For that, function name followed by parentheses is written. Inside parentheses the arguments are passes.

function_name(argument1, argument2, argument3);

Once a function is defined, you can call it the number of times you want.

Function Parameters

Function parameters are the names in the function definition. After defining a parameter, JavaScript allows you to use those parameters for your function.

You can pass one parameter or many parameters at one time as well as different arguments for one parameter.

Not clear the difference of parameter and argument? Here is the answer.

Parameters are written inside the parentheses of function definition. Arguments are written inside the parentheses of function calling.

Using Parameters we say the function that we are providing you this much of data. Using Arguments we pass the actual values for those data.

The Return Statement

A function can have a return statement inside its curly braces. This is useful to take the value after a process such as calculation. This gives the final value returned by the function. That return value can be assigned to a variable and make use of it.

<!DOCTYPE html><html><body><p>This simple function dispaly the multiplication of 4 * 3</p><script>function myFunction(a, b) {     //function definitionreturn a * b;}var x = myFunction(4, 3);       //function callingdocument.writeln(x);            //priting output value</script></body></html>

So far so good!

Alert, Prompt, Confirm

JavaScript provides mainly three types of popup boxes which will be displayed in your browser once you executed a code.

Alert box

Have you ever seen that the browser ask you questions such as;

Do you want to leave this page?

And you need to click OK to proceed.

That’s an alert box. An alert box can be used when you want to ensure that information gets through to the user. User must click OK to proceed.

The alert function takes a single parameter, which is the text need to be displayed to the user in the popup box.

alert(Do you want to leave this page? \n Click OK);

<!DOCTYPE html><html><head><title>Alert Box</title></head><body><h2>JavaScript Alert Box</h2><script>alert("Do you want to leave this page?\nClick OK");</script></body></html>

Prompt box

A Prompt Box is used to take a value by the user before entering a page. In the prompt box, there are two options, OK or Cancel. User must click either OK or Cancel to proceed after entering the input value.

If the user clicks OK, the box returns the input value. If user clicks Cancel, the box returns null.

Here in the prompt box takes two parameters. One is label and the second one is a string

Label: what you want to display in the text box

String: A default string to display in the text box. This is optional.

If Cancel pressed,

<!DOCTYPE html><html><head><title>Prompt Box</title></head><body><h2>JavaScript Prompt Box</h2><script>var user = prompt("Please enter your age");alert(user);</script>
</body></html>

Confirm box

A confirm box is often used to let the user verify or accept something. There are two options in a confirm box also which are OK or Cancel.

If user clicks OK, box returns true.

If user clicks Cancel, box returns false.

<!DOCTYPE html><html><head><title>Confirm Box</title></head><body><h2>JavaScript Confirm Box</h2><script>var result = confirm("Do you really want to leave this page?");if (result == true) {alert("Thanks for visiting");}else {alert("Thanks for staying with us");}</script></body></html>

Are you not familiar with JavaScript Conditional Statements? Click here.

Local Variables

Variables that can be accessed only inside the function it is declared is a global variable. They are local to the function.

Functions Used as Variable Values

Earlier you have seen a function has been assigned to a variable.

A function can be assigned to a variable which means a function can be used for calculations and formulas.

var variable_name = function_name(parameter);

Try out to code a function by yourself now. Do some editing and see what happens.

Here is a calculator created using JavaScript functions.

<!-- create table --><body><script>//function for displaying valuesfunction dis(val){document.getElementById("edu").value+=val}//function for evaluationfunction solve(){let x = document.getElementById("edu").valuelet y = eval(x)document.getElementById("edu").value = y}//function for clearing the displayfunction clr(){document.getElementById("edu").value = ""}</script><div class = title >JavaScript Calculator</div><table border="1"><tr><td><input type="button" value="c" onclick="clr()"/> </td><td colspan="3"><input type="text" id="edu"/></td><!-- clr() function will call clr to clear all value --></tr><tr><!-- creating buttons and assigning values--><td><input type="button" value="+" onclick="dis('+')"/> </td><td><input type="button" value="1" onclick="dis('1')"/> </td><td><input type="button" value="2" onclick="dis('2')"/> </td><td><input type="button" value="3" onclick="dis('3')"/> </td></tr><tr><td><input type="button" value="-" onclick="dis('-')"/> </td><td><input type="button" value="4" onclick="dis('4')"/> </td><td><input type="button" value="5" onclick="dis('5')"/> </td><td><input type="button" value="6" onclick="dis('6')"/> </td></tr><tr><td><input type="button" value="*" onclick="dis('*')"/> </td><td><input type="button" value="7" onclick="dis('7')"/> </td><td><input type="button" value="8" onclick="dis('8')"/> </td><td><input type="button" value="9" onclick="dis('9')"/> </td></tr><tr><td><input type="button" value="/" onclick="dis('/')"/> </td><td><input type="button" value="." onclick="dis('.')"/> </td><td><input type="button" value="0" onclick="dis('0')"/> </td><!-- Evaluating function call eval()--><td><input type="button" value="=" onclick="solve()"/> </td></tr></table></body>

These websites will be useful for your self-studies.

w3schools

coursera

free code camp

--

--