CY_
CY_

Reputation: 7618

Two Confusing Javascript Quiz

Just feel quit confused about some quiz.

Quiz One

var x = 1;
  if (function f(){}) {
    x += typeof f;
  }
  alert(x);

Answer:

The answer for x is "1undefined"

Confusion:

What really happened to "function f(){}" in if condition?

Quiz Two

(function(x){
    delete x;
    return x;
  })(1);

Answer:

The output is 1.

Confusion:

Why delete is not working? When does 'delete' work and when doesn't?

Upvotes: -1

Views: 816

Answers (3)

BryanGrezeszak
BryanGrezeszak

Reputation: 577

The point of confusion on #1 is that the function is being made as a function expression. The function is real (so it passes the if statement as truthy) but it's not a function statement, so no external f reference is created for it.

It's the same concept as when you assign a function to a variable: you're making a function expression.

var g = function(){};

Naming the function expression doesn't actually change that:

var g = function f(){};
// it would still only be externally accessible as g, not f

It would only be accessible as f from inside the function:

var g = function f(){ alert(f); };
g(); // will call the function, and from inside f will work

To make f as a function statement (instead of expression) it would have to be defined on its own within its current scope, like so:

function f() {}
// now we can reference it as f externally as a statement!

even just one character in the way and it becomes an expression instead...

!function f() {}
// now we can't :(

For #2, quite simply: delete is for object properties. Such as:

var obj = {};
obj.foo = 'bar';
delete obj.foo;
alert(obj.hasOwnProperty('foo')); // <- false

Upvotes: 3

Alden Be
Alden Be

Reputation: 517

f is not equivalent to f() you are using typeof on an undefined variable, which returns the string undefined, which you append to x.

As the previous answer stated. Delete removes object properties, it does not clear or destroy variables.

Upvotes: 0

Washington Guedes
Washington Guedes

Reputation: 4365

As any function is true you just joined a number 1 with a string 'undefined'. And in the second, delete only works with object-properties.

Upvotes: 4

Related Questions