JavaScript syntax: Difference between revisions

Content deleted Content added
Function: better examples
Line 740:
// x, y is the argument. 'return x + y' is the function body, which is the last in the argument list.
var add = new Function('x', 'y', 'return x + y');
var t = add(1, 2); // => 3
console.log(t); // 3
</syntaxhighlight>
 
Line 750 ⟶ 749:
return x + y;
};
var t = add(1, 2); // => 3
console.log(t); // 3
</syntaxhighlight>
 
In ES6, arrow function syntax was added, allowing functions that return a value to be more concise. They also retain the <tt>this</tt> of the global object instead of inheriting it from where it was called / what it was called on, unlike the <tt>function() {}</tt> expression.
There exists a shorthand for assigning a function expression to a variable, and is as follows:
 
<syntaxhighlight lang="javascript">
var add = ((x, y) => {return x + y);};
// values can also be implicitly returned (i.e. no return statement is needed)
var addImplicit = (x, y) => x + y;
 
add(1, 2); // => 3
addImplicit(1, 2) // => 3
</syntaxhighlight>
 
For functions that need to be hoisted, there is a separate expression:
 
<syntaxhighlight lang="javascript">
Line 760 ⟶ 769:
return x + y;
}
var t = add(1, 2); // => 3
console.log(t); // 3
</syntaxhighlight>
 
Hoisting allows you to use the function before it is "declared":
Or
 
<syntaxhighlight lang="javascript">
var add = ((x1, y2); // => {3, not a ReferenceError
function add(x, y) {
return x + y;
});
// or
var add = ((x, y) => x + y);
 
var t = add(1, 2);
console.log(t); // 3
</syntaxhighlight>
 
A function instance has properties and methods.
 
Line 782 ⟶ 788:
}
 
console.log(subtract.length); // => 2, expectedarity of the function amount(number of arguments.)
console.log(subtract.toString());
 
Line 791 ⟶ 797:
*/
</syntaxhighlight>
 
New functions can be
 
==Operators==