[Clique aqui para ler em português]
Comments
Like HTML and CSS, it is possible to write inside your JavaScript code that will be ignored by the browser, and will exist simply to provide instructions to your colleagues about how the code works (and for you, if you have to go back to your code after 6 months and not remember what you did). Comments are very useful, and you should appear them often, especially when your main code is too big. There are two types:
- One line comment, written after two bars;
// I’m a comment
- Multiline comment is written between the characters
/**
and*/
;
/**
* Me too
* One comment
*/
Variables
A variable is a container for a value, such as a number that we can use in an addition operation, or a text string that we can use as part of a sentence. But a special thing about variables is that their content can change.
let test = 0;
test = 2;
console.log(test);
The difference between var, let and const
Now you may be thinking “why do we need so many keywords to define variables? Why var and let? And where to use const?”.
The reasons are somewhat historical. When JavaScript was created, there was only var. This works basically well in most cases, but it has some problems with the way it works — its design can be confusing or totally annoying. Therefore, let was created in modern versions of JavaScript, a new keyword to create variables that work a little differently for var, correcting their problems in the process.
JavaScript Constants
Many programming languages have the concept of constant — a value that once declared cannot be changed. There are many reasons why you want to do this, from security (if a third-party script changed these values, it could cause problems) to debugging and understanding the code (it is more difficult to accidentally change values that shouldn’t be changed and mess things up ).
In the early days of JavaScript, there were no constants. In modern JavaScript, we have the keyword const, which allows us to store values that can never be changed, const works in exactly the same way as let, except that you cannot assign a new value to const. In the following example, the second line would generate an error:
const weekDays = 7;
weekDays = 8;
Variable types
There are a few different types of data that we can store in variables.
Numbers
You can store numbers in variables, either whole numbers, such as 30 (also called integers) or decimal numbers, for example 2,456 (also called floats or floating point numbers). You do not need to declare variable types in JavaScript, unlike other programming languages. When you assign a variable the value in number, you don’t include the quotes:
let myAge = 17;
Strings
Strings are strings of text. When you give a variable a text value (string), you need to enclose the text in single or double quotes; otherwise, JavaScript will try to interpret it as another variable name.
let byShark = 'See you!';
Booleans
Booleans are true / false (true / false) values — they can have two values, true (true) or false (false). They are generally used to check a condition, which the code then executes properly. For example, a simple case would be:
let alive = true;
While in reality it would be used more as follows:
let test = 6 < 3;
This example is using the “less than” (<
) operator to test whether 6 is less than 3. As you can expect, it will return false, because 6 is not less than 3 !.
Arrays
An array is a single object that contains multiple values enclosed in square brackets and separated by commas. Try to insert the following lines of code into your console:
let myName = ['Chris', 'Bob', 'Jim'];
let myNumber = [10,15,40];
Once these arrays are defined, you can access each of their values through their location within the array. Try these lines:
myName[0]; // return 'Chris'
myNumber[2]; // return 40
The brackets specify an index value corresponding to the position of the value you want returned. You may have noticed that JavaScript arrays are indexed from scratch: the first element is at position 0 of the index.
Objects
In programming, an object is a code structure that represents a real-life object. You can have a simple object that represents a car park containing information about its width and length, or you could have an object that represents a person, and it contains data about his name, height, weight, what language he speaks, how to say hello to her, and more.
let dog = { name : 'Totó', age : 5 };
To obtain the information stored in the object, you can use the following syntax:
dog.name
Operators
There are several operators in JavaScript, below we will see how to use them.
Operador | Descrição | Exemplo |
---|---|---|
+ | Addition | 6 + 9 |
- | Subtraction | 20 - 15 |
* | Multiplication | 3 * 7 |
/ | Division | 10 / 5 |
% | Rest or module | 10 % 2 |
=== | Strict equality | 5 === 2 + 4 |
!== | Non-equality | 'Chris' !== 'Ch' + 'ris' |
< | Less than | 10 < 6 |
> | Bigger then | 10 > 20 |
Increment and decrement operators
Sometimes you want to repeatedly add or subtract a value from a numeric variable. This can conveniently be done using the increment ++
and decrement --
operators.
count++;
Conditions — IF — ELSE
The IF command is used to change the execution flow of a program based on the value, true or false, of a logical expression.
The else condition serves as an alternative if path. That is, the else will be executed if the condition being verified in the if is false.
Example:
let test = 0;
if(test > 0) {
test--;
} else {
test++;
}
Functions
Functions, also known as subroutines, are widely used in programming. One of the great benefits is not having to copy the code every time you need to perform that operation, in addition to making reading the code more intuitive.
function somar(a, b) {
return a+b;
}
somar(2, 3);
somar(23, 435);
LOOP — FOR
In programming, LOOP is an instruction for the program to repeat tasks, remembering that loop in information technology is also known as a loop.
for (let index = 0; index < 10; index++) {
console.count(‘loop’);
}
There are other ways to make a loop like forEach, for-in, for-of, while and etc, but for now the basic for is enough.
Events
Events are actions or occurrences that happen in the system that we are developing, in which it alerts you about these actions so that you can respond in some way, if desired. For example, if the user clicks a button on a web page, you may want to respond to this action by showing an information box on the screen.
Example:
btn.addEventListener(‘click’, bgChange);
List of events:
Event | Description |
---|---|
click | It is triggered when the primary mouse, trackpad,etc. button is pressed and released. |
mousemove | It is fired whenever the mouse cursor moves. |
mouseover | It is triggered when the mouse cursor is moved over an element. |
mouseout | It is triggered when the mouse cursor moves outside the boundaries of an element. |
dblclick | It is fired when a double click occurs with the mouse, trackpad, etc. |
DOMContentLoaded | It is triggered when the document's DOM is fully loaded. |
load | It is triggered when the entire document (DOM and external resources such as images, scripts, etc.) is fully loaded. |
keydown | It is triggered when a key on the keyboard is pressed. |
keyup | It is triggered when a key on the keyboard is released (after pressing). |
scroll | It is triggered when an element is scrolled. |
For a more complete list of all events that are supported, take a look at the Event Types section of the W3C Document Object Model (DOM) Level 3 Events Specification document - and an event compatibility table can also be very useful.
Literal String
A literal string is zero or more characters in double quotes ("
) or single quotes ('
). A string of characters must be enclosed in quotes of the same type; that is, the two single quotes or both double quotes. example of literal strings.
Table: Special characters in JavaScript
Character | Description |
---|---|
\0 | Null byte |
\b | Backspace |
\f | Form feeder |
\n | New line |
\r | Car return |
\t | Tab |
\v | Vertical tab |
\' | Apostrophe or single quotes |
\" | Double quotes |
\ | Backslash character |
Template strings
Template Strings are strings that allow for inline expressions. You can use multi-line strings and string interpolation with them.
let a = 5;
let b = 10;console.log(`Quinze é ${a + b} e
não ${2 * a + b}.`);
Strict mode
The strict mode of ECMAScript is a way to opt for a restricted variant of JavaScript. Strict mode makes several changes to normal JavaScript semantics. First, strict mode eliminates some silent JavaScript errors by making them throw exceptions. Second, strict mode avoids misunderstandings that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical non-strict mode code. Third, strict mode prohibits some syntax that is likely to be defined in future versions of ECMAScript.
Strict mode for scripts
To invoke strict mode for an entire script, put exactly the “use strict” statement; (or ‘use strict’;) before any other statements.
Validator
If you have a very large JS file it is always good to check that everything is really ok.
Coding Standard
Documentation
Every language has documentation and JavaScript would be no different, a tool I really like to read documentation is DevDocs.
if you need any tips faster use devhints
Thanks for reading!
If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!
😊😊 See you! 😊😊
Top comments (1)
\o/, thanks for the comment, it made me really happy.