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