Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you pass 'null' to 'apply' or 'call'?

Tags:

javascript

According to this JavaScript reference:

The value null is a JavaScript literal representing null or an "empty" value, i.e. no object value is present. It is one of JavaScript's primitive values.

function getMax(arr){
  return Math.max.apply(null, arr);  
}

Wouldn't explicitly passing the keyword this be clearer, or at least more readable? Then again, at this point I may not understand why you would use null.

like image 239
Antonio Pavicevac-Ortiz Avatar asked Nov 10 '15 21:11

Antonio Pavicevac-Ortiz


People also ask

Is it good to pass null?

As with most method calls, it's good practice to avoid passing a null reference, which will likely result in a NullPointerException at runtime.

What is null used for?

A null value in a relational database is used when the value in a column is unknown or missing. A null is neither an empty string (for character or datetime data types) nor a zero value (for numeric data types).

How do you pass a null argument?

You can pass NULL as a function parameter only if the specific parameter is a pointer. The only practical way is with a pointer for a parameter. However, you can also use a void type for parameters, and then check for null, if not check and cast into ordinary or required type.

Why do we use null in JavaScript?

The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.


1 Answers

Calling apply with null as the first argument is like calling the function without providing any object for the this.

What does the apply method do?

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

fun.apply(thisArg, [argsArray])

thisArg

The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.

Further documentation can be found here.

like image 103
Christos Avatar answered Oct 13 '22 17:10

Christos