Javascript Essentials

"this object"​​

Understand JavaScript’s “this”

First, know that all functions in JavaScript have properties, just as objects have properties. And when a function executes, it gets the this property—a variable with the value of the object that invokes the function where this is used.


An instance is an implementation of a Function

  • The this reference ALWAYS refers to (and holds the value of) an object—a singular object—and it is usually used inside a function or a method
  •  it can be used outside a function in the global scope.
  • when we use strict mode, this holds the value of undefined in global functions and in anonymous functions that are not bound to any object.

We need this to access methods and properties of the object that invokes function A,

    var person = {
    firstName   :"Penelope",
    lastName    :"Barrymore",
    showFullName:function () {
    console.log (this.firstName + " " + this.lastName);
    }

    }
​
    person.showFullName (); // Penelope Barrymore

this is not assigned a value until an object invokes the function where this is defined. Let’s call the function where this is defined the “this Function.”

    var person = {
    firstName   :"Penelope",
    lastName    :"Barrymore",
    showFullName:function () {
    console.log (this.firstName + " " + this.lastName);
    }

    }
​
    person.showFullName (); // Penelope Barrymore

this in global scope

  var firstName = "Peter",
    lastName = "Ally";

    function showFullName () {
    console.log (this.firstName + " " + this.lastName);
    }
​
    var person = {
    firstName   :"Penelope",
    lastName    :"Barrymore",
    showFullName:function () {
    console.log (this.firstName + " " + this.lastName);
    }
    }
​
    showFullName (); // Peter Ally​
​
    window.showFullName (); // Peter Ally​

    person.showFullName (); // Penelope Barrymore

When this is most misunderstood and becomes tricky

 

	var person = {
   firstName   :"Penelope",
   lastName    :"Barrymore",
   showFullName:function () {
​// The "context"​
console.log (this.firstName + " " + this.lastName);
 }
}
​
​// The "context", when invoking showFullName, is the person object, when we invoke the showFullName () method on the person object.​
​// And the use of "this" inside the showFullName() method has the value of the person object,​
person.showFullName (); // Penelope Barrymore​
​
​// If we invoke showFullName with a different object:​
​var anotherPerson = {
firstName   :"Rohit",
lastName    :"Khan"​
};
​
​// We can use the apply method to set the "this" value explicitly—more on the apply () method later.​
​// "this" gets the value of whichever object invokes the "this" Function, hence:​
person.showFullName.apply (anotherPerson); // Rohit Khan​
​
​// So the context is now anotherPerson because anotherPerson invoked the person.showFullName ()  method by virtue of using the apply () method​
    

 lets fix lexical scope issues in nested callbacks

  
    var user = {
    data:[
    {name:"T. Woods", age:37},
    {name:"P. Mickelson", age:43}
    ],
    clickHandler:function (event) {
    var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1​
​
    // This line is printing a random person's name and age from the data array​
    console.log (this.data[randomNum].name + " " + this.data[randomNum].age);
    }
    }
​
    // The button is wrapped inside a jQuery $ wrapper, so it is now a jQuery object​
    // And the output will be undefined because there is no data property on the button object​
    $ ("button").click (user.clickHandler); // Cannot read property '0' of undefined

 lets fix lexical scope issues in  callbacks

Solution to fix this when a method is passed as a callback function:


Since we really want this.data to refer to the data property on the user object, we can use the Bind (), Apply (), or Call () method to specifically set the value of this.

fix is call apply & Bind

    $ ("button").click (user.clickHandler);

    $("button").click (user.clickHandler.bind (user)); // P. Mickelson 43

Fix this inside closure

Solution to maintain this inside anonymous functions:

    var user = {
    tournament:"The Masters",
    data      :[
    {name:"T. Woods", age:37},
    {name:"P. Mickelson", age:43}
    ],
​
    clickHandler:function (event) {
    var theUserObj = this;  //*****************************//
    this.data.forEach (function (person) {
    // Instead of using this.tournament, we now use theUserObj.tournament​
    console.log (person.name + " is playing at " + theUserObj.tournament);
    })
    }
​
    }

Fix this when method is assigned to a variable

 

