This is the sixth day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
In this article, we’ll look at some of the other amazing JavaScript bugs that aren’t perfect but don’t affect how JavaScript works – autoappend (“;”) ) problem
Automatic semicolon for imperfect JavaScript (;
) problem
Some “small” bugs encountered in real development are often not easy to find, incredible.
Learn more about JavaScript and explore some of the magic bugs. Let’s start with the code:
// This is a normal function,
function why1(one, two, three) {
return {
one,
two,
three,
}
}
why1('why1'.'why1'.'why1')
/ / can output {one: "why1", two: "why1", three: "why1"},
Copy the code
{one: “why1”, two: “why1”, three: “why1”
// But this is an ordinary function with a problem,
// littleTip: the result of a newline problem
function why2(one, two, three) {
return
{
one, two, three
}
}
why2('why2'.'why2'.'why2')
// undefined
// why??? Why is that?
Copy the code
Analysis:
Question point – Short for object
Is it the object shorthand?
The above notation uses object shorthand here, when deconstructing an assignment:
// After processing the requested data, we usually need to process and get the required data
{ name:a, age:b } = res.data
// If the name of variable A is name and the name of variable B is age, we can abbreviate it
{name, age} = res.data
Copy the code
{name: name, age: age} {name, age}
Answer: Not the shorthand question,
It may seem at first glance that this is a question of shorthand, but often simple questions are not what we think.
The first normal, normal why1 function returns an object based on the argument we passed, with the correct result.
But the second function why2 is also a normal function because it prints undefined to save on line breaks. This is a problem, a magical bug that you can’t understand.
The line after the return is wrapped, the line after the return is empty, and the semicolon (;) is automatically added. The curly braces on the next line {one, two, three} are considered to be the start of a function block, which is meaningless. The comma (“,”) in {one, two, three} is also considered an operator, not a separator. So no error is reported, and return; Undefined is returned. This is also a magic bug that is not easy to find.