They are two different things, although they both create a function (and assign it to a variable).

function name () {
}

Is a function-statement (or "function declaration"). It is only legal to appear as a top-level script element or directly as an element of a function: that is, it is not legal for a function-statement to appear inside an if, or while, etc. All function statements are "lifted" to the top of the function (or script), thus the following is valid:

a()
function a () { alert("a") }

In the form:

variable = function name () {} // or variable = function () {}

The function keyword is in a function-expression context: it creates a new function-object and the resulting function-object (just a "normal value") is assigned to variable. The following is not valid because function-expressions are not lifted.

var b
b() // oops, does not evaluate to a function-object yet!
b = function b () { alert("b") }

All that being said, the "correct way" is to use the function-statement ("function declaration") form unless there is reason to do otherwise.

Happy coding.


See also:

  • What is the difference between a function expression vs declaration in JavaScript?
  • Function Declarations vs. Function Expressions
Answer from user166390 on Stack Overflow
🌐
Math.js
mathjs.org › docs › reference › functions › format.html
mathjs format function
For example format(fraction(1, 3)) will output '1/3' when 'ratio' is configured, and will output '0.(3)' when 'decimal' is configured. truncate: number. Specifies the maximum allowed length of the returned string. If it had been longer, the excess characters are deleted and replaced with '...'. callback: function A custom formatting function, invoked for all numeric elements in value, for example all elements of a matrix, or the real and imaginary parts of a complex number.
Top answer
1 of 3
12

They are two different things, although they both create a function (and assign it to a variable).

function name () {
}

Is a function-statement (or "function declaration"). It is only legal to appear as a top-level script element or directly as an element of a function: that is, it is not legal for a function-statement to appear inside an if, or while, etc. All function statements are "lifted" to the top of the function (or script), thus the following is valid:

a()
function a () { alert("a") }

In the form:

variable = function name () {} // or variable = function () {}

The function keyword is in a function-expression context: it creates a new function-object and the resulting function-object (just a "normal value") is assigned to variable. The following is not valid because function-expressions are not lifted.

var b
b() // oops, does not evaluate to a function-object yet!
b = function b () { alert("b") }

All that being said, the "correct way" is to use the function-statement ("function declaration") form unless there is reason to do otherwise.

Happy coding.


See also:

  • What is the difference between a function expression vs declaration in JavaScript?
  • Function Declarations vs. Function Expressions
2 of 3
3

There is an important and also useful difference between those syntaxes.

Encapsulation

In OOP it is very useful to use encapsulation, which is a mechanism for restricting access to other objects. The difference between public and private vars/functions in javascript could stated like this:

function Color(value)
{
    // public variable
    this.value = value; // get from arguments

    // private variable
    var _name = "test";

   // public function
   this.getRandomColor = function( )
   {
     return Math.random() * 0xFFFFFF;
   }

   // private function
   function getNiceColor()
   {
     return 0xffcc00;
   }
}

Testing public

The public variables and functions inside the a color-instance are accessible:

// create instance of Color
var color = new Color(0xFF0000);
alert( color.value ); // returns red color
alert( color.getRandomColor() ); // returns random color

Testing privates

Private variables and functions cannot be accessed from the color-instance:

var color = new Color(0x0000FF); 
alert( color.getNiceColor() ); // error in console; property does not exist, because function is private.
alert( color._name ); // error in console; property does not exist, because variable is private.

NOTE
It could be better to use good-old prototypes when using public functions, because this method of coding could cause problems with inheritence.

Top answer
1 of 16
1662

Current JavaScript

From ES6 on you could use template strings:

let soMany = 10;
console.log(`This is ${soMany} times easier!`);
// "This is 10 times easier!"

See Kim's answer below for details.


Older answer

Try sprintf() for JavaScript.


If you really want to do a simple format method on your own, don’t do the replacements successively but do them simultaneously.

Because most of the other proposals that are mentioned fail when a replace string of previous replacement does also contain a format sequence like this:

"{0}{1}".format("{1}", "{0}")