Solution to maintain this inside anonymous functions:


    var data = [
    {name:"Samantha", age:12},
    {name:"Alexis", age:14}
    ];
​
    var user = {
    data    :[
    {name:"T. Woods", age:37},
    {name:"P. Mickelson", age:43}
    ],
    showData:function (event) {
    var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1​
    console.log (this.data[randomNum].name + " " + this.data[randomNum].age);
    }
    }
​
    var showUserData = user.showData;
    showUserData (); // Samantha 12 (from the global data array)​
    //*******************************//
    // Bind the showData method to the user object​
    var showUserData = user.showData.bind (user);
​
    // Now we get the value from the user object, because the <em>this</em> keyword is bound to the user object​
    showUserData (); // P. Mickelson 43

constructor pattern object creation

function Employee (name, profession) {
​this.name = name;
​this.profession = profession;
} // Employee () is the constructor function because we use 
the <em>new</em> keyword below to invoke it.​
​
​var richard = new Employee (“Richard”, “Developer”) 
// richard is a new object we create from the Employee
// () constructor function.​
​
console.log(richard.name); //richard​
console.log(richard.profession); // Developer

Encapsulation in JavaScript

When you simply want to create an object just to store some data, and it is the only object of its kind, you can use an object literal and create your object. This is quite common and you will use this simple pattern often.

Encapsulation in JavaScript

function User (theName, theEmail) {
    this.name = theName;
    this.email = theEmail;
    this.quizScores = [];
    this.currentScore = 0;
}
​
User.prototype = {
    constructor: User,
    saveScore:function (theScoreToAdd)  {
        this.quizScores.push(theScoreToAdd)
    },
    showNameAndScores:function ()  {
        var scores = this.quizScores.length > 0 ? this.quizScores.join(",") : "No Scores Yet";
        return this.name + " Scores: " + scores;
    },
    changeEmail:function (newEmail)  {
        this.email = newEmail;
        return "New Email Saved: " + this.email;
    }
}
firstUser = new User("Richard", "Richard@examnple.com"); 
firstUser.changeEmail("RichardB@examnple.com");
firstUser.saveScore(15);
firstUser.saveScore(10); 

Javascript _proto_

In JavaScript, you add methods and properties on the prototype property when you want instances of an object to inherit those methods and properties.

 

This is the reason we add the methods on the User.prototype property, so that they can be used by all instances of the User object

Javascript Constructor

Constructor Property
In my post JavaScript Prototype, I explained that every function has a constructor property, and this property points to the constructor of the function. For example:


 The one disadvantage of overwriting the prototype is that the constructor property no longer points to the prototype, so we have to set it manually. Hence this line:

   
unction Fruit () {}
​var newFruit = new Fruit ();
console.log (newFruit.constructor) // Fruit ()

Prototype Inheritance by Douglas Crockford obj.create

 if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {
        }
​
        F.prototype = o;
        return new F();
    };
}

obj.create

Object.create = function (o) {
​//It creates a temporary constructor F()​
        function F() {
        }
​//And set the prototype of the this constructor to the parametric (passed-in) o object​
​//so that the F() constructor now inherits all the properties and methods of o​
        F.prototype = o;
​
​//Then it returns a new, empty object (an instance of F())​
​//Note that this instance of F inherits from the passed-in (parametric object) o object. ​
​//Or you can say it copied all of the o object's properties and methods​
        return new F();
    }

Understand it by example

// We have a simple cars object​
​var cars = {
    type:"sedan",
    wheels:4​
};
​
​// We want to inherit from the cars object, so we do:​
​var toyota = Object.create (cars); // now toyota inherits the properties from cars​
console.log(toyota.type); // sedan

Topics

Do list here ...

Data Types

The Javascript types can be divided into two categories Objects and Primitives

Primitive types

Number

String

Boolean

Null

Undefined

Object Types

Arrays

Functions

Date

RegExp

Error

// Primitive Types

// Number
typeof 13;

// String
typeof "Javascript Essentials";

// Boolean
typeof true;

// Null
var noValue = null;
typeof noValue;

// Undefined
var noDefined;
typeof noDefined


// Object Types

// Array
was arr = [ '1', '2', '3'];
typeof arr;

// Function
var sum = function( value1, value3 ) { return value1 + value2; }
typeof sum;
typeof sum.prototype;

