Javascript Developer JSE 40 01 · Free Practice Question Easy
Question 24
Q130 - Functions
We define a function using the following function expression:
- let sum = function (a, b) {
- return (a + b);
- }
What could the definition of the corresponding arrow function look like?
-
A
- let sum = function (a, b)
- =>
- {
- return (a + b);
- };
-
B
- let sum = (a, b) => a + b;
-
C
- let sum = (a, b)-- > a + b;
-
D
- let sum = (a, b) => { a + b };
Reveal correct answer
Correct answer: B
Explanation
Topics: arrow function function expression
Try it yourself:
- let sum = function (a, b) {
- return (a + b);
- }
- console.log(sum(3, 4)); // 7
- let sum1 = (a, b) => a + b;
- console.log(sum1(3, 4)); // 7
- let sum2 = (a, b) => {a + b};
- console.log(sum2(3, 4)); // undefined
- // let sum = (a, b)-- > a + b;
- // Uncaught SyntaxError: invalid increment/decrement operand
- /*
- let sum = function (a, b)
- =>
- {
- return (a + b);
- };
- */
- // Uncaught SyntaxError: missing { before function body
Explanation:
There are only two syntactical correct answers.
But only one of them returns a value.
If you use the curly braces inside of an arrow function
you also need to use the return keyword in order to return a value.
Arrow functions allow us to write shorter function syntax.
https://www.w3schools.com/js/js_arrow_function.asp
The function keyword can be used to define a function inside an expression.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function
(There are similar questions Q229 and Q529.)
Q130 (Please refer to this number, if you want to write me about this question.)
A. Choice D is incorrect as it does not follow the correct arrow function syntax. Arrow functions do not use the function keyword or curly braces for single-line expressions. The arrow function in choice D is written in a way that resembles a traditional function expression, which is not the correct format for an arrow function.
B. The correct arrow function syntax for the given function expression is shown in choice A. Arrow functions are a concise way to write function expressions in JavaScript, and in this case, the arrow function directly returns the sum of the two input parameters without the need for explicit return keyword or curly braces.
C. Choice C is incorrect as it contains a syntax error. The arrow function syntax in JavaScript uses the => symbol to separate the parameters from the function body. The use of -- > is not valid in JavaScript arrow functions, resulting in a syntax error.
D. The arrow function syntax in choice B is incorrect. When using curly braces in an arrow function, you need to explicitly use the return keyword to return a value. In this case, the return statement is missing, and the function body is not correctly defined.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
