1

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!

3
  • 1
    typeof returns a string ... "undefined" != undefined Commented Sep 12, 2019 at 6:44
  • The if is not fulfilled no matter whether you test == undefined or == " " (if that's what you mean), because the typeof something is always a string Commented Sep 12, 2019 at 6:44
  • Thank you. I understood now. Commented Sep 12, 2019 at 9:18

2 Answers 2

1

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();

Sign up to request clarification or add additional context in comments.

1 Comment

You cleared all the confusion for me. I should've referred the MDN docs on JS earlier on the "typeof" subject. Thank you!
0

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.

1 Comment

Thank you for correcting me on the part of f2() being executed. That helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.