// Date
var now = new Date();
typeof now;

// RegExp
var myRegExp = / pattern /;
typeof myRegExp;

// Err
var error = new Error( 'Error!!!' );
typeof error;

Number

Values ​​of type  numbers  are predictably numerical value. In a JavaScript program, they are usually written like this:


13

Fractional numbers are written using the point:


13.5

When we work with a very large or very small numbers, we use scientific notation by letter  and , getting our code, if so:


1.313e13 which is equal to 1,313 x 10¹³.

Aritimética

The main thing to do with numbers is arithmetic. arithmetic operations like addition and multiplication take the value of two numbers and produce a new number from them. Here we see how they are in JavaScript:


100 + 4 * 11

The symbols  +  and  *  are called  operators .

The first is the addition and the second represents multiplication. Placing an operator between two values ​​means that applies the same to produce a new value.

The next example means "add 4 and 100, and multiply the result by 11," or is the multiplication happens before the addition? As you may have thought, the multiplication happens first. But, as in mathematics, this can be changed involving addition with parentheses:


(100 + 4) * 11

For subtraction, it is the operator  - and to use this division operator  / .

When operators appear together without parentheses, the order that they will be applied is determined by the precedence of the operators .

 

The example shows that multiplication comes before addition. / * Has the same precedence. Also for + and -. When multiple operators with the same precedence are close to each other (such as 1 - 2 + 1), they are applied from left to right.

These precedence rules is not something you should worry about. When in doubt, just add parentheses.

  1. Parentheses
  2. potentiation
  3. Multiplication, Division, and Division Rest Full
  4. Addition, Subtraction

There is one more arithmetic operator, which is possibly less familiar. The symbol  %  is used to represent the rest of the operation. X% y is the remainder of division of X by Y. For example, produces 314% 100 14% 144 and 12 gives 0.

The precedence of this operator is equal to the multiplication and division. You can also see this operator being referred to as "module" (though technically "rest" is more accurate).

Special numbers

There are three special values ​​in JavaScript that are considered numbers, but do not behave as normal numbers.

The first two are  Infinity  and  -Infinity , which are used to represent the positive and negative infinite. Infinity - 1  remains Infinity, and so on. But do not put much confidence in this type of infinite-based computing, because it is a heavy math, and will quickly take to our next special issue:  NaN .

NaN means "not a number" (not a number). You gets so when it states  0/0  (zero divided by zero) Infinity -Infinity , or any number of other numerical operation which does not produce an accurate and meaningful value.

// Creating a number through the Number object

var test = Number( 'treze' ); 
test
typeof test

13 / 0
-13 / 0

A special feature of NaN is that it is the only value in JavaScript that is not equal to itself . How to check it? The best way to know if a variable is NaN value is testing whether it is equal to it the same (or different).

If you compare the variable A with her same and the result is false, then A is equal to NaN. Let's take a closer look

var A =;

A == A; // -> false
A != A; // -> true

You could also check if a variable is with the value NaN using the method  isNaN () , but it presents some unexpected behavior for making coercion of values ​​for the number type. 

Strings

The next basic data type is the  string . Strings are used to represent text. They are written delimiting its contents in quotes:

"This is a string"
'This is also a string'

ps: Generally, we use single quotes in JavaScript and double quotes in HTML.

When a backslash  \  is found within the quoted text, this indicates that the character after this has a special meaning.

 

A quotation mark preceded by a backslash will not ending the string, but be part of it. When a character 'n' run after a backslash will be interpreted as a new line. Similarly, a 't' after the backslash character means the tab.


"This is the first line\nAnd this is the second"

This is the first line
And this is the second

There is, of course, situations where you want a backslash in a string just like a backslash. not a special code.

If two slashes are followed from one another, they are canceled, and only one will be left on the value of the resulting string. This is how the string


'\\Fabio Badaro'

The character \ when placed at the end of the line, allows you to continue the string of another line.

var phrase01 = 'lorem ipsum ...',
    phrase02 = "... of products.",
    phrase03 = '\ nA consecteur lorem ipsum dolor sit ...',
    phrase04 = '\ that although the pain is quite clear, from the \' lorem \ 'me',
    text = phrase01 + phrase02 + phrase03 + phrase04;

