avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • Resume
  • Archives
  • Categories
  • Photos
  • Music



{{ date }}

{{ time }}

avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • 主页
  • Resume
  • Archives
  • Categories
  • Photos
  • Music

JavaScript Basics

  2023-06-05        
字数统计: 1.9k字   |   阅读时长: 11min

JavaScript Basics

JavaScript is a high-level, interpreted programming language that powers dynamic behavior on the web. It’s an essential skill for frontend development.

Introduction to JavaScript

JavaScript (JS) enables interactive web pages and is an essential part of web applications. It was created in 1995 by Brendan Eich and has since become one of the world’s most popular programming languages.

Where JavaScript Runs

  • Browser: Client-side JS runs in the user’s browser
  • Server: Node.js allows JS to run on servers
  • Mobile Apps: Frameworks like React Native use JS for mobile development
  • Desktop Apps: Electron enables JS-powered desktop applications

Setting Up JavaScript

In HTML

1
2
3
4
5
6
7
<!-- Internal JavaScript -->
<script>
console.log("Hello, World!");
</script>

<!-- External JavaScript -->
<script src="script.js"></script>

Console

You can also run JavaScript in the browser’s developer console (F12 or Right-click > Inspect > Console).

Variables and Data Types

Variable Declaration

There are three ways to declare variables:

1
2
3
4
5
6
7
8
9
10
// var - function-scoped (older way)
var age = 25;

// let - block-scoped, can be reassigned
let name = "John";
name = "Jane"; // Valid reassignment

// const - block-scoped, cannot be reassigned
const PI = 3.14159;
// PI = 3; // Error: Assignment to constant variable

Primitive Data Types

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// String - text
let greeting = "Hello, World!";
let phrase = 'JavaScript is fun';
let template = `My name is ${name}`; // Template literal

// Number - integers and floating points
let integer = 42;
let float = 3.14;
let scientific = 2.998e8; // Scientific notation

// Boolean - true or false
let isActive = true;
let isComplete = false;

// Undefined - variable declared but not assigned
let undefinedVar;
console.log(undefinedVar); // undefined

// Null - intentional absence of value
let emptyValue = null;

// Symbol - unique and immutable
const uniqueID = Symbol('id');

// BigInt - for integers larger than Number can handle
const bigNumber = 9007199254740991n;

Checking Types

1
2
3
4
5
6
7
typeof "Hello"; // "string"
typeof 42; // "number"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (this is a known JavaScript quirk)
typeof Symbol('id'); // "symbol"
typeof 10n; // "bigint"

Complex Data Types

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Object - collection of key-value pairs
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
isEmployed: true,
greet: function() {
return `Hello, my name is ${this.firstName}`;
}
};

// Accessing object properties
console.log(person.firstName); // Dot notation
console.log(person["lastName"]); // Bracket notation
console.log(person.greet()); // Method call

// Array - ordered collection of values
let colors = ["red", "green", "blue"];
let mixed = [1, "two", true, { id: 4 }]; // Can hold different types

// Accessing array elements (zero-indexed)
console.log(colors[0]); // "red"
console.log(colors.length); // 3

// Function - reusable block of code
function add(a, b) {
return a + b;
}

// Arrow function
const subtract = (a, b) => a - b;

// Date
const today = new Date();

Operators

Arithmetic Operators

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let a = 10;
let b = 3;

let sum = a + b; // Addition: 13
let difference = a - b; // Subtraction: 7
let product = a * b; // Multiplication: 30
let quotient = a / b; // Division: 3.33...
let remainder = a % b; // Modulus (remainder): 1
let exponent = a ** b; // Exponentiation: 1000

// Increment/Decrement
let counter = 5;
counter++; // Equivalent to: counter = counter + 1
counter--; // Equivalent to: counter = counter - 1

Assignment Operators

1
2
3
4
5
6
7
8
9
let x = 10; // Basic assignment

// Compound assignment
x += 5; // x = x + 5
x -= 3; // x = x - 3
x *= 2; // x = x * 2
x /= 4; // x = x / 4
x %= 3; // x = x % 3
x **= 2; // x = x ** 2

Comparison Operators

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let a = 5;
let b = "5";

// Equal (value)
a == b; // true (converts types before comparison)

// Strict equal (value and type)
a === b; // false (different types)

// Not equal
a != b; // false

// Strict not equal
a !== b; // true

// Greater/less than
a > 4; // true
a < 10; // true
a >= 5; // true
a <= 5; // true

