Search

Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

JavaScript - Looping Statement example

Loops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true.
Very often when you write code, you want the same block of code to run over and over again in a row.
Instead of adding several, almost equal lines in a script we can use loops to perform a task like this.
In JavaScript there are two different kinds of loops:
          (1)  For
          (2)  While

For Loop :
Loops through a block of code a specified number of times
Syntax:
for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}
When a for loop executes, the following occurs:
The initializing expression initial-expression, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity.
The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the for loop terminates.
The statements execute.
The update expression incrementExpression executes, and control returns to Step 2.
Example
<html>
<body>
<script language=“javascript”>
for (i = 1; i <= 6; i++)
{
document.write("<h" + i + ">Visions Developer " + i);
document.write("</h" + i + ">");
}
</script>
</body>
</html>

The example above defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 6. i will increase by 1 each time the loop runs. Results in printing six predefined headers in HTML.


 While Loop :
Loops through a block of code while a specified condition is true while loop, is used to run the same block of code while a specified condition is true.
Syntax:

while (var<=endvalue)
{
code to be executed
}

Example

<html>
<body>
<script language=“javascript”>
var i=0
while (i<=10)
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
</script>
</body>
</html>

The example above defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.

Do….While Loop
The do...while statement repeats until a specified condition evaluates to false.

Syntax:
do
{
statement
} while

Statement executes once before the condition is checked. If condition returns true, the statement executes again.
At the end of every execution, the condition is checked. When the condition returns false, execution stops and control passes to the statement following do...while.
Example

<html>
<body>
<script language=“javascript”>
i=0;
do
{
i++;
document.write(i);
} while (i<5);
</script>
</body>
</html>

In the following example, the do loop iterates at least once and reiterates until i is no longer less than 5.
Break statement
Use the break statement to break the loop.
Continue statement
Use the continue statement to break the current loop and continue with the next value.
For...In Statement
The for...in statement is used to loop (iterate) through the elements of an array or through the properties of an object. The code in the body of the for ... in loop is executed once for each element/property.
Syntax:
for (variable in object)
{
code to be executed
}
Example