text;


var text2 = 'lorem ipsum ... \
... Products. \
\ NA consecteur lorem ipsum dolor sit ... \
\ That although the pain is quite clear, from the \ 'lorem \' me ';

text2;

Booleans

This type of data,  boolean , is very specific, with only two possible values,  true  or  false  (true or false). We managed to get these values ​​by comparison operations (x is greater than y? The answer is always yes or no, true or false in this case) and through a "trick" using the unary  !

 

This operator  ! (denial) inverts the value passed to it to a Boolean value opposite to the original

 

When we apply the operator  !  To a variable that actually has a value  considerably , we get the false value as a return of this operation

Truthy e Falsy

All kinds of  values  ​​in JavaScript have, intrinsically (in essence), a respective boolean associated value. These values ​​are clearly noticeable when we make comparisons between values ​​and when we use the unary negation operator !

 

Values  ​​falsy (false) are those that have at their core the value boolean to false. These values ​​are:

false
0 (zero)
"" (Empty string)
null
undefined
NaN

All other JavaScript values ​​are considered  truthy (true) . Some values  ​​truthy  peculiar are:

"0" (zero como string)
"false" (false como string)
function () {} (empty functions)
[] (Empty array)
{} (Empty objects)

Operator!

Now that we know exactly what each boolean value of JavaScript loads, we can calmly and consciously use the operator  !  For the opposite value of natural value in operation. Let the examples, and thus

!false         // -> true
!0             // -> true
!""            // -> true
!NaN           // -> true
!"0"           // -> false
!"false"       // -> false
!function() {} // -> false
!{}            // -> false

An interesting way of knowing what the value  truthy  or  falsy  a value is denying it twice with the operator  ! . Yes, it's like in mathematics,

-1 X -1 = 1 . So we have:

!!false         // -> false
!!NaN           // -> false
!!{}            // -> true
!!function() {} // -> true

Danger!!!

We will also see how to compare values ​​through the comparison operators, but it is important that I explain to you one last thing about the values  ​​falsy .

Comparison rules between these values ​​is somewhat  non-intuitive (a little?) , Then have the knowledge of the expected values ​​in some cases it is crucial at the time of a possible bug. Let's see what these peculiarities.

False, 0 e ""

When we compare two of these three values ​​using the operator  == , the result is always  true .

false == 0  // -> true
false == "" // -> true
0     == "" // -> true

Null e Undefined

The null and undefined values ​​are equivalent only to themselves. 

null == false          // -> false
null == null           // -> true
undefined == false     // -> false
undefined == undefined // -> true
undefined == null      // -> true

Undefined values

We set out in two JavaScript undefined types, used to represent the lack of representation of some data.

 

As explained in the previous article actually only  undefined is indeed a primitive data type,  null  is a type of object, when we do your inspection on the island.

 

The value  undefined  appears when you declare a variable and do not give it any value. Since the value  of pixels  is a value that should be assigned to a variable, and represents the default value for this variable.

References

Expressions and Operators

An expression unit consists of any valid code is determined as a value.

 

Conceptually, there are two types of expressions: those that assign a value to a variable, and those that simply have a value.

 

The expression x = 7 is an example of the first type. This expression uses the + operator to assign a value of seven to the variable x. The expression itself evaluates to seven.

 

The code 3 + 4 is an example of second type of expression. This expression uses the + operator to add three four without assigning the result, seven, to a variable

expressions primary

The simplest expressions, known as primary expressions, are autonomous - they do not include other simpler expressions. Javascript primary expressions are constants or literal values, certain keywords of language and references to variables.

1.23
'Hello'
/pattern/

Initializers objects and array literals

The object initializers and array are expressions whose value is an object or a newly created array.

[]
[1 + 2, 3 + 4]
var matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

{}
{x.o: 'Hello'}
var obj = {x: 2.3, y: 4.5}

Danger!!!

The object we created above is a commonly mistaken literal object with a JSON object, they are similar but are different.

var foo = '{ "budget": { "loadTime": { "max": 200 }, "redirectCount": { "max": 1 }, "globalJS": { "min": 2, "max": 5 } } }';
var bar = JSON.parse(foo) // -> Success

