There will be no error because of “excessive” arguments when calling the function.
function totalOf(…nums) { // nums is the name for the array
let sum = 0;
for (let num of nums) sum += num;
return sum;
}
alert( totalOf(1) ); // 1
alert( totalOf(1, 2) ); // 3
alert( totalOf(1, 2, 3) ); // 6
The rest parameters must be at the end.
2. The “arguments” variable
There is also a special array-like object named arguments that contains all arguments by their index.
For instance:
function showName() {
alert( arguments.length );
alert( arguments[0] );
alert( arguments[1] );
}
// shows: 2, John, Bob
showName(“John”, “Bob”);
// shows: 1, Ilya, undefined (no second argument)
showName(“Ilya”);
The “name” property:
function hello() {
alert(“Hi”);
}
alert(hello.name); // hello
The “length” property:
There is another built-in property “length” that returns the number of function parameters.
function f1(a) {}
function f2(a, b) {}
function many(a, b, …more) {}
alert(f1.length); // 1
alert(f2.length); // 2
alert(many.length); // 2. The Rest Parameters is not considered
Custom properties
We can also add properties of our own.
setTimeout allows us to run a function once after the interval of time.
Syntax:
setTimeout(func|code, [delay], [arg1], [arg2], …)
Canceling with clearTimeout
A call to setTimeout returns a “timer identifier” timerId that we can use to cancel the execution.
The syntax to cancel:
let timerId = setTimeout(…);
clearTimeout(timerId);
setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.
Syntax:
setInterval(func|code, [delay], [arg1], [arg2], …)
In JavaScript, objects have a special hidden property [[Prototype]] (as named in the specification), that is either null or references another object. That object is called “a prototype.
__proto__ is a historical getter/setter for [[Prototype]].
Example:
let athlete = {
eats: true,
run() {
alert(“athlete run”);
}
};
let highjumper = {
jumps: true,
__proto__: athlete
};
// run is taken from the prototype
highjumper.run(); // athlete run
// Object.keys only returns own keys
alert(Object.keys( highjumper )); // jumps
// for..in loops over both own and inherited keys
for(let prop in highjumper ) alert(prop); // jumps, then eats
Async and Await are extensions of promises.
Using async simply implies that a promise will be returned, and if a promise is not returned, JavaScript automatically wraps it in a resolved promise with its value.
async function firstAsync() {
return 1;
}
firstAsync().then(alert); // 1
Running the above code gives the alert output as 1, it means that a promise was returned, otherwise the .then() method simply would not be possible.
The await operator is used to wait for a Promise. It can be used inside an Async block only.
Syntax:
let func = new Function ([arg1, arg2, …argN], functionBody);
Example:
let sum = new Function( ‘x’, ‘y’, ‘return x + y’ );
When a function is created using a new Function, its [[Environment]] is set to reference not the current Lexical Environment, but the global one.
So, such a function doesn’t have access to outer variables, only to the global ones.
var p = 9;
function temp() {
var p = 5;
alert( p );
let func = new Function( ‘return p;’ );
alert( func() );
}
temp();//Alerts 5 then 9 since new Function reference global
arr[ 1 ] ++;
arr = arr + arr;
return arr;
}
a = new Array( 1, 3, 2, 5 );
var b = myAdder( a );
console.log( b );
1. 1, 4, 2, 5, 1, 4, 2, 5
2. 1, 4, 2, 51, 4, 2, 5
3. undefined
4. error
Answer: 2
The addition operator either performs string concatenation or numeric addition.
So, ‘1, 4, 2, 5’ + ‘1, 4, 2, 5’ is ‘1, 4, 2, 51, 4, 2, 5’
JavaScript is single-threaded. Asynchronous callbacks are assigned to a message placed in a message queue.
A new message is added to the queue immediately, and will be processed when the currently executing code is finished and any previously-added messages have been processed.
The typeof operator returns a string indicating the type of the unevaluated operand.
console.log( typeof ‘str’ );
console.log( typeof 123 );
console.log( typeof undefined );
console.log( typeof typeof undefined );
console.log( typeof new Array() );
console.log( typeof new String() );
> “string”
> “number”
> “undefined”
> “string”
> “object”
> “object”
The padStart() amd padEnd() methods pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length.
let str = ‘ab’;
console.log( str.padStart( ‘3’, ‘i’ ) );
console.log( str.padEnd( ‘3’, ‘i’ ) );
Output:
iab
abi
The reduce() method reduces the array to a single value.
The reduce() method executes a provided function for each value of the array (from left-to-right).
The return value of the function is stored in an accumulator (result/total).
Syntax
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
function subVal(total, num) {
return total – num;
}
var numbers = [175, 50, 25];
console.log( numbers.reduce( subVal ) );//100 since 175 is initial value. So, 175 – 50 – 25
console.log( numbers.reduce( subVal, 300 ) );//50 since 300 is initial value. So, 300 – 175 – 50 – 25