Need clarification as to why code is correct

Viewed 68
const isString = (a, b, c) => {
  if (((typeof a) == "string") && ((typeof b) == "string") && ((typeof c) == "string")) {
    return "strings";
  }
  return "not strings";
}

Why is the => after the argument required in order for this to work? I got this test question correct via trial and error, but I don't understand why it doesn't work without =>.

Here are the instructions.

Create a function called "isString" that takes 3 arguments (x1, x2, x3)

  • Check if each argument is a string using typeof.
  • If each argument is a string, return "strings".
  • If each argument is NOT a string, return "not strings".
4 Answers

The => is the syntax for an arrow function

Assuming that this is , the => is indicating that it is part of an Arrow Function. The following two codes are equivalent as for the understanding of the two.

// function declaration
function isString (a, b, c) {
  if (((typeof a) == "string") && ((typeof b) == "string") && ((typeof c) == "string")) {
    return "strings";
  }
  return "not strings";
}
// arrow function declaration; can also use `var` instead of `const`
const isString = (a, b, c) => {
  if (((typeof a) == "string") && ((typeof b) == "string") && ((typeof c) == "string")) {
    return "strings";
  }
  return "not strings";
};

This looks like Javascript. There are a few ways to declare a function in Javascript. One, is as you have done it

const myFunc = (params) => {
    // code
}

This is treating myFunc like any other name in Javascript needing to be assigned a value. Another more traditional way is:

function myFunc(params) {
    // code
}

Note that because you have the = after isString, the Javascript engine is expecting you to define it as in the first example.

Related