Logical Operators

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let isAdult = true;
let hasPermission = false;

// AND - both must be true
isAdult && hasPermission; // false

// OR - at least one must be true
isAdult || hasPermission; // true

// NOT - inverts boolean value
!isAdult; // false
!hasPermission; // true

// Short-circuit evaluation
let name = null;
let displayName = name || "Anonymous"; // "Anonymous"

Control Flow

Conditional Statements

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// if statement
let age = 18;

if (age >= 18) {
console.log("You are an adult");
}

// if-else statement
if (age >= 18) {
console.log("You are an adult");
} else {
console.log("You are a minor");
}

// if-else if-else statement
if (age < 13) {
console.log("Child");
} else if (age < 18) {
console.log("Teenager");
} else {
console.log("Adult");
}

// Ternary operator - condition ? expressionIfTrue : expressionIfFalse
let status = age >= 18 ? "Adult" : "Minor";

// switch statement
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Another day");
}

Loops

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// for loop
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}

// while loop
let count = 0;
while (count < 5) {
console.log(count); // 0, 1, 2, 3, 4
count++;
}

// do-while loop (runs at least once)
let num = 0;
do {
console.log(num); // 0, 1, 2, 3, 4
num++;
} while (num < 5);

// for...of loop (for iterables like arrays)
let fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
console.log(fruit); // "apple", "banana", "cherry"
}

// for...in loop (for object properties)
let person = { name: "John", age: 30, job: "developer" };
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}

// break and continue
for (let i = 0; i < 10; i++) {
if (i === 3) continue; // Skip this iteration
if (i === 7) break; // Exit the loop
console.log(i); // 0, 1, 2, 4, 5, 6
}

Functions

Function Declaration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Basic function declaration
function greet(name) {
return `Hello, ${name}!`;
}

console.log(greet("Alice")); // "Hello, Alice!"

// Function with default parameters
function greetWithDefault(name = "Guest") {
return `Hello, ${name}!`;
}

console.log(greetWithDefault()); // "Hello, Guest!"

// Function with multiple parameters
function calculateArea(length, width) {
return length * width;
}

console.log(calculateArea(5, 10)); // 50

Function Expressions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Function expression (anonymous)
const add = function(a, b) {
return a + b;
};

// Named function expression
const subtract = function sub(a, b) {
return a - b;
};

// Arrow functions
const multiply = (a, b) => a * b;

// Multi-line arrow function
const divide = (a, b) => {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
};

Function Scope

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Global scope
let globalVar = "I'm global";

function exampleFunction() {
// Function scope
let localVar = "I'm local";
console.log(globalVar); // Accessible
console.log(localVar); // Accessible
}

exampleFunction();
console.log(globalVar); // Accessible
// console.log(localVar); // Error: localVar is not defined

// Block scope with let/const
if (true) {
let blockVar = "I'm in a block";
const anotherBlockVar = "Me too";
var notBlockScoped = "I'll leak out"; // var is not block-scoped
}

// console.log(blockVar); // Error
// console.log(anotherBlockVar); // Error
console.log(notBlockScoped); // "I'll leak out" - accessible!

Higher-Order Functions

Functions that take other functions as arguments or return them:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Function as an argument
function executeOperation(operation, a, b) {
return operation(a, b);
}

const result = executeOperation(add, 5, 3); // 8

// Returning a function
function createMultiplier(factor) {
return function(number) {
return number * factor;
};
}

const double = createMultiplier(2);
console.log(double(10)); // 20

Working with Arrays

Array Methods

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
let fruits = ["apple", "banana", "cherry"];

// Basic array operations
fruits.push("orange"); // Add to end: ["apple", "banana", "cherry", "orange"]
fruits.pop(); // Remove from end: ["apple", "banana", "cherry"]
fruits.unshift("mango"); // Add to beginning: ["mango", "apple", "banana", "cherry"]
fruits.shift(); // Remove from beginning: ["apple", "banana", "cherry"]

// Finding elements
fruits.indexOf("banana"); // 1
fruits.includes("cherry"); // true

// Transforming arrays
let upperFruits = fruits.map(fruit => fruit.toUpperCase()); // ["APPLE", "BANANA", "CHERRY"]
let longFruits = fruits.filter(fruit => fruit.length > 5); // ["banana", "cherry"]
let allLengths = fruits.reduce((total, fruit) => total + fruit.length, 0); // Sum of all lengths

// Iterating
fruits.forEach(fruit => console.log(fruit));

