Functions recap


#1

Hi everyone,
I am having a little trouble with this. Can you help.

It console.logs: Hi, I am Jahim

However I have an error code of: Oops, try again. Did you create a function called nameString() ?
Thanks in advance.

var nameString = function(name) {
    return "Hi, I am" + " " + name;
};
nameString = "Jahim";
console.log( "Hi, I am" + " " + nameString);

#2


I dont know if this is it but why do you have 2 semi - colon's?


#3

@jahim.ibrahim you would not need to write this:

you would just need to call nameString and pass it a name like this:

console.log(varible_name("some name"));

Hope this helps.

Steven


#4

@desiigner that is not an error. It is okay for you to write code like that. (In fact it is the right way!)


#5

Thanks.
I kept the semicolons, but I modified a
the console log statement. view reply to @steven.copeland. below.

var nameString = function(name) {
    return "Hi, I am" + " " + name;
};
console.log( nameString("Jahim"));

I name t the function in the console log then the value in it.


#6

You can check if there is a bug in your code by looking here but if their is no bug in your code like yours here:

It will NOT show you an error.


#7

To summarize this problem a bit:
as @steven.copeland mentioned the semicolons are not an issue here but are 100% correct.
https://www.codecademy.com/blog/78
The real problem are these two lines:

nameString = "Jahim";
console.log( "Hi, I am" + " " + nameString);

Because what happens is that by the first line:

nameString = "Jahim";

you replace your function:

function(name) {
    return "Hi, I am" + " " + name;
}

with this value:

 "Jahim"

So when the test function wants to call nameString("testName") it fails because nameString is no longer a function and therefore this adding of parenthesis won't work. That is why it asks you to create a nameString function although you already did this.

You found a workaround by just doing what the function does without using the function but that is not really what the exercise wants you do practice :wink:

PS: You'll see that the function is useful when you call it multiple times with different names, because instead of:

nameString = "Jahim";
console.log( "Hi, I am" + " " + nameString);
nameString = "desiigner";
console.log( "Hi, I am" + " " + nameString);
nameString = "steven";
console.log( "Hi, I am" + " " + nameString);

you could just write:

console.log( nameString("Jahim"));
console.log( nameString("desiigner"));
console.log( nameString("steven"));

especially when the functions get longer it might be really helpful that you can change the output and behavior of a function by simply using a different parameter as input.


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.