<script language=“javascript”>
var x;
var mycars = new Array();
mycar s[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>

Above code will display all the elements of array mycars on web page. With each element on new line

JavaScript - Conditional Statement example

A conditional statement is a set of commands that executes if a specified condition is true.
JavaScript supports two conditional statements: if...else and switch.

If Condition
Use of if statement to perform certain statements if a logical condition is true; use the optional else clause to perform other statements if the condition is false.
Syntax : 
if ( condition){
          statements1
}else{
          statements2
}
       
Example :

<html>
<body>
<script language=“javascript”>
var d = new Date()
var time = d.getHours()
if (time < 10)
{
document.write("<b>Good morning</b>");
}
else
{
document.write("<b>Good day</b>");
}
</script>
</body>
</html>
 
In above example we get current browser date and time by inbuilt function Date () and getHours() that we see in near future.

In variable d we store current date for getting hours from that.
Variable time will store current time in hours, if a condition check for time is less than 10.
If time is less than 10 then “Good morning” message is printed otherwise control goes to else block and “Good day” message is displayed on web page.


Switch Statement

A switch statement allows a program to evaluate an expression and attempt to match the expression’s value to a case label.
If a match is found, the program executes the associated statement.
The program first looks for a label matching the value of expression and then executes the associated statement.
If no matching label is found, the program looks for the optional default statement, and if found, executes the associated statement.
If no default statement is found, the program continues execution at the statement following the end of switch.
The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch.
If break is omitted, the program continues execution at the next statement in the switch statement.

Syntax : 
switch ( expression)

{
    case label :
               statement;
               break;

    case label :
              statement;
              break;

     default:
             statement;
}

Example :   
<html>
<body>
<script language=“javascript”>
var d = new Date();
theDay=d.getDay();

switch (theDay)
{
case 5:
     document.write("<b>Finally Friday</b>");
     break;

case 6:
     document.write("<b>Super Saturday</b>");
     break;
case 0:
     document.write("<b>Sleepy Sunday</b>");
     break;

default:
     document.write("<b>Good Weekend </b>");
}
</script>
</body>
</html>

In above example getDay() gets days number from current date.
Above example will generate a different greeting based on what day it is. Note that Sunday=0, Monday=1, Tuesday=2, etc.
The code will store day value in variable theDay and depending on this value message inside case is displayed on web page.
D.getDay will always give some numerical value.
Numerical value for Sunday is 0, and for Saturday it is 6. If theDay value doesn’t satisfy given case statement then default case is executed.

JavaScript - Operators example

An operator is used for getting some process between operands.

JavaScript supports lots type of Operators We not going deeply on all operators but lets go through all type.

Arithmetic Operators
OperatorDescriptionExampleResult
+Addition
x=2
y=2
x+y
4
-Substraction
x=5
y=2
x-y
3
*Multiplication
x=5
y=4
x*y
20
/Division
x=15
y=5
x/y
3
%Modulus (division remainder)
x = 5
y = 2
x/y
1
++Increment
x=5
x++
6
--Decrement
x = 5
x--
4

Example:

<script language="JavaScript">

var a = 5;

++a;

alert("The value of a = " + a );

</script>
Assignment Operators
OperatorDescriptionExample
=Equal Assign
x = y
x = 10
+=Addition & Equal
x += y
x = x + y
-=Substraction & Equal
x -= y
x = x - y
*=Multiplication & Equal
x * = y
x = x * y
/=Division & Equal
x /= y
x = x / y
%=Modulation & Equal
x % y
x = x % y
   

Example:

<script language="JavaScript">

var a = 10;

var b = 2;

a+=b;

alert("The value of a +=b is = " + a );

</script>


Comparison  Operators
OperatorsDescriptionExampleResult
==Is equal to5 == 8false
===Is equal to (check for both value & type)
x = 5
y=*5*
x==y
x===y


true
false
!=Is not equal5!=8false
>Is greater than5>8false
<Is less than5<8true
>=Is greater than or equal to5>=8false
<=Is less than or equal to5<=8false

Example:

<script language="JavaScript">
var a = 5;
var b = 6;
a= a>b;
alert("The value of a = " + a );
</script>

Logical  Operators
OperatorDescriptionExampleResult
&&And
x=6
y=3
(x<10 && y>1)


true
||Or
x=6
y=3
(x == 5 || y == 5)
false
!Not
x=6
y=3
!(x == y)


false

Example:
<script language="JavaScript">

var userID;
var password;
userID = prompt("Enter User ID " , " ");

password = prompt ("Enter Password"," ");

if (userID == "Visions" && password == "Developer")
{
Alert ("Valid Login");
}
else
{
Alert(“Invalid Login”);
}
</script>

String  Operator
A string is most often text, for example “Hello Good Morning”. To Stick or join two or more string variables together use the + operator (String Operator).
Example :
                    Txt1 = "Visions"
                    Txt2 = "Developer"
                    Txt3 = Txt1 + " " + Txt2
Now the Txt3 Variable Contain Visions Developer
Conditional Operator
JavaScript is scripting language but still it contains a conditional operator that assign a value to a variable based on some condition.
                Syntax :  varname = (condition)?value1:value2
               
Example: Msg = (userId = "CEO")?"Welcome ABC":"Welcome"
If the variable userId is equal to "CEO", then put the string "Welcome ABC" in the variable named Msg. If the variable userID is not equal to "CEO", the put the string "Welcome" into the variable named greeting.

JavaScript - Variables

After getting basic knowledge and some needed topics of JavaScript. Now let’s get through Variables, Operators etc.

        A variable is a “container” for information you want to store. A variable’s value can change during the script. You can refer to a variable by name to see its value or to change its value.

Rules For Variable Names :

- Variable names are case sensitive.
- They must begin with a letter or the underscore (‘_’) character.
- Always remember that JavaScript is case-sensitive! A variable named "vision" is not the same as a variable named "VISION".

Declare Variable :   
- You can create a variable with the var statement.
Syntax : var variablename = some value
- You can also create a variable without the var statement.
    Variablename = some valueAssign.
- You can assign a value to a variable like this.
    Var cName = "Visions" Or also like this
    cName = "Visions"
The variable name is on the left side of the expression and the value you want to assign to the variable is on the right. Now the variable ‘cName’ has the value “Visions”.
Lifetime of Variables
When you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared.
               
If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts they are declared and end when the page is closed.
So like other programming language there are no such complexity regarding lifetime or scope of variable.
               
If Short if you declare variable in function then within that function used as local variable otherwise outside of function it is used by publically by all functions.

Example:  
<script language=”javascript”>

var name = "Visions Developer"

document.write(name)

document.write("<h1>"+name+"</h1>")

</script>

This example declares a variable, assigns a value to it, and then displays the Variable. Then the variable is displayed one more time, only this time as a heading.

Javascript - Popup Boxes

Now you all are getting basic knowledge of JavaScript Syntax, how to use and how to embed with Html so let’s be yourself ready to fly with dynamism of JavaScript.

When we want something highlighted, prompted or any important thing to say end users then we have to attract his visions on that information. So Popup Boxes popping up that information at end user’s sight.
In JavaScript we can create three kind of popup boxes :
  • Alert Box
  • Confirm Box
  • Prompt Box

Alert Box :

An alert box is often used if you want to make sure information comes through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax:                
alert("Alert Message")                 
Example:
 <html>
<head>
<script language="javascript">
function show_alert()
{
alert("Hi! This is vIsIoNs DeVeLoPeR!!")
}
</script>
</head>
<body>
<input type="button" on click="show alert()" value="Show alert box" >
</body>
</html>

In above example when user click on button one function called that we see deeply in near future tutorials. That Show Alert() function give alert box with content.

 If we want more than one line in alert box then use ‘\n’
alert("Hi! This is vIsIoNs DeVeLoPeR!!" + ‘\n’ + “Beyond Imagination Beyond Success!!!”)

Confirm Box :

A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
Syntax: 
confirm("Message")                      
Example:
 <html>
<head>
<script language="javascript">
function disp_confirm()
{
var r=confirm("Press a button")
if (r==true)
{
document.write("You pressed OK!")
}
else
{
document.write("You pressed Cancel!")
}
}
</script>
</head>
<body>
<input type="button" on click="disp_confirm()" value="Display a confirm box" />
</body>
</html>

In above example when user gets box with ok and cancel when user click on ok then text shown you pressed ok if cancel clicked then you pressed cancel.

Prompt Box :

A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel” the box returns null.
Syntax:  
prompt("sometext","defaultvalue")
Example:
 <html>
<head>
<script language="javascript">
function disp_prompt()
{
var c=prompt("Please enter 1st Rank IT Company","Visions Developer")
if (c!=null && c!="")
{
document.write("Hello " + c + "! Is best IT company in world.")
}
}</script>
</head>
<body>
<input type="button" onclick="disp_prompt()" value="Display a prompt box">
</body>
</html>
After clicking button this asked to enter value from user but also it’s come with default value which is Visions Developer.
And after getting proper input from user print that value as given in function.

Basic Concepts

In Intoduction part we see about scripting language, JavaScript introduction, and how to write JavaScript with html that one programme. Now let’s learn some facts and more close look in JavaScript.

Ending Statements with a Semicolon is necessary?

    When we use other programming language then in most of language we put Semicolon at end of statement. With traditional programming languages, like C++ and Java, each code statement has to end with a semicolon.
Many programmers continue this habit when writing JavaScript, but in general, semicolons are optional! However, semicolons are required if you want to put more than one statement on a single line.

How to Handle Older Browsers?

Browsers that do not support JavaScript will display the script as page content. To prevent them from doing this, we may use the HTML comment tag as follows:
<script language="JavaScript">
<! -- Document. Write ("Hello JavaScript!")//-->
</script>
The two forward slashes at the end of comment line (//) are a JavaScript comment symbol. This Prevents the JavaScript compiler from compiling the line.

Writing JavaScript Code
JavaScript Where to JavaScript in the body section will be executed WHILE the page loads. JavaScript in the head section will be executed when CALLED.

Where to Put the JavaScript?
JavaScript in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event.

Scripts in the head section: Scripts to be executed when they are called, or when an event is triggered, go in the head section. When you place a script in the head section, you will ensure that the script is loaded before anyone uses it.
<Html>
<Head>
<script language=”JavaScript">
....</script></head>

Scripts in the body section: Scripts to be executed when the page loads go in the body section. When you place a script in the body section it generates the content of the page.
<html>
<head>
</head>
<body><script language=”javascript">
....</script></body>

Scripts in both the body and the head section: We can place an unlimited number of scripts in your document, so you can have scripts in both the body and the head section.
<Html>
<Head>
<script language=”JavaScript">
....</script>
</head>
<Body>
<script language=”JavaScript">
....</script>
</body>

Using an External JavaScript in HTML file
Sometimes you might want to run the same JavaScript on several pages, without having to write the same script on every page. To simplify this, you can write a JavaScript in an external file. Save the external JavaScript file with a .js file extension.
To use the external script, point to the .js file in the "src" attribute of the <script> tag:
<Html>
<Head>
<script src="fileName.js">
</script>
</head>
<Body>
</body>
</html>

Java Script - Introduction

Welcome Friends, you are coming to see this tutorial so this shows that you surf through web of internet so I think you are basically known with Internet, WWW, Server and Client little much and that is enough for me to give start in Dynamic Scripting Language JAVASCRIPT.

First of all let’s understand about scripting language.

    Scripting Language

A high-level programming language that is interpreted by another program at runtime rather than compiled by the computer’s processor as other programming languages are Scripting languages, which can be embedded within HTML, commonly are used to add functionality to a Web page, such as different menu styles or graphic displays or to serve dynamic advertisements. These types of languages are client-side scripting languages, affecting the data that the end user sees in a browser window. Other scripting languages are server-side scripting languages that manipulate the data, usually in a database, on the server.

Scripting languages came about largely because of the development of the Internet as a communications tool. JavaScript, ASP, JSP, PHP, Perl, and Python are examples of scripting languages.

A scripting language developed by Netscape to enable Web authors to design interactive sites. Although it shares many of the features and structures of the full Java language, it was developed independently. JavaScript can interact with HTML source code, enabling Web authors to spice up their sites with dynamic content. JavaScript is endorsed by a number of software companies and is an open language that anyone can use without purchasing a license.

A-Z of JavaScript - 2

?
var myEarth = earth({name:"earth",numberofmoons:1});
var myjupiter=jupiter({name:"jupiter",numberofmoons:66});
The three key points here:


1.       There is code reuse.
2.       There is encapsulation. The name and numberOfMoons properties are encapsulated.
3.       The child objects can add in their own specific functionality.
Now an explanation of the syntax:


1.       The base object planet accepts some data in the spec object.
2.       The base object planet creates a closures called that which is returned. The that object has access to everything in the spec object. But, nothing else does. This provides a layer of encapsulation.
3.       The child objects, earth and jupiter, set up their own data and pass it to base planet object.
4.       The planet object returns a closure which contains base functionality. The child classes receive this closure and add further methods and variables to it.
Hoisting 
No matter where var's are declared in a function, javascript will "hoist" them meaning that they behave as if they were declared at the top of the function. 
view source
print?
mylocation = "dublin"; // global variable
function outputPosition() {
console.log(mylocation);  // outputs "undefined" not "dublin"
var mylocation = "fingal" ;
console.log(mylocation);  // outputs "fingal"
}
outputPosition();
In the function above, the var declaration in the function means that the first log will "see" the mylocation in the function scope and not the one declared in the global scope. After declaration, the local mylocation var will have the value "undefined", hence why this is outputted first.  Functions that are assigned to variables can also be hoisted.  The only difference being that when functions are hoisted, their definitions also are - not just their declarations.Immediate Function Expressions
Immediate function expression are executed as soon as they are defined. 
view source
print?
(function() {

console.log("I ain't waiting around");

}());
There are two aspects of the syntax to note here.  Firsty, there is a () immediately after the function definiton, this makes it execute. Secondly, the function can only execute if it is a function expression as opposed to a function declaration. The outer () make the function an expression.  Another way to define a an immediate function expression is: 
view source
print?
var anotherWay = function() {
console.log("I ain't waiting around");
}()

JSON
JavaScript Object Notation (JSON) is a notation used to represent objects. It is very similar to the format used for Javascript Object literals except the property names must be wrapped in quotes. The JSON format is not exclusive to javascript; it can be used by any language (Python, Ruby etc). JSON makes it very easy to see what's an array and what's an object. In XML this would be much harder. An external document - such as XSD - would have to be consulted. In this example, Mitt Romney has an array describing who might vore for him and an object which is his son. 
view source
print?
{"name": "Mitt Romney", "party": "republicans", "scary": "of course",
"romneysMostLikelyVoters": ["oilguzzlers", "conservatives"], son : {name:'George Romney}}

Loose typing
Javascript is loosely typed. This means that variables do not need to be typed. It also means there is no complex class hierarchies and there is no casting. 
view source
print?
var number1 = 50;
var number2 = "51";

function output(varToOutput) {
// function does not care about what type the parameter passed is.
console.log(varToOutput);
}
output(number1);  // outputs 50
output(number2);  // outputs 51

Memoization
Memoization is a mechanism whereby functions can cache data from previous executions. 
view source
print?
function myFunc(param){
if (!myFunc.cache) {
myFunc.cache = {}; // If the cache doesn't exist, create it.
}
if (!myFunc.cache[param]) {
//... Imagine the code to work out result below
// is computationally intensive.
var result = {
//...
};
myFunc.cache[param] = result;  // now result is cached.
}
return myFunc.cache[param];
}

Method
When a function is stored as a property of an object, it is referred to as a method. 
view source
print?
var myObject {
myProperty: function () {
//...
// the this keyword in here will refer to the myObject instance.
// This means the "method" can read and change variables in the
// object.
}
}

Modules
The goal of modules is to enable javascript code bases to more modular.  Functions and variables are collated into a module and then the module can decide what functions and what variables the outside world can see - in the same way as encapsulations works in the object orientated paradigms. In javascript we create modules by combining characteristics of closures and immediate function expressions. 
view source
print?
var bankAccountModule = (function moduleScope() {
var balance = 0; //private
function doSomethingPrivate(){  // private method
//...
return { //exposed to public
addMoney: function(money) {
//...  
},
withDrawMoney: function(money) {
//...
},
getBalance: function() {
return balance;
}
}());
In the example above, we have a bank account module:


·         The function expression moduleScope has its own scope. The private variable balance and the private function doSomethingPrivate, exist only within this scope and are only visible to functions within this scope.
·         The moduleScope function returns an object literal. This is a closure which has access to the private variables and functions of moduleScope. The returned object's properties are "public" and accesible to the outside world.
·         The returned object is automatically assigned to bankAccountModule
·         The immediate function ()) syntax is used. This means that the module is initialised immediately.
Because the returned object (the closure) is assigned to bankAccountModule, it means we can access the bankAccountModule as: 
view source
print?
bankAccountModule.addMoney(20);
bankAccoumtModule.withdrawMoney(15);
By convention, the filename of a module should match its namespace. So in this example, the filename should be bankAccountModule.js.  
Namespace Pattern
Javascript doesn't have namespaces built into the language, meaning it is easy for variables to clash. Unless variables are defined in a function, they are considered global. However, it is possible to use "." in variables names. Meaning you can pretend you have name spaces. 
view source
print?
DUBLINTECH.myName = "Alex"
DUBLINTECH.myAddress = "Dublin

Object Literal Notation
In javascript you can define an object as collection of name value pairs.   The values can be property values or functions. 
view source
print?
var ireland = {
capital: "Dublin",
getCapital: function () {
return this.capital;
}
};

Prototype properties (inheritance)
Every object has a prototype object. It is useful when you want to add a property to all instances of a particular object. Suppose you have a constructor function, which representent Irish people who bought in the boom. 
view source
print?
function IrishPersonBoughtInTheBoom(){
}

var mary = new IrishPersonBoughtInTheBoom ();
var tony = new IrishPersonBoughtInTheBoom ();
var peter = new IrishPersonBoughtInTheBoom ();
...
Now, the Irish economy goes belly up, the property bubble explodes and you want to add a debt property to all instances of this function. To do this you would do: 
view source
print?
IrishPersonBoughtInTheBoom.prototype.debt = "ouch";
Then... 
view source
print?
console.log(mary.debt);   // outputs "ouch"
console.log(tony.debt);   // outputs "ouch"
console.log(peter.debt);   // outputs "ouch"
Now, when this approach is used, all instances of IrishPersonBoughtInTheBoom share the save copy of the debt property. This means, that they all have the same value as illustrated in this example.  
Returning functions
A function always returns a value.  If return is not specified for a function, the undefined value type will be returned. Javascript functions can also return some data or another function. 
view source
print?
var counter = function() {
//...
var count = 0;
return function () {
return count = count + 1;
}
}

var nextValue = counter();
nextValue();   // outputs 1
nextValue();   // outputs 2
Note, in this case the inner function which is returned "closes" over the count variable - making it aclosure - since it encapsulates its own count variable. This means it gets its own copy which isdifferent to the variable return by nextValue.count.
this keyword
The this keyword in Java has different meanings, depending on the context it is used. In summary:


·         In a method context, this refers to the object that contains the method.
·         In a function context, this refers to the global object. Unless the function is a property of another object. In which case the this refers to that object.
·         If this is used in a constructor, the this in the constructor function refers to the object which uses the constructor function.
·         When the apply or call methods are used the value of this refers to what was explictly specified in the apply or call invocation.
typeof
typeof is a unary operator with one operand. It is used to determine the types of things (a bit like getClass() in Java). The values outputted by typeof are "number", "string", "boolean", "undefined", "function", "object". 
view source
print?
console.log(typeof "tony");          // outputs string
console.log(typeof 6);               // outputs number
console.log(false);                  // outputs boolean
console.log(this.doesNotExist);   // outputs undefined if the global scope has no such var
console.log(typeof function(){});    // outputs function
console.log(typeof {name:"I am an object"});  //outputs object
console.log(typeof ["I am an array"]) // typedef outputs object for arrays
console.log(typeof null)              // typedef outputs object for nulls
Some implementations return "object" for typeof for regular expressions; others return "function". But the biggest problem with typeof is that it returns object for null. To test for null, use strict equality... 
view source
print?
if (myobject === null) {
...
}

Self-redefining functions
This is a good performance technique. Suppose you have a function and the first time it is called you want it to perform some set up code that you never want to perfom again. You can execute the set up code and then make the function redefine itself after that so that the setup code is never re-excuted. 
view source
print?
var myFunction = function () {
//set up code only to this once
alert("set up, only called once");

// set up code now complete.
// redefine function so that set up code is not re-executed
myFunction = function() {
alert("no set up code");
}
}
myFunction();  // outputs - Set up, only called once
myFunction();  // outputs - no set up code this time
myFunction();  // outputs - no set up code this time
Note, any properties added to the set up part of this function will be lost when the function redefines itself. In addition, if this function is used with a different name (i.e. it is assigned to a variable), the re-definition will not happen and the set up code will re-execute.Scope
In javascript there is a global scope and a function scope available for variables. The var keyword does not need to be used to define variable in the global scope but it must be used to define variable in the local function scope. When a variable is scoped to a local function shares the name with a global variable, the local scope takes precedence - unless var was not used to declare the local variable in which case any local references are pointing to the global reference. There is no block scope in javascript. By block we mean the code between {}, aka curly braces. 
view source
print?
var myFunction = function () {
var noBlockScope = function ( ) {
if (true) {
// you'd think that d would only be visible to this if statement
var d = 24;  
}
if (true) {
// this if statement can see the variable defined in the other if statement
console.log(d);
}
}
noBlockScope();

Single var pattern
You can define all variables used by a function in one place.  It is ensures tidy code and is considered best practise. 
view source
print?
function scrum() {
var numberOfProps = 2,
numberOfHookers = 1,
numberOfSecondRows = 2,
numberOfBackRow = 3
// function body...
}
If a variable is declared but not initialized with a value it will have the value undefined.
Strict Equality
In javascript it is possible to compare two objects using ==. However, in some cases this will perform type conversion which can yield unexpected equality matches. To ensure there is strict comparison (i.e. no type conversions) use the === syntax. 
print?
console.log(1 == true)    // outputs true
console.log(1 === true)   // outputs false
console.log(45 == "45")   // outputs true
console.log(45 === "45")  // outputs false

Truthy and Falsey
When javascript expects a boolean, you may specify a value of any type. Values that convert to true are said to be truthy and values that convert to false are said to be falsey. Example of truthy values are objects, arrays, functions, strings and numbers: 
view source
print?
// This will output 'Wow, they were all true'
if ({} && {sillyproperty:"sillyvalue"} && [] &&
['element'] && function() {} && "string" && 89) {
console.log("wow, they were all true");
}
Examples of falsey values are empty strings, undefined, null and the value  
view source
print?
// This will out put: 'none of them were true'
if (!("" || undefined || null || 0)) {
console.log("none of them were true");
}