Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying a Function to Null in Javascript

Why does the following work:

function sum(a,b) { return a + b; }
var result = sum.call(null,3,4);     // 7

Why is result defined? I am invoking sum as a method of null. But null is not an object and cannot have properties!

What is going on?

like image 945
Fawkes5 Avatar asked Jul 25 '12 21:07

Fawkes5


People also ask

Can a function be null JavaScript?

JavaScript uses the null value to represent the intentional absence of any object value. If you find a variable or a function that returns null , it means that the expected object couldn't be created.

How do you give a value to null in JavaScript?

In JavaScript, null is a special value that represents an empty or unknown value. For example, let number = null; The code above suggests that the number variable is empty at the moment and may have a value later.

What does apply () do in JavaScript?

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

IS null == null in JavaScript?

null is a special value in JavaScript that represents a missing object. The strict equality operator determines whether a variable is null: variable === null . typoef operator is useful to determine the type of a variable (number, string, boolean).


1 Answers

The first argument for Function.prototype.call is the context, which defines the this value for the execution context of the invoked function, nothing else.

So basically, you're saying that this is referring to null (at least, in ES5 strict mode), but since you don't access this anyway, it makes no difference.

In non-strict mode, this cannot be null, so it's replaced with the global object instead.

like image 148
jAndy Avatar answered Oct 04 '22 00:10

jAndy