You get a bonus - 1 coin for daily activity. Now you have 1 coin

All together: JavaScript features

Lecture



  1. Code structure
  2. Variables and Types
  3. Interaction with the visitor
  4. Operator features
  5. Logical operators
  6. Cycles
  7. switch design
  8. Functions
  9. Methods and properties
  10. Total

This chapter presents the main features of JavaScript, at the level of basic constructs, types, syntax.

It will be especially useful if you have previously programmed in another language, well, or as a repetition of important points in the section.

Everything is very compact, with links to detailed descriptions.

Code structure

Operators are separated by a semicolon:

1 alert( 'Привет' ); alert( ); alert( 'Мир' );

As a rule, a line break also implies a semicolon. So it will also work:

1 alert( 'Привет' )
2 alert( 'Мир' )

.. However, sometimes JavaScript does not insert a semicolon. For example:

1 var a = 2
2 +3
3
4 alert(a); // 5

There are cases when this leads to errors that are hard enough to find and fix.

Therefore, it is recommended to put semicolons. Now it is, in fact, the standard.

Single-line comments // ... and multi-line /* ... */ are supported:

Read more: Code structure.

Variables and Types

  • Declared a var directive. Can store any value:

    var x = 5;
    x = "Петя" ;

  • There are 5 "primitive" types and objects:
    1 x = 1; // число
    2 x = "Тест" ; // строка, кавычки могут быть одинарные или двойные
    3 x = true ; // булево значение true/false
    4 x = null ; // спец. значение (само себе тип)
    5 x = undefined ; // спец. значение (само себе тип)

    There are also special numeric values Infinity (infinity) and NaN .

    The value NaN indicates an error and is the result of a numeric operation if it is incorrect.

    We'll talk about objects in the chapter Objects as associative arrays; they are very different in JavaScript from most other languages.

  • A null value is not a "link to a null address / object" or something similar. This is just a special value.

    It is assigned if we want to indicate that the value of the variable is unknown.

    For example:

    var age = null ; // возраст неизвестен

  • The value undefined means “variable not assigned”.

    For example:

    var x;
    alert( x ); // undefined

    You can assign it explicitly: x = undefined , but this is not recommended.

  • In the name of the variable can be used any letters or numbers, but the number can not be the first. Dollar characters $ and underscore _ are allowed along with letters.

Read more: Variables, Introduction to Data Types.

Interaction with the visitor

The simplest functions for interacting with the visitor in the browser:

prompt (question [, default]])
Ask a вопрос and return the entered string, or null if the visitor clicked "Cancel".
confirm (question)
Ask a вопрос and suggest buttons "Ok", "Cancel". Returns true/false , respectively.
alert
Display a message on the screen.

All these functions are modal , i.e. Do not allow the visitor to interact with the page until the response.

For example:

1 var userName = prompt( "Введите имя?" , "Василий" );
2 var smokes = confirm( "Вы хотите чаю?" );
3
4 alert( "Посетитель: " + userName);
5 alert( "Чай: " + smokes);

Details: User interaction: alert, prompt, confirm.

Features of operators

  • To add lines, use the + operator.

    If at least one argument is a string, the other one is also cast to the string:

    1 alert( 1 + 2 ); // 3, число
    2 alert( '1' + 2 ); // '12', строка
    3 alert( 1 + '2' ); // '12', строка

  • The === comparison checks for exact equality, including the same type. This is the most obvious and reliable way to compare.

    The remaining comparisons == < <= > >= perform a numeric type conversion:

    1 alert( 0 == false ); // true
    2 alert( true > 0 ); // true

    There will be no casts when comparing two strings (see below).

    Exception: null and undefined values ​​behave in non-zero comparisons.

    • They are equal to each other null == undefined and are not equal to anything else. In particular, non-zero.
    • In other comparisons with casting (not === ), the null value is converted to zero, and undefined becomes NaN (“error”).

    This behavior can lead to non-obvious results, so it’s best to use === for comparison.

    For example, a funny consequence of these rules for null :

    1 alert( null > 0 ); // false, т.к. null преобразовано к 0
    2 alert( null == 0 ); // false, в стандарте явно указано, что null равен лишь undefined
    3
    4 // но при этом (!)
    5 alert( null >= 0 ); // true , т.к. null преобразовано к 0
    From the point of view of common sense is impossible. The value null not equal to zero and no more, but null >= 0 returns true !

  • String comparisons are lexicographical, characters are compared by their unicode codes.

    Therefore, it turns out that lowercase letters are always larger than uppercase letters:

    1 alert( 'а' > 'Я' ); // true

