0

I am new to javascript. I am creating a text adventure. I am trying to write a function to take a given parameter, and use the .toLowerCase and return it as the same variable. I think I have the general idea to do it, but I just can not get it to work. Thanks!

function lowercase(a){
    return a.toLowerCase();
}

var alive = 1;
while(alive == 1){
    var name = prompt("What is your name?");
    lowercase(name);
    document.write("Hello " + name + "!\n");
    break;
}

5 Answers5

1

You need to assign the result of the function:

name = lowercase(name);

Are you new to programming in general? Because Javascript is similar to most other language in this regard.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Also, you can skip `lowercase(a)` completely and just do this: `name = name.toLowerCase()`. – Dai Feb 28 '15 at 00:24
  • @Dai Of course, but it seems like he's trying to learn how to write and use functions. – Barmar Feb 28 '15 at 00:25
  • Yes @Dia. I do realize how to use .toLowerCase, but I want to learn how to use them. –  Feb 28 '15 at 00:31
1
name = lowercase(name);

Since you are returning the value in your function, you must reinitialize the value of the variable. Javascript as far as I know is not a "pass by reference" language. It has always been a "pass by value". Read more about it here.

What's the difference between passing by reference vs. passing by value?

Community
  • 1
  • 1
kapitanluffy
  • 1,269
  • 7
  • 26
  • 54
0

The value of the name variable isn't being changed at the moment, you need to assign it to the result of the function.

function lowercase(a){
    return a.toLowerCase();
}

var alive = 1;
while(alive == 1){
    var name = prompt("What is your name?");
    name = lowercase(name);
    document.write("Hello " + name + "!\n");
    break;
}
wnbates
  • 743
  • 7
  • 16
0

use name = lowercase(name); the function returns a result, but you have to assign this result to a variable in order to use it after, or you can simply say

document.write('Hello' + lowercase(name) + 'something');
qwerty_igor
  • 919
  • 8
  • 14
0
name = lowercase(name);

Note, you should almost always use "===" instead of "==". "===" tests whether something's value and data type (number, string, boolean, object, etc.) matches another, whereas "==" only tests whether the values match (after performing a type conversion). For example:

if ("42" == 42) { // true (string 42 equals number 42)
if ("42" === 42) { // false (string does not equal number, what you want)