Introduction
When it comes to JavaScript, it is definitely a different language by all means. The results of writing a code are not "so-obvious" as you would expect in languages like C#/Java, etc. JavaScript is something which people loved back in late 90s, the early modern internet era. Then for years, it was neglected badly, ignored because of the love people had for "server" side scripts/languages. Then, there came an era of revival for JavaScript and with the advent of stuff like Ajax/Angular JS/Backbone JS/Node JS, etc. JavaScript is now paying all other languages back in the same coin. People are now writing JavaScript on server side, client side and every side of the application.
You may agree or disagree, but IMO, the stages Javascript has been through has made it such a unique language. A language which was once considered to show funny alerts in the browser is now being used to write full fledge server side code as well as front end code - who knew it? At least, I didn't :)
Background
The idea of this series is to bring a collection of all the "not-so-obvious" things that can or may have happened to you while writing JavaScript code. If you are a beginner to JavaScript, I am sure you must be going through these "oh-what-not-obvious-at-all" moments while writing core JavaScript code.
Let's share and make a collection out of them!
JavaScript OMG # 1 - "Ubiquity of Variables in JavaScript"
Ever heard of scope? Scope is like visibility and life time of a particular object/variable in code. Variables declared within a method in a server side like C# has block level scope. What do I mean by BLOCK LEVEL SCOPE? Let's see an example.
When you try to compile it, Visual Studio tells you something you don't want to hear:
"The name 'bar' does not exist in the current context"
Here is the hotness of JavaScript in action ...check out !
What do you think the above JavaScript function will do when called?
The "OMG" is IT WORKS (no big deal - everything WORKS in JavaScript .... Sssshhhh ;))
And the results on the console are like this:
The above code will not work in statically typed languages like C# since the compiler is not sure if 'bar
' will ever be declared or not (since it depends on the 'if
' condition to be true
).
What happened? Is JavaScript crazy? No! It's not crazy. It's OMG! Enjoy!
There is something in JavaScript world called "Variable Hoisting" (Hoist means to "raise up").
Within a function or globally (I'll talk about global in later articles), all variable declarations fly to the top of the function above line 1 written in function. This means when we write this code and call the function, all variable declarations are hoisted within its scope. We all know that scope of variables defined within the function, is the function itself. So no matter where you "declare" the variable, I am not saying assigning value, I am saying wherever you "declare" the variable, does not matter, all declarations fly and go up to the top of their scope, in this example to the top of the function Foo( )
, so variable FooFoo
and bar
are declared at the top, hence visible everywhere.
Quote:
What will happen if the if condition fails? The assignment of bar will never happen and the function will printf
10
undefined
because the value of bar will never get defined.
JavaScript OMG # 2 - "Truthy Falsy"
You know what is boolean datatype write? In server side languages, it can hold a TRUE
or a FALSE
value. In some databases, this kind of data type is defined as a bit which can hold either 1
(for true
) or 0
(for false
), this holds true for MS SQL Server since there is no boolean data type, bit datatype
works there anyways.
So is true TRUTHY and false FALSY ? .... Who knows ;)
In famous languages like C#/Java, etc., conditions want an expression which must give a boolean result. So if the expression returns 'true
', the condition runs, else it goes to the 'else
' block, if defined.
Let us look at an easy C# example:
int RoleId = GetRoleId();
if(RoleId==10)
{
}
else
{
}
Let us look at another easy C# example:
int[] BookId = {4,3,6,25};
if(BookId.Length>3 && BookId.Max()>20)
{
}
In JavaScript, as you might expect, it is different. JavaScript can accommodate values other than boolean within 'if
' conditions. These values need to be either "Truthy" or "Falsy".
Check out the following JavaScript code:
var name = " Some good boi";
if(name)
{
console.log("name is truthy at the moment");
}
"name is truthy at the moment"
If the expression/variable passed to the 'if
' statement is "something", literally something! JavaScript 'if
' statement considers it and jumps into the 'if
' statement. So that 'something' has to be a Truthy value. All the following values are considered 'falsy' in JavaScript:
false
(the boolean false
not the string
'false
') 0
(the number zero) ""
(empty string) null
- undefined
- NaN (a special Number value meaning Not-a-Number!)
Everything except the above values are considered 'truthy' and will let the 'if
' condition to run successfully.
Few quick examples:
var totalPoint = 10;
var extraPoint ;
if(totalPoint && extraPoint)
{
console.log('Student is a geek');
}
if(totalPoint || extraPoint)
{
console.log('Student is average')
}
Student is average
Similarly,
var totalPoint = 10;
var extraPoint= 40;
if(totalPoint && extraPoint)
{
console.log('Student is a geek');
}
if(totalPoint || extraPoint)
{
console.log('Student is average')
}
Student is a geek
Another Use of TRUTHY/FALSY Concept
Truthy/Falsy concept is used in JavaScript to set default values to a variable. Check out:
var config;
var logConfig = config || {};
Similarly, another example ...
var amount;
var extraAmount = 100;
var finalAmount = ( amount && extraAmount )? 50:100;
console.log(finalAmount);
100
More OMGs on the Way...
Did you learn anything interesting/fun/annoying reading this article?
I will be posting at least 2 or 3 OMGs in every episode of JavaScript OMGs. If you learned anything out of it, feel free to express.
Wishing you a good day from New York City!