JavaScript basic syntax

Writing grammar

  1. Case sensitive. Like Java, variable names, function names and everything else are case sensitive writing syntax.
  2. Semicolons at the end of each line are optional. If multiple statements are written on a line, semicolons must be added to distinguish multiple statements.
  3. Comment, single line comment: / / comment content; Multiline comment: / * comment content*/
  4. Brackets represent code blocks. You can certainly understand the following statements. Like java, braces represent code blocks.
    if (count == 3) { 
       alert(count); 
    } 
    



Output statement

js can output content in the following ways, but different statements are output to different locations

  1. Use window Alert() writes the warning box.
  2. Use document Write() writes the HTML output.
  3. Use console Log() is written to the browser console.
<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script>
    // There are three ways of JavaScript output. Annotation syntax is the same as Java
    window.alert("Hello, world!1") // Pop up warning box

    document.write("Hello, world!2"); // Write to html

    console.log("Hello, world!3"); // Write to console
</script>

</body>
</html>

Write warning box:

Write HTML output:
Write to the console, and press F12 in the browser interface to see the console in the following figure:



variable

In JavaScript, variables are declared with the VaR keyword (short for variable). Format var variable name = data value;. JavaScript is a weakly typed language, and variables can store different types of values; As follows, when defining a variable, it is assigned as numeric data. You can also change the value of the variable to a string type number

var test = 20;
test = "Zhang San";

js also has the following rules for naming variable names, which are basically the same as the java language

  1. The constituent characters can be any letter, number or underscore (_) Or dollar sign ($);
  2. The number cannot start;
  3. It is recommended to use hump naming;

The var keyword in JavaScript is a bit special. It is different from other languages in the following aspects

  1. Scope: global variables

      {
          var age = 20;
      }
      alert(age);  // The age variable defined in the code block can also be used outside the code block
    
  2. Variables can be defined repeatedly

      {
          var age = 20;
          var age = 30;//JavaScript will replace 20 of the previous age variable with 30
      }
      alert(age); //The printed result is 30
    

To solve the above problem, ECMAScript 6 adds the let keyword to define variables. Its usage is similar to var, but the declared variables are only valid in the code block where the let keyword is located, and repeated declarations are not allowed.

For example:

{
    let age = 20;  
}
alert(age); // age is not defined

ECMAScript 6 adds the const keyword to declare a read-only constant. Once declared, the value of the constant cannot be changed. Just look at the common features through the following code

const PI = 3.14;
PI = 3; // An error is reported. The variable decorated with const can only be assigned once



data type

There are two types of data types available in JavaScript: primitive types and reference types.

Note: use the typeof operator to obtain the data type, alert(typeof age); Output the data type of the age variable in the form of a pop-up box

Raw data type:

  1. Number: number (integer, decimal, NaN(Not a Number))

    var age = 20;
    var price = 99.8;
    
    alert(typeof age); // The result is: number
    alert(typeof price);// The result is: number
    
  2. String: character, string, single or double quotation

    var ch = 'a';
    var name = 'Zhang San'; 
    var addr = "Beijing";
    
    alert(typeof ch); //The result is string
    alert(typeof name); //The result is string
    alert(typeof addr); //The result is string
    
  3. boolean: boolean. true,false

    var flag = true;
    var flag2 = false;
    
    alert(typeof flag); //The result is boolean
    alert(typeof flag2); //The result is boolean
    
  4. null: object is empty

    var obj = null;
    alert(typeof obj);//The result is object
    
    stay JavaScript Medium, null yes "nothing". It is regarded as something that does not exist.
    Unfortunately, in JavaScript Medium, null The data type of is an object.
    You can null stay JavaScript Middle is an object understood as a bug. It was supposed to be null. 
    You can set the value to null Empty object:
    
  5. Undefined: when the declared variable is uninitialized, the default value of the variable is undefined

    var a ;
    alert(typeof a); //The result is undefined
    



operator

JavaScript provides the following operators. Most of them are the same as the Java language. The difference is that = = and = = = in JS relational operators. We will only demonstrate the difference between these two in a moment. Other operators will not be demonstrated

  1. Unary operator: +, –
  2. Arithmetic operators: +, -, *, /,%
  3. Assignment operators: =, + =, - =
  4. Relational operators: >, <, > =, < =,! =, = =, = =, = =
  5. Logical operators: & &, ||,!
  6. Ternary operator: conditional expression? true_value : false_value

==Difference from = = = and
==

  1. Judge whether the types are the same. If not, perform type conversion
  2. Then compare the values

===: js

  1. Judge whether the types are the same. If not, return false directly
  2. Then compare the values
var age1 = 20;
var age2 = "20";

alert(age1 == age2);// true--- convert the type first, and then compare the content
alert(age1 === age2);// False--- first compare whether the types are consistent. If they are inconsistent, return false directly. If they are consistent, then compare the contents

Type conversion: when the = = operator is explained above, it is found that type conversion will be performed, so let's explain the type conversion in JavaScript in detail.

