DEV Community

Cover image for Day 100/100 Reverse Function
Rio Cantre
Rio Cantre

Posted on • Originally published at dev.to

Day 100/100 Reverse Function

banner

Declaring Functions

Functions allow you to package up lines of code that you can use (and often reuse) in your programs.

function reversString(reverseMe) {
         var reversed = "";
         for (var i = reverseMe.length - 1; i >= 0; i--) {
              reversed += reverseMe[i];
         }
         return reversed;
} 
Enter fullscreen mode Exit fullscreen mode

The reverseString() function had one parameter: the string to be reversed. In both cases, the parameter is listed as a variable after the function name, inside the parentheses. And, if there were multiple parameters, you would just separate them with commas.

Return statements

function sayHello() {
    var message = "Hello!"
    console.log(message);
}
Enter fullscreen mode Exit fullscreen mode

In the sayHello() function above, a value is printed to the console with console.log, but not explicitly returned with a return statement.

You can write a return statement by using the return keyword followed by the expression or value that you want to return.

function sayHello() {
    var message = "Hello!"
    return message; // returns value instead of printing it
}
Enter fullscreen mode Exit fullscreen mode

Function Recap

  • Functions package up code so you can easily use (and reuse) a block of code.

  • Parameters are variables that are used to store the data that's passed into a function for the function to use.

  • Arguments are the actual data that's passed into a function when it is invoked:

function add(x, y) {
var sum = x + y;
return sum; // return statement
}
Enter fullscreen mode Exit fullscreen mode

Code Snippets

for(var i=0; i<numbers.length; i++){
   for(var j=0; j<numbers[i].length; j++){
      if(numbers[i][j]%2===0)
         numbers[i][j]="even";
      else
         numbers[i][j]="odd";
      }
}
console.log(numbers);


var facebookProfile = {
    name: "Bear",
    friends: 123,
    messages: ["Bear loves fish", "Bear loves nap", "Bear love honey"],
    postMessage: function(message) {
        facebookProfile.messages.push(message);
    },
    deleteMessage: function(index) {
        facebookProfile.messages.splice(index, 1);
    },
    addFriend: function() {
        facebookProfile.friends = facebookProfile.friends + 1;
    },
    removeFriend: function() {
        if(facebookProfile.friends >0) 
           facebookProfile.friends = facebookProfile.friends - 1;
    }
};

console.log(facebookProfile);

Enter fullscreen mode Exit fullscreen mode

Summary

Happy Hacking!!!

Resource

Discussion (0)