Click here to Skip to main content
15,883,883 members
Articles / Web Development / HTML

The OMGs of JavaScript - Part # 1

Rate me:
Please Sign up or sign in to vote.
4.49/5 (14 votes)
9 Dec 2014CPOL4 min read 31.7K   27   12
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)


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Jan Zumwalt11-Feb-15 13:23
Jan Zumwalt11-Feb-15 13:23 
Questionjavascript scoping Pin
Member 1033131011-Dec-14 8:28
Member 1033131011-Dec-14 8:28 
AnswerRe: javascript scoping Pin
Anas R Firdousi11-Dec-14 8:43
Anas R Firdousi11-Dec-14 8:43 
AnswerRe: javascript scoping Pin
JakePogo15-Dec-14 6:38
professionalJakePogo15-Dec-14 6:38 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun10-Dec-14 17:52
Humayun Kabir Mamun10-Dec-14 17:52 
GeneralCorrection Pin
phil.o10-Dec-14 5:02
professionalphil.o10-Dec-14 5:02 
AnswerRe: Correction Pin
Anas R Firdousi10-Dec-14 5:25
Anas R Firdousi10-Dec-14 5:25 
GeneralRe: Correction Pin
phil.o10-Dec-14 5:28
professionalphil.o10-Dec-14 5:28 
QuestionNot sure ... Pin
Florian Rappl9-Dec-14 23:42
professionalFlorian Rappl9-Dec-14 23:42 
... if you understood JavaScript. It is a different language than C# (obviously). Therefore there are other concepts. The concept of hoisting for instance. Only function give scope in JavaScript, therefore your assumption that your first part is an actual "OMG moment" is only justified for people, who did not read the spec. Why are you using something without reading the manual?! Of course you might see different behavior for similar code. It is a different language.

Second JavaScript's "if" does NOT work differently than in C#. First you need to forget the concept of a pure boolean, since JavaScript types are always dynamic, hence even a boolean is just an embedded value in a dynamic type. Therefore there is no compiler to check the data type in such statements (that would also be impossible by the definition of a dynamic type).

Second for a condition a boolean evaluation is required (hence your initial assumption about a boolean type, which was unfortunately wrong, since the condition is only triggered at runtime and does not require anything at compile-time). So what to do now? The answer is to call a special function on the value which casts the stored value to a boolean representation. In case of an embedded "boolean" value (true or false) this is just the identity. Otherwise a scheme is applied that depends on the data type. Therefore the number 0is represented in the boolean false value, while all other numbers are true (excluding the special case NaN, as this is not only represented as false, but also false when compared with NaN itself).

So why is it not different in C#? I can overload the true and false operators of a data type and use values of that type directly in a condition. Therefore you see that C# also does not require booleans as values in conditions, but just types that can be represented as booleans.

C#
void Main()
{
	var foo = new Foo();
	
	if (foo)
		Console.WriteLine("Obviously works without having a pure boolean type...");
}

class Foo
{
	public static Boolean operator true(Foo foo)
	{
		return true;
	}
	
	public static Boolean operator false(Foo foo)
	{
		return false;
	}
}


That works and I did not use anything special like a pre-compiler or anything.
AnswerRe: Not sure ... Pin
Anas R Firdousi10-Dec-14 5:32
Anas R Firdousi10-Dec-14 5:32 
GeneralRe: Not sure ... Pin
Florian Rappl10-Dec-14 6:40
professionalFlorian Rappl10-Dec-14 6:40 
Questionformat Pin
Simon_Whale9-Dec-14 23:10
Simon_Whale9-Dec-14 23:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.