JavaScript foundation first day

Posted by manianprasanna on Sun, 05 Dec 2021 18:18:09 +0100

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - Introduction mode</title>
</head>
<body>
  <!-- External form: through script of src Property to introduce independent .js file -->
  <script src="demo.js">
    // The code here will be ignored!!!!
  	alert(666);  
  </script>
</body>
</html>

1. Introduction

Master the introduction of JavaScript and preliminarily understand the role of JavaScript

Introduction of javascript

JavaScript programs cannot run independently. They need to be embedded in HTML before the browser can execute JavaScript code. There are three ways to introduce JavaScript code into HTML through script tags:

1, Internal form

Through Script   Tag Package js code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - Introduction mode</title>
</head>
<body>
  <!-- Inline form: through script Label package JavaScript code -->
  <script>
    alert('Hi, welcome to Zhibo to learn front-end technology!');
  </script>
</body>
</html>

2, External chain

Generally, JavaScript code is written in a separate file ending in. js, and then introduced through the src attribute of the script tag

// js file code

document.write('Hi, welcome to Zhibo to learn front-end technology!');
// html 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - Introduction mode</title>
</head>
<body>
  <!-- External form: through script of src Property to introduce independent .js file -->
  <script src="demo.js"></script>
</body>
</html>

If js code is introduced into HTML page, don't write js code in Script, because it will be ignored!!! The following code is shown:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - Introduction mode</title>
</head>
<body>
  <!-- External form: through script of src Property to introduce independent .js file -->
  <script src="demo.js">
    // The code here will be ignored!!!!
  	alert(666);  
  </script>
</body>
</html>

Comments and terminators

Comments can mask code execution or add comments. JavaScript supports two forms of comment syntax:

Single-Line Comments

Use / / to comment the single line code, as shown below

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - notes</title>
</head>
<body>
  
  <script>
    // This is the syntax for single line comments
    // Only one line can be commented at a time
    // Comments can be repeated
    document.write('Hi, welcome to Zhibo to learn front-end technology!');
  </script>
</body>
</html>

multiline comment

//Pass/*   */    To annotate multiline text, the code is as follows

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - notes</title>
</head>
<body>
  
  <script>
    /* This is the syntax for multiline comments */
    /*
    	A more common multiline comment is this
    	You can wrap any line in some
    	Any number of lines is OK
      */
    document.write('Hi, welcome to Zhibo to learn front-end technology!');
  </script>
</body>
</html>

Terminator

In JavaScript; Represents the end of a piece of code, which can be omitted in most cases; Use enter instead.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - Terminator</title>
</head>
<body>
  
  <script> 
    alert(1);
    alert(2);
    alert(1)
    alert(2)
  </script>
</body>
</html>

JavaScript, like HTML and CSS, ignores [some] whitespace characters, but the line feed (carriage return) will be recognized as a terminator;, Therefore, in the actual development, many people advocate omitting the terminator when writing JavaScript code;

Input and output

Output and input can also be understood as the interaction between human and computer. Users input information to the computer through keyboard and mouse, and the computer displays the results to users after processing. This is a process of input and output.

For example: if you press the direction key on the keyboard, the up / down key can scroll the page. Pressing the up / down key is called input, and the page scrolls, which is called output.

output

JavaScript can receive the user's input and then output the input result:

alert(), document.wirte(), console.log();

Take a number as an example. If you input any number into alert() or document.write(), it will be displayed (output) to the user in the form of a pop-up window.

input

Entering any content into prompt() will appear in the browser in the form of pop-up window, generally prompting the user to enter some content.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - Input and output</title>
</head>
<body>
  
  <script> 
    // 1. Any number entered will be displayed in the form of pop-up window
    document.write('What to output');
    alert('What to output');

    // 2. Prompt the user to enter the name in the form of pop-up window. Note that the text here uses English quotation marks
    prompt('Please enter your name:');
  </script>
</body>
</html>

2, Variable

Variables can be understood as containers for storing data, and master the declaration method of variables

<script>
  // The x symbol represents the value of 5
  x = 5;
  // The y symbol represents the value of 6
  y = 6;
    
  //For example: using variables in JavaScript can record a certain data (value)!

  // Save the user input in the variable num (container)
  num = prompt('Please enter a number!');

  // Output the user input through the num variable (container)
  alert(num);
  document.write(num);
</script>

statement

