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
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.

🌐
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.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Intl › NumberFormat
Intl.NumberFormat - JavaScript | MDN - Mozilla
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.
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}

🌐
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!")
🌐
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....
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Functions
Functions - JavaScript | MDN - Mozilla
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.
Find elsewhere
🌐
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 › Global_Objects › Intl › NumberFormat › format
Intl.NumberFormat.prototype.format() - JavaScript | MDN
July 10, 2025 - The format() method of Intl.NumberFormat instances formats a number according to the locale and formatting options of this Intl.NumberFormat object.
🌐
Scaler
scaler.com › home › topics › what is javascript string format?
What is JavaScript string format? - Scaler Topics
June 27, 2024 - The format method accepts a list of parameters and replaces the placeholders in the strings with the parameters i.e. the value of the placeholders/ variables. The placeholders are the integer values starting from 0 (first placeholder) till n ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Intl › DateTimeFormat › format
Intl.DateTimeFormat.prototype.format() - JavaScript | MDN
July 20, 2025 - 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"
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Template_literals
Template literals (Template strings) - JavaScript - MDN - Mozilla
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.
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Text_formatting
Text formatting - JavaScript - MDN Web Docs - Mozilla
November 15, 2024 - 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, ...
🌐
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.
🌐
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%');
🌐
W3Schools
w3schools.com › js › js_functions.asp
JavaScript Function Study Path
Function Study Path Function Intro Function Invocation Function Parameters Function Returns Function Arguments Function Expressions Function Arrow Function Quiz JS Objects · Object Study Path Object Intro Object Properties Object Methods Object this Object Display Object Constructors JS Scope · JS Scope JS Code Blocks JS Hoisting JS Strict Mode JS Dates · JS Dates JS Date Formats JS Date Get JS Date Set JS Date Methods JS Temporal New
🌐
Day.js
day.js.org › docs › en › display › format
Format · Day.js
dayjs().format() // current date in ISO8601, without fraction seconds e.g.
🌐
Beautifier
beautifier.io
Online JavaScript beautifier
Sublime Text 2: JsFormat, a javascript formatting plugin for this nice editor by Davis Clark,
🌐
Format.JS
formatjs.github.io
Format.JS
A modular collection of JavaScript libraries focused on formatting numbers, dates, and strings.