Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

The OMGs of JavaScript - Part # 1

4.49/5 (14 votes)
9 Dec 2014CPOL4 min read 32.6K  
This is part#1 of a series of not so-obvious stuff in JavaScript... beginner to expert!

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.

C# Code to check block level scoping

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 !

Javascript Way !!!

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:

JS Code result in Chrome Console.

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:

JavaScript
int RoleId = GetRoleId(); // Suppose the method GetRoleId() returns the RoleId

if(RoleId==10)   // the expression RoleId==10 eventually converts to a true or false
{
   // program flow comes here if the expression evaluates to 'true'
}
else
{
  // program flows comes here if the expression evaluates to 'false'
}

Let us look at another easy C# example:

JavaScript
int[] BookId = {4,3,6,25};

if(BookId.Length>3 && BookId.Max()>20)
{
    // Do something only if the expression BookId.Length>3 && BookId.Max()>20 converts to a 'true'
}

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:

JavaScript
var name = " Some good boi";

if(name)   // name is 'string' here 
{
   console.log("name is truthy at the moment");
}

//Outputs:
"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:

JavaScript
var totalPoint = 10;
var extraPoint ;  // if value is not defined it will have 'undefined' by default in JS

if(totalPoint && extraPoint) // so a TRUTHY (totalPoint) AND a FALSY (extraPoint) = FALSY
{
   console.log('Student is a geek');
}

if(totalPoint || extraPoint)
{
   console.log('Student is average')
}

// Output
Student is average

Similarly,

JavaScript
var totalPoint = 10;
var extraPoint= 40;  // now it has some value so it is TRUTHY

if(totalPoint && extraPoint) // so a TRUTHY (totalPoint) AND a TRUTHY (extraPoint) = TRUTHY
{
   console.log('Student is a geek');
}

if(totalPoint || extraPoint)
{
   console.log('Student is average')
}

//Output
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:

JavaScript
var config;

var logConfig = config || {};

// the above code translates to,
// if config variable has something(TRUTHY), give it to logConfig else 
// if config has nothing/not initialized/undefined (FALSY), give a new object literal to logConfig

Similarly, another example ...

JavaScript
var amount; 
var extraAmount = 100;

var finalAmount = ( amount && extraAmount )? 50:100; 

// The above line translates to if both 'amount' and 'extraAmount' are defined(TRUTHY), 
// then finalAmount will be //50 else 100

console.log(finalAmount);

//Output

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!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)