Declaration (definition) variables are composed of two parts: declaration keyword and variable name (identification)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - Declaration and assignment</title>
</head>
<body>
  
  <script> 
    // let variable name
    // Declaration (definition) variables are composed of two parts: declaration keyword and variable name (identification)
    // let is a keyword, which is a word provided by the system to declare (define) variables
    // age is the name of the variable, also known as the identifier
    let age;
  </script>
</body>
</html>

let is a keyword that declares a variable. age is a variable and a variable name. It is used to store data

Let and var are both keywords for declaring variables in JavaScript. It is recommended to use let to declare variables!!!

assignment

We declare a variable, just an empty container, and we also add data to this container.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - Declaration and assignment</title>
</head>
<body>
  
  <script> 
    // Declaration (definition) variables are composed of two parts: declaration keyword and variable name (identification)
    // let is a keyword, which is a word provided by the system to declare (define) variables
    // age is the name of the variable, also known as the identifier
    let age;
    // Assign a value and store 18 this data in the "container"
    age = 18;
    // So the value of age becomes 18
    document.write(age);
    
    // You can also declare and assign values at the same time
    let str = 'hello world!';
    alert(str);
  </script>
</body>
</html>

2.2 keywords

JavaScript uses the special keywords let and var to declare (define) variables. You should pay attention to some details when using them:

Here are the precautions when using let:

  1. Simultaneous declaration and assignment are allowed

  2. Duplicate declarations are not allowed

  3. Multiple variables can be declared and assigned at the same time

  4. Some built-in keywords in JavaScript cannot be used as variable names

Here are the precautions when using var:

  1. Simultaneous declaration and assignment are allowed

  2. Allow duplicate declarations

  3. Multiple variables can be declared and assigned at the same time

In most cases, there is little difference between let and VaR, but let is more rigorous than var. therefore, let is recommended. The differences between them will be further introduced later.

2.3 naming rules for variable names

There are a series of rules for variable names (identifiers):

  1. Can only be letters, numbers, underscores, $, and cannot start with numbers

  2. Letters are case sensitive. For example, age and age are different variables

  3. JavaScript internal occupied words (keywords or reserved words) are not allowed

  4. Try to ensure that variables have certain semantics. See the word to know the meaning

Note: the so-called keyword refers to the words used inside JavaScript, such as let and var, and the reserved word refers to the words not used inside JavaScript at present, but may be used in the future.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - Variable name naming rules</title>
</head>
<body>
  
  <script> 
    let age = 18; // correct
    let age1 = 18; // correct
    let _age = 18; // correct

    // let 1age = 18; //  Error, cannot start with a number
    let $age = 18; // correct
    let Age = 24; // Correctly, it is a different variable from lowercase age
    // let let = 18; //  Error, let is a keyword
    let int = 123; // Not recommended. int is a reserved word
  </script>
</body>
</html>

array

  An Array is one that can hold multiple values in order

Declaration syntax:

  let Array name = [Data 1.Data 2, data 3, data 4]
  let arr = ['Little Joe', 'Lv Bu', 'Bridge', 'Fei Zhang', 'Flying car','train']

  Data is saved in order, and each data has its own number

The number in the computer starts from 0, so Xiao Qiao's number is 0, the label of the bridge is 2, and so on

In an array, data is also called subscript and index

Arrays can store any type of data

Value syntax:

let week = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday',]
        document.write(week[6])

The value of this string of code is Sunday

Length of array

The length of the array is obtained by length

        let arr = ['Little Joe', 'Lv Bu', 'Bridge', 'Fei Zhang', 'Flying car','train']
         console.log = (arr.length)

 

data type

Computer programs can process a large amount of data. In order to facilitate data management, the data are divided into different types:

Note: the data type is detected by the typeof keyword

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - data type</title>
</head>
<body>
  
  <script> 
    // Check what type of data 1 is, and the result is number
    document.write(typeof 1);
  </script>
</body>
</html>

3.1 digital type

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - data type</title>
</head>
<body>
  
  <script> 
    let score = 100; // positive integer
    let price = 12.345; // decimal
    let temperature = -40; // negative

    document.write(typeof score); // The result is number
    document.write(typeof price); // The result is number
    document.write(typeof temperature); // The result is number
  </script>
</body>
</html>

Note: in JavaScript, decimals, negative numbers, and integers are all numeric types

