Uncaught SyntaxError: Unexpected token else?????????????????

function ifThing(word) {

var word = 'foo';

if(word === 'foo'); {

console.log("It's foo!");

} else {

console.log("No.");

}

}

ifThing(foo);

3 Answers

Relevance
  • Chris
    Lv 7
    6 months ago

    1. remove the semi-colon after the if

    2. function ifThing(word) {

    will declare a variable called word and store the argument of the function call inside. In other words, redeclaring "var word" is not required.

    3. your code checks against 'foo', which is text. However when you call your function at the end, you're passing a variable without content. You probably meant to write

    ifThing("foo");

    https://jsfiddle.net/khrismuc/uavpbj14/

  • 6 months ago

    All you need to do is get rid of the semicolon (;) in the line:

    > if (word === 'foo'); {

    That will fix the syntax. Unfortunately, the logic has a flaw, too. Remove the "var word='foo';" statement. It simply overwrites whatever was passed as an argument with the string 'foo'. The === operator will take care of undefined and null arguments, comparing false because === requires an exact type match.

    I missed the other error, that foo in "ifThing(foo);" is undefined--or appears to be. If the name hasn't been declared, you'll get an error that'll stop your script without even calling ifThing(). Nothing you put in your function can help that. The function never gets called.

    The type of "not defined" that the function can actually handle is the case where you have introduced the name without giving it a value:

    var foo;

    ifThing(foo);

    That will pass an object of type 'undefined' and === will return false when comparing that to a string.

  • Anonymous
    6 months ago

    this is a classic complete misunderstanding of how javascript works...

    var does NOT check if "word" exists and then creates an object if there is none; it only tells javascript that all instances of "word" is an object. There is no viable way to do what you really want to do because the SCOPE changes when you call a function, you MUST use typeof foo = "undefined" in the same scope, and if foo was never declared to begin with OOPS ERROR!

    Your error is " if(word === 'foo'); { "

    Semicolon

    And if foo was never declared before you call the function, you STILL get an error... just don't write bad code that uses undefined/undeclared variables and tries to fix them if undefined/undeclared. It's EXTREMELY bad practice that people who don't understand how javascript works have insisted you should do.

Still have questions? Get your answers by asking now.