// Sorting
fruits.sort(); // Alphabetical sort: ["apple", "banana", "cherry"]
fruits.reverse(); // Reverse: ["cherry", "banana", "apple"]

// Slicing and splicing
let citrus = fruits.slice(1, 3); // Shallow copy of portion: ["banana", "cherry"]
fruits.splice(1, 1, "blueberry", "blackberry"); // Remove and insert: ["apple", "blueberry", "blackberry", "cherry"]

Working with Objects

Object Methods

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};

// Getting information
Object.keys(person); // ["firstName", "lastName", "age"]
Object.values(person); // ["John", "Doe", 30]
Object.entries(person); // [["firstName", "John"], ["lastName", "Doe"], ["age", 30]]

// Checking properties
person.hasOwnProperty("age"); // true

// Adding/modifying properties
person.email = "john@example.com";
Object.assign(person, { phone: "123-456-7890", age: 31 }); // Updates age, adds phone

// Preventing modifications
const frozen = Object.freeze({ x: 1, y: 2 }); // Cannot be modified
const sealed = Object.seal({ a: 1, b: 2 }); // Properties can't be added/removed but can be modified

Object Destructuring

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const user = {
id: 1,
displayName: "jdoe",
fullName: {
firstName: "John",
lastName: "Doe"
}
};

// Basic destructuring
const { id, displayName } = user;
console.log(id); // 1
console.log(displayName); // "jdoe"

// Nested destructuring
const { fullName: { firstName, lastName } } = user;
console.log(firstName); // "John"

// Default values
const { admin = false } = user;
console.log(admin); // false

// Renaming
const { displayName: username } = user;
console.log(username); // "jdoe"

Error Handling

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// try...catch
try {
// Code that might throw an error
const result = nonExistentFunction();
} catch (error) {
console.error("An error occurred:", error.message);
} finally {
// Code that always runs
console.log("This always executes");
}

// Throwing custom errors
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero");
}
return a / b;
}

try {
console.log(divide(10, 0));
} catch (error) {
console.error(error.message); // "Division by zero"
}

JavaScript Best Practices

  1. Use strict mode to catch common coding errors:

    1
    2
    'use strict';
    // Your code here
  2. Prefer const/let over var for more predictable scoping

  3. Use meaningful variable and function names for better readability

  4. Add comments for complex logic, but make code self-documenting when possible

  5. Handle errors appropriately using try/catch

  6. Avoid global variables to prevent namespace pollution

  7. Use === and !== instead of == and != to avoid unexpected type coercion

  8. Use default parameters instead of checking for undefined

  9. Use template literals for string concatenation

  10. Use array and object destructuring for cleaner code

Learning Resources

  • MDN JavaScript Guide
  • JavaScript.info
  • Eloquent JavaScript
  • freeCodeCamp JavaScript Course
  • Web Development
  • JavaScript
  • Programming

扫一扫,分享到微信

微信分享二维码
JavaScript Advanced Concepts
CSS Layout & Responsive Design
目录
  1. 1. JavaScript Basics
    1. 1.1. Introduction to JavaScript
      1. 1.1.1. Where JavaScript Runs
    2. 1.2. Setting Up JavaScript
      1. 1.2.1. In HTML
      2. 1.2.2. Console
    3. 1.3. Variables and Data Types
      1. 1.3.1. Variable Declaration
      2. 1.3.2. Primitive Data Types
      3. 1.3.3. Checking Types
      4. 1.3.4. Complex Data Types
    4. 1.4. Operators
      1. 1.4.1. Arithmetic Operators
      2. 1.4.2. Assignment Operators
      3. 1.4.3. Comparison Operators
      4. 1.4.4. Logical Operators
    5. 1.5. Control Flow
      1. 1.5.1. Conditional Statements
      2. 1.5.2. Loops
    6. 1.6. Functions
      1. 1.6.1. Function Declaration
      2. 1.6.2. Function Expressions
      3. 1.6.3. Function Scope
      4. 1.6.4. Higher-Order Functions
    7. 1.7. Working with Arrays
      1. 1.7.1. Array Methods
    8. 1.8. Working with Objects
      1. 1.8.1. Object Methods
      2. 1.8.2. Object Destructuring
    9. 1.9. Error Handling
    10. 1.10. JavaScript Best Practices
    11. 1.11. Learning Resources

150 篇 | 131.7k
次 | 人
这里自动载入天数这里自动载入时分秒
2022-2025 loong loong | 新南威尔士龙龙号