3.2 string type

Data wrapped in single quotation marks (''), double quotation marks ('') or back quotation marks are called strings. There is no essential difference between single quotation marks and double quotation marks. Single quotation marks are recommended. (` `)

matters needing attention:

  1. Either single quotation marks or double quotation marks must be used in pairs

  2. Single quotation marks / double quotation marks can be nested with each other, but they are not nested with themselves. Either the outer single and the inner double, or the outer double and the inner single

  3. It can be used if necessary

  4. Escape character \, output single quotation mark or double quotation mark

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - data type</title>
</head>
<body>
  
  <script> 
    let user_name = 'Xiao Ming'; // single quotes 
    let gender = "male"; // Use double quotation marks
    let str = '123'; // It looks like a number, but when it is wrapped in quotation marks, it becomes a string
    let str1 = ''; // This is called an empty string
		
    documeent.write(typeof user_name); // The result is string
    documeent.write(typeof gender); // The result is string
    documeent.write(typeof str); // The result is string
  </script>
</body>
</html>

String splicing  

  //  Prepare an input box, and then use a variable to store the data in the input box
        // Then print the variable that stores this input box, and the inside shows: I'm xx years old, spliced with string   
        let age = prompt('Please enter age')
        document.write('I've been here this year' + age + 'Years old')

Function: concatenate strings and variables

Template string

Symbols: backquotes   '  `` '

When splicing variables, use ${}     Variables are enclosed in parentheses

  // Prepare two input boxes, and then prepare two variables to accept the data entered by the user
        let unme = prompt('Please enter your name')
        let age = prompt('Please enter your age')
        // Then use the template string to splice, and then prepare a variable to receive
        let me = `hello everyone,My name is ${unme},I this year ${age}Years old`
        document.write(me)

 

3.3 boolean type (key)

When it indicates positive or negative, the corresponding data in the computer is boolean type data. It has two fixed values, true and false. For positive data, use true and for negative data, use false.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - data type</title>
</head>
<body>
  
  <script> 
    //  Is Mr. pink handsome? Answer yes or no
    let isCool = true; // Yes, I fell to death!
    isCool = false; // No, the man with the horse pole!

    document.write(typeof isCool); // The result is boolean
  </script>
</body>
</html>

undefined (unassigned)

Generally, it is unassigned data. Only variables are declared without assignment. The type of variables is undefined by default

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - data type</title>
</head>
<body>
  
  <script> 
    // Only variables are declared and assigned
    let tmp;
    document.write(typeof tmp); // The result is undefined
  </script>
</body>
</html>

  Note: the value of a variable in JavaScript determines the data type of the variable.

null (empty type)

let obj = null   // nul is assigned, but the content is empty

null   and   undefined differences

undefined: indicates that there is no assignment

null: indicates that the value is assigned, but the content is empty

Null official explanation: treat null as an object not created for

Type conversion

In JavaScript, data is divided into different types, such as numeric value, string, Boolean value and undefined. In the process of actual programming, there is a conversion relationship between different data types.

Implicit conversion

When some operators are executed, the system automatically converts the data type, which is called implicit conversion.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Basics - Implicit conversion</title>
</head>
<body>
  <script> 
    let num = 13; // numerical value
    let num2 = '2'; // character string

    // The result is 132
    // The reason is that the numerical value num is converted into a string, which is equivalent to '13'
    // Then + splices the two strings together
    console.log(num + num2);

    // The result is 11
    // The reason is that the string num2 is converted to a numeric value, which is equivalent to 2
    // Then subtract the value 2 from the value 13
    console.log(num - num2);

    let a = prompt('Please enter a number');
    let b = prompt('Please enter another number');

    alert(a + b);
  </script>
</body>
</html>

Note: as long as one of the two sides of the + sign is a string, the other side will be converted to string form. Arithmetic operators other than the + sign, such as - * /, will convert the data to digital type

A '+' sign in front of the value can be converted to the Number type Number

Display conversion

Write your own code to tell the system what type to turn to

To digital:

Number (data)

Convert to numeric type

If the string contains a number, the result will be NaN (Not a Number) when the conversion fails, that is, it is Not a Number

NaN is also data of type Number, representing non numbers  

Parselnt (data): only integers are retained

parseFloat (data): you can keep decimals

Convert to character type:

String (data)

Variable. ToString (base)

Topics: Javascript