Normally you would expect the output to be {1}{0} but the actual output is {1}{1}. So do a simultaneous replacement instead like in fearphage’s suggestion.

2 of 16
1512

Building on the previously suggested solutions:

// First, checks if it isn't implemented yet.
if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}

"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")

outputs

ASP is dead, but ASP.NET is alive! ASP {2}


If you prefer not to modify String's prototype:

if (!String.format) {
  String.format = function(format) {
    var args = Array.prototype.slice.call(arguments, 1);
    return format.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number] 
        : match
      ;
    });
  };
}

Gives you the much more familiar:

String.format('{0} is dead, but {1} is alive! {0} {2}', 'ASP', 'ASP.NET');

with the same result:

ASP is dead, but ASP.NET is alive! ASP {2}

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Intl › NumberFormat
Intl.NumberFormat - JavaScript | MDN
Getter function that formats a range of numbers according to the locale and formatting options of the Intl.NumberFormat object from which the method is called.
🌐
Coderwall
coderwall.com › p › flonoa › simple-string-format-in-javascript
Simple String.format() in javascript (Example)
March 21, 2023 - function format(fmt, ...args) { if (!fmt.match(/^(?:(?:(?:[^{}]|(?:\{\{)|(?:\}\}))+)|(?:\{[0-9]+\}))+$/)) { throw new Error('invalid format string.'); } return fmt.replace(/((?:[^{}]|(?:\{\{)|(?:\}\}))+)|(?:\{([0-9]+)\})/g, (m, str, index) => { if (str) { return str.replace(/(?:{{)|(?:}})/g, m => m[0]); } else { if (index >= args.length) { throw new Error('argument index is out of range in format'); } return args[index]; } }); } function print(fmt, ...args) { console.log(format(fmt, ...args)); } print("Hello, {0}! The answer is {1}.", "World", 42); print("{0} {1}", "{1}", 42); print("{{0}} will be replaced with {0}", 42); print("{0}} woops, throw!")
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Functions
Functions - JavaScript | MDN
The function expects the num parameter to be a number — although this is not enforceable in JavaScript without writing runtime validation code. In the formatNumber(2) call, the number 2 is the function's argument: it's the value that is actually passed to the function in the function call.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-string-formatting
JavaScript String Formatting - GeeksforGeeks
August 5, 2025 - JavaScript string formatting refers ... be done using methods like concatenation, template literals (backticks), and custom formatting functions, which help create flexible and clean string outputs in your code....
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Intl › NumberFormat › format
Intl.NumberFormat.prototype.format() - JavaScript | MDN
The format() method of Intl.NumberFormat instances formats a number according to the locale and formatting options of this Intl.NumberFormat object.
🌐
Guru99
guru99.com › home › javascript › javascript string format: methods with examples
JavaScript String Format: Methods with EXAMPLES
July 28, 2025 - Here, we have created a custom format function named “welcomeMsg()” that accepts two variables “name” and “id” as arguments and outputs formatted strings by utilizing the template string literals.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Template_literals
Template literals (Template strings) - JavaScript | MDN
Template literals are sometimes informally called template strings, because they are used most commonly for string interpolation (to create strings by doing substitution of placeholders). However, a tagged template literal may not result in a string; it can be used with a custom tag function to perform whatever operations you want on the different parts of the template literal.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Intl › DateTimeFormat › format
Intl.DateTimeFormat.prototype.format() - JavaScript | MDN
Note that the function is bound to the Intl.DateTimeFormat from which it was obtained, so it can be passed directly to Array.prototype.map(). ... const a = [new Date(2012, 8), new Date(2012, 11), new Date(2012, 3)]; const options = { year: "numeric", month: "long" }; const dateTimeFormat = new Intl.DateTimeFormat("pt-BR", options); const formatted = a.map(dateTimeFormat.format); console.log(formatted.join("; ")); // "setembro de 2012; dezembro de 2012; abril de 2012"
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Text_formatting
Numbers and strings - JavaScript | MDN
We will introduce their underlying representations, and functions used to work with and perform calculations on them. In JavaScript, numbers are implemented in double-precision 64-bit binary format IEEE 754 (i.e., a number between ±2^−1022 and ±2^+1023, or about ±10^−308 to ±10^+308, ...
🌐
Numeraljs
numeraljs.com
Numeral.js
' ' : '', output; value = value * 100; // check for space before % format = format.replace(/\s?\%/, ''); output = numeral._.numberToFormat(value, format, roundingFunction); if (numeral._.includes(output, ')')) { output = output.split(''); output.splice(-1, 0, space + '%'); output = output.join(''); } else { output = output + space + '%'; } return output; }, unformat: function(string) { return numeral._.stringToNumber(string) * 0.01; } }); // use your custom format numeral().format('0%');
🌐
CoreUI
coreui.io › blog › what-is-javascript-printf-equivalent
JavaScript printf equivalent · CoreUI
June 22, 2024 - You can define custom string formatting functions using the String.prototype.format method in JavaScript. This method returns formatted strings based on placeholders within the string.
🌐
Beautifier
beautifier.io
Online JavaScript beautifier
Sublime Text 2: JsFormat, a javascript formatting plugin for this nice editor by Davis Clark,
🌐
Day.js
day.js.org › docs › en › display › format
Format · Day.js
dayjs().format() // current date in ISO8601, without fraction seconds e.g.
🌐
Flexiple
flexiple.com › javascript › string-format
JavaScript String Format – Formatting Strings in JS - Flexiple
JavaScript string formatting involves manipulating and presenting text in various ways. Developers use string formatting in JavaScript to integrate variables and constants into strings dynamically, making code more readable and maintainable.
Top answer
1 of 16
74

Adapt the code from MsAjax string.

Just remove all of the _validateParams code and you are most of the way to a full fledged .NET string class in JavaScript.

Okay, I liberated the msajax string class, removing all the msajax dependencies. It Works great, just like the .NET string class, including trim functions, endsWith/startsWith, etc.

P.S. - I left all of the Visual Studio JavaScript IntelliSense helpers and XmlDocs in place. They are innocuous if you don't use Visual Studio, but you can remove them if you like.

<script src="script/string.js" type="text/javascript"></script>
<script type="text/javascript">
    var a = String.format("Hello {0}!", "world");
    alert(a);

</script>

String.js

// String.js - liberated from MicrosoftAjax.js on 03/28/10 by Sky Sanders
// permalink: http://stackoverflow.com/a/2534834/2343

/*
    Copyright (c) 2009, CodePlex Foundation
    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, are permitted
    provided that the following conditions are met:

    *   Redistributions of source code must retain the above copyright notice, this list of conditions
        and the following disclaimer.

    *   Redistributions in binary form must reproduce the above copyright notice, this list of conditions
        and the following disclaimer in the documentation and/or other materials provided with the distribution.

    *   Neither the name of CodePlex Foundation nor the names of its contributors may be used to endorse or
        promote products derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED
    WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
    FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
    IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</textarea>
*/

(function(window) {

    $type = String;
    $type.__typeName = 'String';
    $type.__class = true;

    $prototype = $type.prototype;
    $prototype.endsWith = function String$endsWith(suffix) {
        /// <summary>Determines whether the end of this instance matches the specified string.</summary>
        /// <param name="suffix" type="String">A string to compare to.</param>
        /// <returns type="Boolean">true if suffix matches the end of this instance; otherwise, false.</returns>
        return (this.substr(this.length - suffix.length) === suffix);
    }

    $prototype.startsWith = function String$startsWith(prefix) {
        /// <summary >Determines whether the beginning of this instance matches the specified string.</summary>
        /// <param name="prefix" type="String">The String to compare.</param>
        /// <returns type="Boolean">true if prefix matches the beginning of this string; otherwise, false.</returns>
        return (this.substr(0, prefix.length) === prefix);
    }

    $prototype.trim = function String$trim() {
        /// <summary >Removes all leading and trailing white-space characters from the current String object.</summary>
        /// <returns type="String">The string that remains after all white-space characters are removed from the start and end of the current String object.</returns>
        return this.replace(/^\s+|\s+$/g, '');
    }

    $prototype.trimEnd = function String$trimEnd() {
        /// <summary >Removes all trailing white spaces from the current String object.</summary>
        /// <returns type="String">The string that remains after all white-space characters are removed from the end of the current String object.</returns>
        return this.replace(/\s+$/, '');
    }

    $prototype.trimStart = function String$trimStart() {
        /// <summary >Removes all leading white spaces from the current String object.</summary>
        /// <returns type="String">The string that remains after all white-space characters are removed from the start of the current String object.</returns>
        return this.replace(/^\s+/, '');
    }

    $type.format = function String$format(format, args) {
        /// <summary>Replaces the format items in a specified String with the text equivalents of the values of   corresponding object instances. The invariant culture will be used to format dates and numbers.</summary>
        /// <param name="format" type="String">A format string.</param>
        /// <param name="args" parameterArray="true" mayBeNull="true">The objects to format.</param>
        /// <returns type="String">A copy of format in which the format items have been replaced by the   string equivalent of the corresponding instances of object arguments.</returns>
        return String._toFormattedString(false, arguments);
    }

    $type._toFormattedString = function String$_toFormattedString(useLocale, args) {
        var result = '';
        var format = args[0];

        for (var i = 0; ; ) {
            // Find the next opening or closing brace
            var open = format.indexOf('{', i);
            var close = format.indexOf('}', i);
            if ((open < 0) && (close < 0)) {
                // Not found: copy the end of the string and break
                result += format.slice(i);
                break;
            }
            if ((close > 0) && ((close < open) || (open < 0))) {

                if (format.charAt(close + 1) !== '}') {
                    throw new Error('format stringFormatBraceMismatch');
                }

                result += format.slice(i, close + 1);
                i = close + 2;
                continue;
            }

            // Copy the string before the brace
            result += format.slice(i, open);
            i = open + 1;

            // Check for double braces (which display as one and are not arguments)
            if (format.charAt(i) === '{') {
                result += '{';
                i++;
                continue;
            }

            if (close < 0) throw new Error('format stringFormatBraceMismatch');


            // Find the closing brace

            // Get the string between the braces, and split it around the ':' (if any)
            var brace = format.substring(i, close);
            var colonIndex = brace.indexOf(':');
            var argNumber = parseInt((colonIndex < 0) ? brace : brace.substring(0, colonIndex), 10) + 1;

            if (isNaN(argNumber)) throw new Error('format stringFormatInvalid');

            var argFormat = (colonIndex < 0) ? '' : brace.substring(colonIndex + 1);

            var arg = args[argNumber];
            if (typeof (arg) === "undefined" || arg === null) {
                arg = '';
            }

            // If it has a toFormattedString method, call it.  Otherwise, call toString()
            if (arg.toFormattedString) {
                result += arg.toFormattedString(argFormat);
            }
            else if (useLocale && arg.localeFormat) {
                result += arg.localeFormat(argFormat);
            }
            else if (arg.format) {
                result += arg.format(argFormat);
            }
            else
                result += arg.toString();

            i = close + 1;
        }

        return result;
    }

})(window);
2 of 16
45

Here is what I use. I have this function defined in a utility file:

  String.format = function() {
      var s = arguments[0];
      for (var i = 0; i < arguments.length - 1; i++) {       
          var reg = new RegExp("\\{" + i + "\\}", "gm");             
          s = s.replace(reg, arguments[i + 1]);
      }
      return s;
  }

And I call it like so:

var greeting = String.format("Hi, {0}", name);

I do not recall where I found this, but it has been very useful to me. I like it because the syntax is the same as the C# version.

🌐
Format.JS
formatjs.github.io
Format.JS
A modular collection of JavaScript libraries focused on formatting numbers, dates, and strings.