var baz = { budget: { loadTime: { max: 200 }, redirectCount: { max: 1 }, globalJS: { min: 2, max: 5 } } }';
var boo = JSON.parse(baz) // -> Error

function definition expression

A function definition expression defines a JavaScript function and the value of this expression is the newly created role.


var square = function (x) { return x * x };

property access expression

An expression of access to property is assessed on the value of an object property or an array element. JavaScript defines two syntaxes for access to property.

expression. identifier
expression [expression]

var o = {x 1, y {z: 2, 3}};

// Accessing with point
ox // -> 1
Oyz // -> 2

// Accessing with keys
or [ 'x'] // -> 1
or [ 'and'] [ 'z'] // -> 2

// Merging
or [ 'and'] z // -.> 2

invocation expression

An invocation expression is a JavaScript syntax to call (or execute) a function or method.

f(0)
Math.max(x, y, z)
a.sort()

Expressions of object creation

An expression of object creation creates a new object and calls a constructor function to initialize the properties of this object.

new Object();
new Point(2, 3);

new Object;
new Date;

unary

Unary operators change the value of one operand to produce a new value. In JavaScript, all unary operators have high precedence and all are right associative.

 

Unary arithmetic operators are: +, -, ++, - but not all unary operators are symbols, some are written words.

The operator  typeof  produces a string with the value of the given type to provided for evaluation.


typeof 7

The operator delete  that attempts to delete the object property or array element specified as an operand.

var o = { x: 1, z: 2 }
delete o.x // -> success
x in or // -> false

The operator  void  is a unary operator that appears before its single operand, which can be of any type, this operator is unusual and rarely used.

It evaluates its operating and then discards the value and returns undefined


javascrip:void window.open()

Operators Increase

We have two types of increment operators: those used for numbers and used for  strings and numbers .

 

The operators  ++  and  -  are used to increase variable / type values  ​​number . They are often used to assist operators in the logical structure of the program, increasing or decreasing by one unit the value of the variable.

A final information. These operators can be used  before  or  after  the variable, so called operators  pre-increment  or  post-increment .

 

What is the difference between them? The difference is that when we use the operator before the variable, it will be changed before the code execution , then the value processed for the current operation will be already modified, and when we use the operator after the variable, this change will be seen only  later when this variable is requested .

var total = 0;
Total ++ // -> 0 (value has changed, but it will be noticed the next operation)
Total // -> 1
Total ++ // -> 2
--Completely // -> 1
total-- // -> 1
Total // -> 0

Números e Strings

These operators will be used  always  for you! Really are VERY important and elegant, it tells the way. The function of them is to add more content the old variable but without declaring it in verbose form (writing more than could / should).

 

In fact, these operators  operate and assign  the value to the same variable. It can be used to  add, subtract, multiply and divide numbers , or  concatenate new strings in variables that contain values ​​of this type.

// Adding numbers
var result = 7
result + = 6 // -> 13

// concatenando strings
was meuNome = 'Eric'
meuNome += ' Douglas' // -> "Eric Douglas"

// Subtracting numbers
result - = 6 // -> 7

// Multiplying numbers
result * = 3 // -> 21

// Dividing numbers
result / = 2 // -> 10.5

// Rest of the division of numbers
result% = 2 // -> 0.5

// Add an example of how the same variable
// Without using these operators
result = result + 0.8 // -> 1.3

Comparison Operators

Comparison operators are one of the types of  binary operators , in which case, two values ​​used to effect operation.

 

Comparison operators always return a Boolean saying if the comparison is true or false . They are also used in the logical structure of the program.

<Less than // - checks whether the left number is 
   // Less than the number / Right String

<= // Or less than - check if the number of 
   // Left is less than or equal to the number / Right String

> // Greater than - checks whether the left number is higher
   // The number / right string

> = // Greater than or equal to - check if the number is left 
   // Greater than or equal to the number / right string


15 < 30  // -> true
15 <= 30 // -> true
15 > 30  // -> false
15 >= 30 // -> false

comparing Strings

The way to compare strings may not be very intuitive, as any capital letter will always be less  than a lowercase letter.

13 < 26 // -> true

