Pass a string to a JavaScript function by placing it inside the function call’s parentheses: greet('Maya'). The function receives it through a parameter, such as function greet(name) { ... }; strings are primitive values, so the parameter receives the string’s value, not a reference that lets the function change the original string.
Pass a String as an Argument
A function definition names the parameter it expects, and a function call supplies the argument. The parameter is a local name available inside the function. The argument is the value supplied at the call site. The names do not have to match:
function greet(person) {
return `Hello, ${person}!`;
}
const message = greet('Maya');
console.log(message); // Hello, Maya!
Here, person is the parameter and 'Maya' is the argument. When the call runs, JavaScript assigns the string value to the parameter for that function call. You can also pass a string stored in a variable:
const name = 'Maya';
greet(name);
Use parentheses even when there is just one argument. If the function expects a string, pass a string expression there: a quoted literal, variable, concatenation, or function result. The value does not have to be written directly in the call.
Choose the Right String Syntax
JavaScript supports single-quoted strings, double-quoted strings, and template literals. Single and double quotes work for ordinary string values. The opening and closing quote must match, and the string cannot contain an unescaped copy of its delimiter. Template literals use backticks and can include expressions inside ${...}.
printName('Maya');
printName("Maya");
printName(`Maya`);
const firstName = 'Maya';
printName(`Hello, ${firstName}`);
These calls all pass strings. The last call evaluates the template literal first and passes the resulting text, Hello, Maya. Template literals are useful for building text from variables, but they are not automatically safe HTML or SQL; escaping and parameterization depend on where the value will be used.
A frequent syntax mistake is leaving a text value unquoted. In greet(Maya), JavaScript treats Maya as an identifier, such as a variable name. If no variable with that name exists, the call throws a ReferenceError. Write greet('Maya') when Maya is literal text.
What Happens to the Argument
JavaScript passes arguments by value. For a string, the value copied into the parameter is the string value itself. Because strings are primitive values and immutable, a function cannot alter the characters in the caller’s string. String methods such as toUpperCase() return a new string rather than changing the existing one.
function shout(text) {
text.toUpperCase();
return text;
}
const original = 'hello';
console.log(shout(original)); // hello
console.log(original); // hello
The call to toUpperCase() creates the value HELLO, but this example discards that return value. To use the transformed text, return it or assign it to a variable:
function shout(text) {
return text.toUpperCase();
}
const result = shout('hello');
console.log(result); // HELLO
It is sometimes said that JavaScript passes objects by reference. More precisely, JavaScript passes values in every case. When the value is an object, that value identifies the object, so a function can use it to mutate the shared object. A string is not such an object reference. This distinction explains why changing a string parameter does not rewrite a variable outside the function.
Reassigning a Parameter Does Not Replace the Caller’s Variable
A parameter is a local binding. Assigning a new string to that parameter changes what the local name refers to, not the variable used as the argument. The caller’s variable remains unchanged:
function addGreeting(text) {
text = `Hello, ${text}`;
return text;
}
let name = 'Maya';
const greeting = addGreeting(name);
console.log(greeting); // Hello, Maya
console.log(name); // Maya
To keep a transformed result, return it and use the returned value, as above. If you need the caller to observe a change without using a return value, you could put the string in an object property and update that property. Usually, returning the new string is simpler and makes the function’s behavior easier to understand.
Also note that const prevents reassignment of the variable, not all operations involving its value. A string cannot be edited in place regardless of whether its variable was declared with const or let. Use let only when the variable itself needs to be assigned a different value later.
Pass More Than One String
Functions can accept several arguments. Their order must match the order of the parameters in the definition, so clear parameter names and call sites matter:
function formatName(first, last) {
return `${first} ${last}`;
}
const fullName = formatName('Maya', 'Chen');
JavaScript does not enforce a declared string type for ordinary function parameters. A caller can pass a number, object, or other value instead. If the function relies on string methods, document the expected input or check it. Convert only when conversion is appropriate:
function showValue(value) {
return String(value);
}
showValue(42); // '42'
String(value) explicitly converts many values to strings, while value.toString() requires the value to have that method and can fail for null or undefined. Conversion is not a substitute for validation: converting an unexpected object may produce text that is technically valid but not useful for the function’s purpose.
Return a String or Use a Default
Passing a string into a function and getting a string back are separate parts of a function’s behavior. A function only gives a result to its caller when it returns one. Without a return statement, the result of the call is undefined, even if the function logs text or modifies a local parameter.
You can provide a default parameter for calls that omit an argument or pass undefined:
function greet(name = 'there') {
return `Hello, ${name}!`;
}
console.log(greet()); // Hello, there!
console.log(greet('Maya')); // Hello, Maya!
A default parameter does not apply to every falsy value. For example, an empty string is an actual argument, so greet('') uses the empty string. If blank input should also trigger a fallback, check for it explicitly, perhaps after trimming whitespace. Decide whether blank text is valid for the task rather than assuming that missing, blank, and invalid input mean the same thing.
Strings in Callbacks and Asynchronous Code
A string can be passed to a function that accepts a callback, just as it can be passed to any other function. The callback receives its own arguments according to the API that invokes it. For example, an event handler can close over a string variable:
const label = 'Save';
button.addEventListener('click', function () {
console.log(label);
});
This example assumes button is a reference to a DOM element. The string is not passed as an argument to addEventListener; instead, the callback reads label from its surrounding scope when the event occurs. To pass data as a callback argument, use an API that supplies or accepts such arguments, or create a function that calls your function with the value.
The same idea applies to promises and timers. A function can receive a string now and use it later in a callback, but the string remains a value; waiting does not make it mutable or change the argument-passing rule. Be attentive to when a callback runs and which variable it reads, especially if that variable can later be reassigned.
Common Problems and How to Fix Them
- Text is not quoted:
send(hello)looks for a variable namedhello. Usesend('hello')for literal text. - The function expects a different parameter order: Check the definition and pass arguments in that order. For functions with many related options, an object parameter can be clearer.
- A method call appears to do nothing: Many string methods return a new string. Store or return the result instead of expecting the original value to change.
- The result is
undefined: Check that the function returns a value and that every relevant branch reaches areturn. - An unexpected type arrives: Check the call site and, where appropriate, validate with
typeof value === 'string'before using string-specific behavior.
For an API that takes several optional settings, you may choose an object rather than a long list of positional arguments. For example, a function could accept { name: 'Maya', greeting: 'Welcome' } and read the properties it needs. That does not change how strings work; it changes the shape of the argument and can make call sites easier to read when options are numerous.
Frequently Asked Questions
How do I pass a string variable to a JavaScript function?
Pass the variable name as the argument, without adding quotes around it: greet(name). The variable must already be in scope and contain the value you intend to pass.
Can a function change the original string?
No. Strings are immutable primitive values. A function can create and return a different string, but it cannot change the characters in the caller’s string in place.
Do I need to use quotes when passing a string?
Use quotes when writing a literal, such as greet('Maya'). Do not put quotes around a variable name, because that would pass the variable name as literal text rather than pass the variable’s value.
How do I pass a string with spaces or punctuation?
Put the literal inside matching quotes, for example search('red apples, ripe'). If the text contains the chosen quote character, escape it or use the other quote style; template literals are another option.
How can I pass a number as a string?
Convert it explicitly with String(number) when text is what the function needs, then pass the result. For example, showValue(String(42)) passes the string '42', not the number 42.
Related
- Bullseye Graphic in PowerPoint: Make One Cleanly
- Access Split Form: Put the Datasheet on the Bottom
- Balance of Payments: How It Works and What It Shows
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- INDIRECT in Excel: How to Drag Formulas to New CellsIf you want an INDIRECT formula to follow different cells as you drag it, build its address from…
- Count Unique Numbers in Excel: Formulas and MethodsTo count distinct numeric values in a range in Microsoft 365 or Excel 2021, use =IFERROR(ROWS(UNIQUE(FILTER(A2:A100,ISNUMBER(A2:A100)))),0), assuming the…
- Excel VLOOKUP Multiple Values: Formulas That WorkTo return every matching row for one lookup value in Microsoft 365, use FILTER rather than VLOOKUP. With…
- Excel Filters: How to Sort and Show the Rows You NeedTo filter data in Excel for Microsoft 365 on Windows, select a cell in your data, choose Data…
- Python String Length: How len() Counts Characters in PythonUse Python’s built-in len() function to get a string’s length: len('hello') returns 5. It counts Unicode code points…
- MS Access Split Function: Syntax and ExamplesYes. Microsoft Access’s VBA Split function divides a string into a zero-based array of smaller strings wherever it…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.