unthodox
unthodox

Reputation: 23

Variable scope related. Calling a variable in a function from a different fuction - unexpected behaviour/results

I am learning javascript and I tumbled upon this behaviour where it would not execute the function f2() at the end of the code.

function f1() {
  var oneT = 55;
  console.log(oneT);
}
f1();
console.log(typeof(oneT));

function f2() {
  if (typeof(oneT) == undefined) {
    console.log("oneT can't be read outside the f1() as it's scope is limited to the fn f1().");
  }
}
f2();

If the undefined is not put in " ", then the f2() at the end is skipped (overlooked?). If put in " ", then it executes the f2(). Can someone explain to me the possible reason for this behaviour? Thank you in advance!

Upvotes: 1

Views: 33

Answers (2)

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

You are seeing that because the typeof operator is returning you the value "undefined" as a string.

From the MDN docs:

The typeof operator returns a string indicating the type of the unevaluated operand.

You can do a typeof() on top of typeof(typeof(oneT)) to check that it is indeed returning you a string.

The f2() is getting called but you don't see any output as the if block is skipped entirely, because you are comparing a string "undefined" returned from the typeof(oneT) with the undefined value:

function f1() {
  var oneT = 55; //function scope
  console.log(oneT);
}

f1();
console.log(typeof(typeof(oneT))); //string

function f2() {
  if (typeof(oneT) == undefined) { //false and if is skipped
     console.log("oneT can't be read outside the f1() as it's scope is limited to the fn f1().");
  }
  console.log("Inside f2"); //prints this
}

f2();

function f3() {
  if (typeof(oneT) === "undefined") { //true
     console.log("oneT can't be read outside the f1() as it's scope is limited to the fn f1().");
  }
}
f3();

Upvotes: 1

Jan Turoň
Jan Turoň

Reputation: 32912

f2() is executed every time, just the condition inside is not met. == undefined evaluates true if on the left side is a falsy value (0, empty string, null, false, undefined). typeof returns string "undefined" which is not empty string.

Upvotes: 0

Related Questions