Other types converted to number

  1. String to number type: convert to a number according to the literal value of the string. If the literal value is not a number, it is converted to NaN;

    take string Convert to number There are two ways:
    1. use `+` Positive sign operator
    var str = +"20";
    alert(str + 1) //21
    
    2. use `parseInt()` function(method): 
    ar str = "20";
    alert(parseInt(str) + 1);
    
  2. boolean to number type: true to 1, false to 0

    var flag = +false;
    alert(flag); // 0
    

Other types are converted to boolean

  1. number type is converted to boolean type: 0 and NaN are converted to false, and other numbers are converted to true
  2. String type is converted to boolean type: empty string is converted to false, and other strings are converted to true
  3. null type converted to boolean type is false
  4. undefined to boolean type is false
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    /*
        ==:
            1. Judge whether the types are the same. If not, perform type conversion
            2. Then compare the values

        ===:
            1. Judge whether the types are the same. If not, return false directly
            2. Then compare the values
    */
  var age1 = 20;
  var age2 = "20";

  alert(age1 == age2);  // true
  alert(age1 === age2);  // false

    /*
        Type conversion:
            * Other types are converted to number:
                1. string: It is converted to a number according to the literal value of the string. If the literal value is not a number, it is converted to NaN. Generally, parseInt is used
                2. boolean: true To 1, false to 0
    */

    var str = +"20";
    alert(str + 1);  // 21
    alert(parseInt(str) + 1); // 21

    var flag1 = +true;
    alert(flag1);  // 1
    var flag2 = +false;
    alert(flag2); // 0

  /*
        Type conversion:
            * Other types are converted to boolean:
                1. number: 0 And NaN to false, and other numbers to true
                2. string: Empty strings are converted to false, and other strings are converted to true
                3. null: false
                4. undefined: false
    */

    var number1 = 0;
    if(number1){   // Automatic type conversion in if statements
         alert("The returned result is true");
    }else{
         alert("The returned result is false");
    }


    var number2 = 12;
    if(number2){   // Automatic type conversion in if statements
         alert("The returned result is true");
    }else{
         alert("The returned result is false");
    }

    var str1 = null;
    if(str1){   // Automatic type conversion in if statements
         alert("The returned result is true");
    }else{
         alert("The returned result is false");
    }

    var str2 = "afasf";
    if(str2){   // Automatic type conversion in if statements
         alert("The returned result is true");
    }else{
         alert("The returned result is false");
    }

    var a;
    if(a){   // Automatic type conversion in if statements
         alert("The returned result is true");
    }else{
         alert("The returned result is false");
    }
</script>

</body>
</html>



Process statement

if statement, switch statement, for statement, while statement, do... While statement

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    // 1. if
    var count = 3;
    if(count == 3){  // Perform automatic type conversion, count -- > Boolean
        alert(count);
    }

    // 2. switch
    var weekday = 3;
    switch(weekday){
        case 1:{
            alert("Monday");
            break;
        }
        case 2:{
            alert("Tuesday");
            break;
        }
        case 3:{
            alert("Wednesday");
            break;
        }
        case 4:{
            alert("Thursday");
            break;
        }
        case 5:{
            alert("Friday");
            break;
        }
        case 6:{
            alert("Saturday");
            break;
        }
        case 7:{
            alert("Sunday");
            break;
        }
        defalut:{
            alert("Output error");
            break;
        }
    }

    // 3. for
    var sum = 0;
    for(let i = 0; i <= 100; i++){
        sum += i;
    }
    alert(sum);  // 5050

    // 4. while
    var i = 0;
    var sum = 0;
    while(i <= 100){
        sum += i;
        i++;
    }
    alert(sum);  // 5050

    // 5. do....while
    var i = 0;
    var sum = 0;
    do{
        sum += i;
        i++;
    }while(i <= 100);
    alert(sum);  // 5050

</script>
</body>
</html>



function

Functions (that is, methods in Java) are code blocks designed to perform specific tasks; JavaScript functions are defined by the function keyword.
Method 1:

function Function name(Parameter 1,Parameter 2..){
    Code to execute
}

Mode 2:

var Function name = function (parameter list){
    Code to execute
}

be careful:

  1. Type is not required for formal parameters. Because JavaScript is a weakly typed language, parameters a and b of the following functions do not need to define data types, because adding var before each parameter is meaningless.
    function add(a, b){
        return a + b;
    }
    
  2. There is no need to define the type of the return value. You can use return directly inside the function

Function calling function: function name (actual parameter list);

let result = add(10,20);

Note: in JS, function calls can pass any number of parameters, such as let result = add(1,2,3); It passes data 1 to variable a, data 2 to variable b, and data 3 has no variable reception.

Case:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>

  // Mode 1
  function add(a, b){
    return a + b;
  }

  let result = add(100, 200);
  alert(result); // 300

  // Mode II
  var add = function(a, b){
    return a + b;
  }

  let result1 = add(100, 200);  // The number of incoming parameters is exactly 2
  alert(result1);  // 300

  let result2 = add(200, 300, 1000);  // The number of bits of the incoming parameter is greater than two, and only the first two are taken
  alert(result2);  // 500

  let result3 = add(100);  // If the number of incoming parameters is less than two, NaN is returned
  alert(result3); // 100 + NaN = NaN


</script>
</body>
</html>

Tags: Javascript Front-end

Posted by WendyB on Sat, 04 Jun 2022 01:33:06 +0530