Click here to Skip to main content
14,118,915 members
Click here to Skip to main content
Add your own
alternative version

Stats

23.9K views
27 bookmarked
Posted 9 Dec 2014
Licenced CPOL

The OMGs of JavaScript - Part # 1

, 9 Dec 2014
Rate this:
Please Sign up or sign in to vote.
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:

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:

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:

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:

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,

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:

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 ...

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)

Share

About the Author

Anas R Firdousi
Software Developer (Senior)
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 1 Pin
Jan Zumwalt11-Feb-15 13:23
memberJan Zumwalt11-Feb-15 13:23 
This is not code that would be commonly used. This is more theoretical than practical Frown | :(
Questionjavascript scoping Pin
Member 1033131011-Dec-14 8:28
memberMember 1033131011-Dec-14 8:28 
AnswerRe: javascript scoping Pin
Anas R Firdousi11-Dec-14 8:43
memberAnas 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
memberHumayun Kabir Mamun10-Dec-14 17:52 
GeneralCorrection Pin
phil.o10-Dec-14 5:02
mvephil.o10-Dec-14 5:02 
AnswerRe: Correction Pin
Anas R Firdousi10-Dec-14 5:25
memberAnas R Firdousi10-Dec-14 5:25 
GeneralRe: Correction Pin
phil.o10-Dec-14 5:28
mvephil.o10-Dec-14 5:28 
QuestionNot sure ... Pin
Florian Rappl9-Dec-14 23:42
professionalFlorian Rappl9-Dec-14 23:42 
AnswerRe: Not sure ... Pin
Anas R Firdousi10-Dec-14 5:32
memberAnas 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
professionalSimon_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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web02 | 2.8.190518.1 | Last Updated 10 Dec 2014
Article Copyright 2014 by Anas R Firdousi
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid