ES5
To illustrate the basic and essential parts of the JS for a better use of language and demystify many questions that have arisen over the years, to the JS become an essential language for those working with web. (At least for me lol!)
JavaScript was not created by the W3C, as many think. In fact it was created by a guy named Brendan Eich at Netscape (one of the pioneers of web browsers). He called LiveScript, but then its name was changed to JavaScript. Even so the original name is ECMAScript why JavaScript is maintained by the European Computer Manufacturer's Association. Ie, call JavaScript yourself, that's how everybody calls.
Returning to the main subject: JavaScript is not maintained by the W3C, it is a language created and maintained by ECMA. They keep a language documentation on their website, but the best documentation are still the materials you can find on the web the same.
JavaScript is a lightweight language, interpreted and object-based with first - class functions , most known as the scripting language for Web pages but also used in several other without browser environments as node.js or Apache CouchDB . It is a scripting language multi-paradigm , based on prototype that is dynamic, and supports programming styles object - oriented, imperative and functional.
You may have read the part that talks about developing separating into layers, where we explained that there are three basic layers in development for Web: the information is with HTML formatting, which is with the CSS and behavior, which is with JavaScript.
JavaScript is the third layer of development which it handles the first two layers, ie HTML and CSS. Imagine that you need a Slider images. The whole drive, click actions in the little arrows and etc, is the JavaScript that will take care. That's what we call behavior.
It may be too early to talk about object-oriented programming languages, but you need to know at least that JavaScript is a language with Object Orientation. We will not go into details now, we do not want you to confuse the balls. But know that an object on the schedule is a set of information. Object is a group of data. But for now, just stay with this information. Let's delve into appropriate time.
Do list here ...
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;
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¹³.
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.
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).
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.
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;
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
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)
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
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.
When we compare two of these three values using the operator == , the result is always true .
false == 0 // -> true
false == "" // -> true
0 == "" // -> true
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
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.
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
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/
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}
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
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 };
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
An invocation expression is a JavaScript syntax to call (or execute) a function or method.
f(0)
Math.max(x, y, z)
a.sort()
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 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()
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
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 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
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
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
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
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
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
This logical operator and binary returns true if one of the values are true.
true && false // -> true
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
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.
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
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 && // -> ''
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"
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
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
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
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.
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
}
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);
}
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.
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');
}
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');
}
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');
}
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);
}
}
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
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 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
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
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