'Thirteen' < 'Twenty-six' // -> false * pay attention here *

var thirteen = 13
thirteen <= 13 // -> true

26 > 13 // -> true
'Twenty six'> 'Thirteen' // -> true

Equality operators

In addition to the comparators shown above, we also have the comparators equality, which are constantly used in our code, but has some peculiarities that if you do not know, certainly  will generate errors in their programs.

// == Tests equality
! = // Forehead inequality
=== // Tests equality restrictively
! == // Forehead inequality restrictively

The big difference between an operator and another is that the first double ( ==  and  ! = ) To compare the values ​​if they are not of the same type , come with a special feature of JavaScript called  Type Enforcement (or type conversion) and this can create a lot of headaches for you. Oh really!

 

I will explain about coercion in the next section, but let's try to understand the code, in a practical way, how each operator works, and then I will explain in a theoretical way and lock it down.

'13' == 13 // -> true
'13' != 13 // -> false

'13' === 13 // -> false
'13' !== 13 // -> true

Coercion Types

The name scares a little right ?! And indeed we should be careful with this because arise many pearls bugs in your code from this effort that the JavaScript is to make all instructions.

 

Whenever you use an operator in JavaScript (if so, is an operation), you will receive a return value, never a mistake, even if you try to work with different data types.

The  coercion of types  (or  conversion  types) is just that! When we try to do operations with data types  different , the JavaScript in bestow with the conversion of the values ​​for some other ...

But the great and terrible problem is that you can hardly predict what this new value, as the rules for such a conversion are not intuitive, which can cause some (s) fail (s) in your application.

 

To avoid all this concern, you should use the operators  ===  and  ! == , Which make the same check equal to their "cousins" , but  NOT  do coercion of types!

true === 'true'   // -> false
true === 1        // -> false
false === 'false' // -> false
false === 0       // -> false

true === true     // -> true
false === false

Logical operators

Whenever we think the logic of the program should think of Boolean values, and to generate these boolean values ​​from the values ​​that our variables carry, we will use the logical operators, which are a type of binary operator, or require two values to generate a third.

 

The operator  !  Is a logical operator which returns a boolean value, but is an exception to the rule for being a unary operator .

&& // This operator is called "E" logical
|| // This operator is called "OR" logic
! // This operator is called "NO" logic

&& Logical

This logical operator and binary returns  true  if both values ​​(or operands) are true. This will be used in the case in conditional structures, an issue that we will address below. For now you just need to know that.


true && true // -> true

|| Logical

This logical operator and binary returns  true  if one of the values ​​are true.


true && false // -> true

! Logical

As we have seen, this operator transforms operating in Boolean, but with the peculiarity of reversing its value  truthy / falsy  for a fact Boolean.


!true // -> false

Curiosities

When we use the logical operators out of conditional structures, they have a unique way of working, which is very worthwhile to be understood so that we can leave our most elegant and concise code.

 

Whenever we use  &&  and  || , they convert the value of the left side for a boolean , to know what value is returned for this operation.

|| operator

The operator  ||  returns the value of your left when it can be converted to  true , that is, when its value is the type  truthy , and always returns the value of the right otherwise, regardless of what value is this, even other value  falsy . See this in practice.

var left = '' // -> type value falsy
var right = 13 // -> type value truthy

left || right // -> 13

var right = 0 // -> now we assign this value falsy right in and see what happens

left || right // -> 0

// Now let's get both values ​​truthy

left = 13
right = 31

left || right // -> 13

&& operator

This operator does the opposite. When the left value is  falsy , it is returned, regardless of what value is that of the right. And the right value will always be returned when the left is  truthy , even if the right amount is  falsy . Let's see the code for clarity.

var left = NaN // -> type value falsy
var right = 13 // -> type value truthy
 
left right && // -> NaN
 
var left = 31 // now we'll assign a value truthy on the left and see what happens
 
left right && // -> 13
 
// Now we will leave the value of the right falsy
 
right = ''
 
left right && // -> ''

ternary operator

This operator is very powerful indeed, as verbosity prevents the code, making it so much more elegant.

 

It is called  ternary operator because it involves three parts in its operation. Let's analyze it down. First I will show it running and then I'll explain it.

var user = ''

