Help!


#1

Hey can someone please help me with the whole functions thing ! I am not understanding it.


#2

A function is a pre-made, reusable set of instructions. They are used to keep your code D.R.Y. (Don't repeat yourself). They are meant to shorten and/or speed up your code. You could print "Hi" five times using console.log, or you could use a function to do this when needed. Example:

console.log("Hi");
console.log("Hi");
console.log("Hi");
console.log("Hi");
console.log("Hi");

Or

var printHi = function(times) {
    for (i = 0; i < times; i++) {
        console.log("Hi");
    }
};
printHi(5);

#3

Can you please explain the return thing too?


#4

Return just prepares your data for further processing. It is a best practice to (nearly always) use return in your function. If you use console.log() then it would be turned into a string, which you may not want.


#5

Thank you very much cadecodes.


#6

Anytime! Just post again if you need anymore help! :slightly_smiling:


#7

Whats the error with this???

var nameString = function (name ) {
return "Hi, I am" + " " + name;
};
nameString(Soham);
Oops, try again. Your code doesn't look quite right. Click "Stuck? Get a hint!" if you need help!


#8

That was functions recap.


#9

Soham needs to be in quotes ("Soham") because it is a string! :slightly_smiling:


#10

Oh God
:slightly_smiling:


#11

var nameString = function (name ) {
return "Hi, I am" + " " + name;
};
nameString("Soham");
Oops, try again. There was a problem with your syntax.
Now whats wrong???


#12

It may be a spacing problem. Line 1 should be:

var nameString = function(name) {

#13

No,its not that.The problem is not spacing.


#14

I believe you need to call console.log on it
console.log(nameString("Soham"));