Javascript Functions

JavaScript Functions

 

Many times, we need to perform same operation that needs to be repeated several times. 

Example, formatting the phone number in certain format whenever it appears in the application. That is where functions come into play. JavaScript function allows to use the same piece of code multiple times. 

To make it clearer, Even JavaScript itself has many build in functions. E.g.:

isNan() returns true, if object is not a number

returns false if object is a number 

JavaScript allows to create functions that can make it easier to do repetitive operations without repeating the same code repeatedly. These functions are also called "user defined functions." 

OK! Enough of theory, let us get into action. 

Simple function that displays a message in the pop-up window: 

function DisplayMessage() {

    alert("hello world!");

}

DisplayMessage();

Note: Local Variables and Outer Variables. 

Local variables are accessible only inside the block of code that they are declared in. 

function DisplayMessage() {

    var localVar = "This variable is declared within the function.";

    alert(localVar);

}

DisplayMessage(); //will show the pop up message.

alert(localVar); //Uncaught ReferenceError: message is not defined" 

Outer variables are accessible even outside the function block of code 

var OuterVar = "This variable is declared outside the function";

function DisplayMessage() {

    var localVar = " And This variable is declared within the function.";

    alert(localVar + OuterVar);

}

DisplayMessage(); //will show the pop up message.

alert(OuterVar);

Function to convert Fahrenheit to Celsius

 function toCelsius(fahrenheit) {

    return (5 / 9) * (fahrenheit - 32);

}

document.getElementById("p1").value = toCelsius('77'); 

Note:  Function cannot return more than one value but multiple values can be stored in an array like below: 

Function to divide numbers: 

Steps: 1. Create a function for dividing two numbers 

           2. Store the formula in a variable

           3. Store all three values in a array

           4. return array (Not returning one value) 

<html>

  <body>

    <div>

        <p id='p1'> </p>

        <p id='p2'> </p>

        <p id='p3'> </p>

  </div>

 </body>

</html>

function Divide (dividend, divisor) {

    var quotient = dividend / divisor;

    var arr = [dividend, divisor, quotient];

    return arr;

// Store returned value in a variable

var all = Divide(10, 2); 

// Displaying individual values

document.getElementById("p1").textContent = (all[0]); // 0utputs: 10

document.getElementById("p2").textContent = (all[1]); // 0utputs: 2

document.getElementById("p3").textContent= (all[2]); // 0utputs: 5








No comments:

Post a Comment

Date Object

Purple: Style Blue: HTML Green: JavaScript  <!DOCTYPE html> <html> <style> #dates {   font-family: "Trebuchet MS...