// Using Ternary operator or
User ? User 'guest' // -> "guest"

// Assigning a value to variable User
user = 'Eric'

// Using the ternary operator again
user ? user: 'invited' // -> "Eric"
  1. We indicate the variable or condition to be evaluated. If we use the User variable.
  2. This amount to be analyzed will be transformed into a boolean from its value  truthy / false 
  3. If its value is  truthy , then the operator returns the signal After The statement '?' . If the value is  falsy , the value returned is what is after the sign '' .
  4. You can return any JavaScript expression as the return value of this evaluation

operator in

The operator in  expecting an operand on the left side that is or may be converted to a string. On the right side he expects an operand that is an object. It evaluates to true  if the value on the left is the name of a property of the right object.

var o = {x: 1, and 2, z 3};
'y' in o // -> true
'w' in o // -> false
'toString' in o // -> true

var a = [7, 8, 9];
'0' in a // -> true
1 in a   // -> true
3 in a   // -> false

instanceof operator

The operator  instanceof  expect an object to the operand on the left and an operand on the right side to identify a class of objects. The operator evaluates to  true  if the left side of the object is a class instance on the right and is evaluated  false  if otherwise.

var d = new Date();

d instanceof Date // -> true
d instanceof Object // -> true
d instanceof Number // -> false

var a = [1, 2, 3];

a instanceof Array // -> true
a instanceof Object // -> true
a instanceof RegExp // -> false

Precedence Rules

To find out what operation will occur first, you need to know the order of precedence of operators.

 

Check out the list in most of the order (on top) to the lowest (bottom) operator regarding his precedence.

++, - // Pre / post increment / decrement
! // Boolean value alters
typeof   // determina o tipo do operando
* / E% // multiplies, divides and rest
+ And - // adds and subtracts
+        // concatena strings
<, <=,> And> = // comparison numerical order
<, <=,> And> = // comparison alphabetical order
// == Equality test
! = // Inequality test
=== // Strict equality test
! == Strict inequality // test
&& // It is logical
|| // Logical OR
?: Ternary operator //
= // Assignment to the variable or property
* =, / =,% =, + = And - = // operation and assignment

Instructions

The difference we have between  expressions  and statements  is that  expressions  are evaluated to produce a value, since the instructions  are executed to make something happen.

 

The way to make something happen is to evaluate the expression that has side effects that is to generate some value.

var statement

The instruction  var  creates one or more variables, a good practice is to create several variables writing only once the expression  var

var foo = 'foo';
where bar = 'bar';

// Best Pratice

var foo = 'foo', bar = 'bar';
each bar = {
            foo: 1,
            bar: 2
          },
    baz = {
            foo: 1,
            bar: 2
          }

instruction function

The instruction  function  is used to define roles, functions have identifiers (name) and parameters (separated by).

function identificador (param1, param2, param3) {
    instructions;
}

function foo (x, y) {
    return x + y;
}

function factorial (n) {
    if (n <= 1) return 1;
    return n * factorial (n -1);
}

conditional statements

The conditional statements run or jump further instructions, depending on the value of a specified expression. These instructions are the decision points in your code and sometimes also known as branches.

if statement

The statement  if  is the fundamental control construction that allows JavaScript language to make decisions or, more accurately, execute statements conditionally. This statement has two forms.

if (expression)
    instruction

The expression is evaluated, if the value is true (true)  statement is executed and the various forms of writing instruction if

if (true)
    console.log('foo');

if (true) console.log('foo');

// Remember the JSHint and JSLint

if (true) {
    console.log('foo');
    console.log('bar');
}

else statement

The instruction  else  is supplementary education  if , if the expression is true  true , JavaScript executes the first statement, otherwise  else  performs the second statement, the statement  else  is always supplement the instruction if  closer.

if (expression)
    statement1
else
    statement2

if(true)
    console.log('foo');
else
    console.log('bar');

if(true){
    console.log('foo');
    console.log('bar');
}
else {
    console.log('foo');
    console.log('bar');
}

if(true){
    if(true){
        console.log('foo');
    }
    else {
        console.log('bar');
    }
}
else {
    console.log('baz');
}

Else if statement

The statement  if / else evaluates an expression and executes code or another depending on the outcome.