Read more: Basic operators, Comparison operators and Boolean values.

Logical operators

There are logical operators in JavaScript: AND (denoted by && ), OR (denoted by || ) and NOT (denoted by ! ). They interpret any value as logical.

Do not confuse them with bitwise AND, OR, NOT operators, which also exist in JavaScript and work with numbers at the bit level.

As in most other languages, the logical operators use a “short cycle” of calculations. For example, the evaluation of the expression 1 && 0 && 2 will stop after the first AND && , since it is clear that the result will be false (zero is interpreted as false ).

The result of the logical operator is the last value in a short cycle of calculations.

It can be said in a different way: although the values ​​are interpreted as logical, but the one that ultimately determines the result is returned without conversion.

For example:

1 alert( 0 && 1 ); // 0
2 alert( 1 && 2 && 3 ); // 3
3 alert( null || 1 || 2 ); // 1

Read more: Logical operators.

Cycles

  • Three types of cycles are supported:

    01 // 1
    02 while (условие) {
    03    ...
    04 }
    05
    06 // 2
    07 do {
    08    ...
    09 } while (условие);
    10
    11 // 3
    12 for ( var i = 0; i < 10; i++) {
    13    ...
    14 }

  • A variable can be declared directly in a loop, but it will also be visible outside it.
  • break/continue directives to exit the loop / go to the next iteration are supported.

    To exit simultaneously from several levels of the cycle, you can set a label.

    Syntax: " имя_метки: ", it is put only before cycles and blocks, for example:

    1 outer:
    2 for (;;) {
    3      ...
    4    for (;;) {
    5      ...
    6      break outer;
    7    }
    8 }

    The transition to the label is possible only from the inside of the cycle, and only to the external block in relation to this cycle. In an arbitrary place of the program can not go.

Read more: Break and continue directives.

switch design

For comparisons in the switch construction, the === operator is used.

For example:

01 var age = prompt( 'Ваш возраст' , 18);
02
03 switch (age) {
04    case 18:
05      alert( 'Никогда не сработает' ); // результат prompt - строка, а не число
06
07    case "18" : // вот так - сработает!
08      alert( 'Вам 18 лет!' );
09      break ;
10
11    default :
12      alert( 'Любое значение, не совпавшее с case' );
13 }

Details: switch design.

Functions

Syntax of functions in JavaScript:

1 // function имя(список параметров) { тело }
2 function sum(a, b) {
3    var result = a + b;
4
5    return result;
6 }

  • sum is the name of the function, the restrictions on the name of the function are the same as on the variable name.
  • Variables declared via var inside a function are visible everywhere inside this function, if , for , etc. blocks. visibility is not affected.
  • Parameters are passed "by value", i.e. copied into local variables a , b , with the exception of objects that are passed "by reference", we will discuss them in detail in the chapter Objects as associative arrays.
  • A function without return is considered to return undefined . Calling return with no value also returns undefined :

    1 function f() { }
    2 alert( f() ); // undefined

Read more: Functions.

Methods and properties

All values ​​in JavaScript, with the exception of null and undefined , contain a set of auxiliary functions and values ​​accessible "through the dot".

Such functions are called "methods", and values ​​- "properties".

For example:

1 alert( "Привет, мир!" .length ); // 12

Strings also have a toUpperCase() method that returns an uppercase string:

1 var hello = "Привет, мир!" ;
2
3 alert( hello.toUpperCase() ); // "ПРИВЕТ, МИР!"

Read more: Methods and properties.

Total

In this chapter, we repeated the main features of JavaScript, the knowledge of which is necessary to bypass most of the “rakes”, and just to write good code.

created: 2014-10-07
updated: 2021-03-13
132498



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone