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;
}
3
  • Strings are immutable. Every method that changes a string value in any way returns a new string. Commented Feb 28, 2015 at 1:30
  • Why are you running a while loop and then breaking out of it straight away? Commented Feb 28, 2015 at 1:48
  • @Qantas94Heavy I was just doing that for testing Commented Mar 1, 2015 at 0:52

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Also, you can skip lowercase(a) completely and just do this: name = name.toLowerCase().
@Dai Of course, but it seems like he's trying to learn how to write and use functions.
Yes @Dia. I do realize how to use .toLowerCase, but I want to learn how to use them.
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?

Comments

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');

Comments

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;
}

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.