But what about when you need to perform one of several codes, a way to do this is through instruction  else if , it can be understood that the  else if  is a multiple  if .

if(n < 25){
    console.log('foo');
}
else if (n < 50){
    console.log('bar');
}
else {
    console.log('baz');
}

switch statement

A statement  if  causes a branch in the execution flow of a program and you can use  else if  to make a branching several ways, however, this is not the best option when  all  the ramifications depend on the same expression in this case is a waste evaluating the same expression several times.

 

The statement  switch  is exactly this situation, the word  switch  is followed by a parenthetical expression and a block of code in braces.

switch (expression) {
    instrucoes
}

switch(foo) {
    case 1:
        console.log('foo');
        break;

    case 2:
        console.log('bar');
        break;

    default:
        console.log('baz');
        break;
}

If none is found the verification  swicht  enters the instruction  default  and also the failure of the  UPS  makes the  switch  between the case follows, even though the expression was true

You can also use the  switch  within a function with the  return  instead of  break

function convert(foo){
    switch(typeof foo) {
        case 'number':
            return x.toString(16);

        case 'string':
            return '"' + foo + '"';

        default:
            return String(foo);
    }
}

repeat instructions

Looping statements are the instructions that divert their way to themselves to repeat parts of your code. Javascript has four repeat instruçãos  while, do while, for and is in

while statement

As the instruction if  it is the basic conditional statement JavaScript instruction  while  is the basic JavaScript loop. 

while (expression)
    instruction

var count = 0;

while(count < 10) {
    console.log(count);
    count++;
}

the while statement

The statement of the while  is similar to the instruction  while  but with the difference that the expression is tested at the end and not the beginning of the loop, this means that the loop body is always executed at once. 

do {
    instruction
} While (expression);

var count = 0;

do {
    console.log(count);
    count++;    
} while(count < 2);

// Never forget to make your expression return true at some point, if not BROWSER CRASH

for statement

The instruction  is  provides a more convenient loop construction, education  is  simplifies the ties that follow a common pattern.

for (inicializacao; teste; increase)
    instruction

for(var i = 0; i < 9; i++) {
    console.log(i);
}

* Do FizzBuzz

Write a program that prints the numbers from 1 to 100, but in multiples of three print "Fizz" instead of the number and multiples of five print "Buzz". For numbers that are multiples of both 3 and 5, print "FizzBuzz".


Example 1

for(var i = 1; i <= 100; i++) {
    
    if(i % 3 === 0 && i % 5 === 0) {
        console.log('FizzBuzz');
    }
    else if (i % 3 === 0) {
        console.log('Fizz')
    }
    else if (i % 5 === 0) {
        console.log('Buzz');
    }
    else {
        console.log(i);
    }
}

Example 2

for (var i = 1; i <= 100; i++) {
  var f = i % 3 == 0, b = i % 5 == 0;
  console.log(f ? b ? "FizzBuzz" : "Fizz" : b ? "Buzz" : i);
}

Example 3

for(var i=1;i<=100;i++, msg="") {
    if (!(i%3)) msg += "Fizz"; 
    if (!(i%5)) msg += "Buzz";
 
    console.log(msg || i); 
}

Example 4
for(var i = 0; i < 100;) console.log ( (++i % 3 ? '' : 'Fizz') + ( i % 5 ? '' : 'Buzz' ) || i);

A caution to be taken when using loops, if  while  and  the while  is to always check that your expression will one day return  true  for education, if we do not have endless emails Itaú rs.

And when using the loop  is,  the boot variable declaration be careful not to throw it in the global scope, and take care of the  hoisting  (lifting) on the Javascript, then in  is  chained never can use variables with the same name, unless you are using ECMA6

Danger!!!

Instruction is in

The instruction  is in  use the keyword  is  but it's a different totalemente tie kind of bond  is .

The instruction  for ... in  performing the iterations patir of a specific variable, covering all properties of an object.
For each distinct property JavaScript perform an iteration. The following syntax:

for (variable in object)
    intrucao 

Where to learn more

and even more ...

Some tools ...

Events!

Books!

Learn Javascript this object

By Tarun Sharma

Learn Javascript this object

  • 1,025