Wais Kamal
Wais Kamal

Reputation: 6180

How do I treat all function arguments as strings?

I have this function:

function read(x) {
  console.log("You typed: " + x);
}

If I run read("Hello") in the console, I get:

You typed: Hello;

But if I run read(Hello), I get:

Uncaught ReferenceError: Hello is not defined

I modified the function this way:

function read(x) {
  console.log("You typed: " + x.toString());
}

but no success.

So, I want to treat the function argument as a string, regardless of how the user inputs it. How do I accomplish this?

Upvotes: 1

Views: 942

Answers (3)

Serg
Serg

Reputation: 7475

When a user inputs a string it will be passed as a string. For example:

var str = "Hello";
read(str); // will print "You typed: Hello"

In other words, when you input a string, let's say via console, you don't have to put it into quotes. But when you set a string value to your variable in code you do have put it in quotes.

But what you are trying to do with this read(Hello) is to pass a variable named Hello which doesn't even exist in this context. To fix it you can write this:

var Hello = "Hello";
read(Hello); // will print "You typed: Hello"

and it will work just fine.

Upvotes: 0

god_papa
god_papa

Reputation: 49

Please read few basic of coding before getting deeper into programing.

When you called read like:

read("Hello");

Value was passed to read function. However on calling like:

read(Hello);

This is calling read function with value of variable Hello and Hello is never declared.

ReferenceError: The ReferenceError object represents an error when a non-existent variable is referenced.

Value can be string, number, Boolean, and array, object.

read(5);
read(true);
read('a');

These all are values.

var a = 55;
var b = 'Hello';
var c = false;

read(a); // Passing value of a variable
read(b); // Passing value of b variable
read(c); // Passing value of c variable

variables: You use variables as symbolic names for values in your application. The names of variables, called identifiers, conform to certain rules.

Upvotes: 1

Thomas
Thomas

Reputation: 181785

You can't. The language syntax is just designed this way, so if you write read(Hello) it will look for a variable named Hello. This doesn't exist, hence the error.

If you want to pass a string, you'll need to quote it (or assign it to a variable, then pass the variable). There's no way around that.

Upvotes: 3

Related Questions