Today I learned something about Javascript that surprised me. No wonder I had been writing some really awful code, because I had not grasped many such oddities of my favorite language. Let me share with you a few oddities of Javascript as a language, which probably gives way too much leverage to a developer in my opinion.
Location of opening braces
What do you think the following will do?
function func() {
return {
name: "AGuy"
};
}
console.log(func().name);
You are probably guessing right, it will print AGuy on the Firebug (or other console)
How about this:
function func() {
return
{
name: "AGuy"
};
}
console.log(func().name);
The same output right? Nope.
You get this!
WTH? Why is that, just because I moved the brace to a new line? Java would have happily accepted this sort of daredevilry.
It turns out Javascript inserts a semicolon if I don't put a brace on the same line, so that the second piece is actually executing the following"
function func() {
return undefined; // This is where we return already!
// The rest is dead code!
{
name: "AGuy"
};
}
More interesting stuff as I read through this fun book, I'm loving it (This is not a McDonald's ad, sorry)
Reference: "Javascript Patterns", Stoyan Stefanov
Location of opening braces
What do you think the following will do?
function func() {
return {
name: "AGuy"
};
}
console.log(func().name);
You are probably guessing right, it will print AGuy on the Firebug (or other console)
How about this:
function func() {
return
{
name: "AGuy"
};
}
console.log(func().name);
The same output right? Nope.
You get this!
func() is undefined
WTH? Why is that, just because I moved the brace to a new line? Java would have happily accepted this sort of daredevilry.
It turns out Javascript inserts a semicolon if I don't put a brace on the same line, so that the second piece is actually executing the following"
function func() {
return undefined; // This is where we return already!
// The rest is dead code!
{
name: "AGuy"
};
}
More interesting stuff as I read through this fun book, I'm loving it (This is not a McDonald's ad, sorry)
Reference: "Javascript Patterns", Stoyan Stefanov
Comments
Post a Comment