Home
Posts
Article
Encyclopedia
Garden
Set
English
Followed
+
Follow
The garden is empty ~
Have not added flowers yet.
Posts (56)
养花风水
9 hours ago
养花风水

Creating Interactive Forms Using JavaScript

Forms play an integral role in web development. They allow users to provide data, make transactions with the sites, and carry out other functions, for example, signing up or in, giving feedback and so on. Creating forms has been made a piece of cake by HTML, however, the most interesting bits in creating forms are made possible by the use of Javascript. This means that forms created using Javascript can have moving parts, for example, elements inside the form can be changed, validated, or updated depending on the user's interactions. In this article, we will dive deeper into the world of Javascript and see how it can be applied to make forms more engaging.

Deciphering the Anatomy of a Form

As far as HTML is concerned, a typical form has a number of input elements such as text boxes, radio buttons, check boxes, a drop box and a submit button. Such elements are all enclosed within a tag called `
`. The primary objective of a form is to gather user details, which is why the `` tag also has the `action` and `method` attributes that help to identify where and how the details provided in the form will be forwarded once the form is submitted. But for a form to be engaging then Javascript has to be implemented.

We'll work with the HTML form:

Basic HTML Form

<form id="contactForm">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
  <button type="submit">Submit</button>
</form>


The HTML code above demonstrates a basic form with input fields for a name, email, and a submit button. The way the functionality is designed very simply, when the data is filled, the page gets refreshed and the information filled in the form is sent over. But thanks to JavaScript we have a chance to reshape it.

Enhancing Usability Through Javascript

It provides a structural base however forms are made interactive using JavaScript. Within the JavaScript, tasks can be set in order such as form input requirement checking, auto filling forms, and content replacement or adding without reloading the page.

1. Filling out the Form

Filling the form allows the users to put in relevant information and is completed after the requirements are checked. Before you send the filled in form to the server. Some of the things to look out for are making sure all required fields have some values filled in and/or the email address is in a valid format. And this is where the use of JavaScript comes along.

Form Validation Example

document.getElementById("contactForm").addEventListener("submit", function(event) {
    let name = document.getElementById("name").value;
    let email = document.getElementById("email").value;
    if (name === "" || email === "") {
        event.preventDefault();
        alert("All fields must be filled out.");
    }
});


In the above examples , the `submit` event listener checks the name and email before sending the form, so these fields are not empty. If there is any blank space on the name and email field , the `event.preventDefault()` method will cancel the submission of the form using an alert.


2. Input feedback on real-time basis

Apart from checking the validation of the form after the submission, form submission can also be a feature which allows to give feedback on real time to the users while they are filling the form, for instance highlighting correctly filled fields or where the user has filled in data incorrectly, or even providing feedback on whether the user's email address is correct or not.

Real-Time Email Validation Example

document.getElementById("email").addEventListener("input", function() {
    let email = this.value;
    let emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,6}$/;
    if (emailPattern.test(email)) {
        this.style.borderColor = "green"; // Valid email
    } else {
        this.style.borderColor = "red"; // Invalid email
    }
});


This script takes into consideration the validity of the email format when a user changes the email input. In case the email structure is corrected the border of the email input will be colored green, in the opposite case the border will be red. This will not only help users comply with the format but also visualize what is needed.

3. Adaptive Form Fields

Java,Script must be the code,among other the code which enables form fields to be usably altered through inserting key elements. For instance, if a customer wishes other fields to appear on the form, they can, in turn, add/subtract fields.

Adaptive Form Fields Example

document.getElementById("newsletter").addEventListener("change", function() {
    let newsletterField = document.getElementById("newsletterType");
    if(this.value =="yes") {
        newsletterField.style.display = "block"; // Show newsletter type field
    } else {
        newsletterField.style.display = "none"; // Hide it if "No" is selected
    }
});


In this scenario, the consumers specify whether they wish to receive the newsletter, in which case a new field requesting them to specify the type of newsletter they would like to receive appears. It is the capability of JavaScript that makes this kind of dynamic change without refreshing the page.

4. Submission of Form

After all the required fields in the form have been filled and the form data validated then you can proceed to getting the form submitted. In the conventional way, sending a form would imply sending the data to the server and the page being reloaded; with the help of JavaScript this is not necessary, it is now possible to send the form data even without reloading the page enabling better user experience.

AJAX Form Submission Example

document.getElementById("contactForm").addEventListener("submit", function (event) {
    event.preventDefault();
    const formData = new FormData(this);
    fetch("/submit-form", {
        method: "POST",
        body: formData
    })
    .then((response) => response.json())
    .then((data) => {
        alert("Submit form successfully!");
    })
    .catch((error) => {
        alert("An error occurred in course of submission.");
    });
});


In this case after a form was submitted, its data was sent to the server using the `fetch` method without refreshing the browser. As a result the user gets a success or error message depending on what the server sends back.

0
0
Article
养花风水
9 hours ago
养花风水
A number of new features made their ways into javascript with the introduction of its gallant version ECMAScript 6 or ES6. These features worked towards the goal of creating a language that's powerful, abstract and easy with great effectiveness. It is recommended for anyone who is seeking to bridge their knowledge in javascript or is starting out to know these main points of ES6. This article's focus will be shifted to some of these features along with their effect on the cutting edge javascript development.

Let and Const

As of writing this article, 'var' was the only keyword previously available to create variables in JavaScript. Although the `var` keyword was useful for declaring variables, it also came with negative aspects concerning scope and hoisting which can create bugs and make codes more messy than they need to be. Two new ways of declaring variables were introduced with the enactment of ES6. These were `let` and `const`.

1. Let: Block scoped variable can be accessed only inside the block in which they were declared, be it a loop or an if statement, and it can be done through the use of the keyword `let`. This overcomes the potential complications offered by `var`, as the scope of the variable is more easily understood.

2. Const: It is worth noting that Const is a nominative program that allows to declare constants which means that these variables are never changed, they are initialized once and for all. This turns out to be less cumbersome while dealing with read-only variables thus increasing the readability of the code by preventing reassignment of a variable by mistake.

Arrow Functions

One of the major features of ES6 which is so popular and in fact everywhere is the arrow function. An arrow function is a special type of function that can enable you to access global variables and have a different context 'this'. This makes them very effective when working with functions or callbacks in objects.

Arrow functions use the syntax '=>'. For example:

Arrow Function Example

let add = (a, b) => a + b;


In this illustration we can say that the arrow function added the benefit of only more parsers seeing that it effectively behaves like a standard function. Perhaps the most noteworthy of all is how arrow functions are able to bind the value of `this` scope passed as an argument during its parent invocation which is quite required in event handling or callback situations.

Template Literals

The other most valuable feature introduced with ES6 is SaaSits easy for a user to use template literals. Instead of quotation template literals allows you to use placeholders along with backticks.

For example:

Template Literals Example

let name = "Alice";
let greeting = `Hello, ${name}!`;


What made the context even more interesting was the quote say hello to Alice. Instead of saying hello to Alice, string concatenation is long gone. Because multi-line strings are supported, longer texts that span several paragraphs are made easier to work with.


Destructuring

Another interesting topic that was added to ES6 is Destructuring. When faced with the problem of more optimal ways to unpack values from objects or arrays and write them in variables, ES6 provided a solution to the pain. Rather than reaching for the extreme method of indexing or dot notation, Use of compact form makes the code easier to understand.

For arrays:

Array Destructuring Example

let numbers = [1, 2, 3];
let [a, b, c] = numbers;


For objects:

Object Destructuring Example

let person = { name: "John", age: 30 };
let { name, age } = person;


Writing these statements at the top, the journalist tackles the features of many programming languages, especially those with object-oriented characteristics; the feature is referred to as Pointers.

Classes

Es6 classes only serve to simplify the understanding of smearing for many of us. Objects can be summed up with blueprints methods and inheritance, which of course an architect would like to hope such a simple concept can hardly bring new artistic styles.

A basic class can be defined like this:

Class Example

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    greet() {
        console.log(`Hello, my name is ${this.name}`);
    }
}
let person = new Person("Alice", 25);
person.greet(); // Outputs: Hello, my name is Alice


So far, the built-in JavaScript class examples seem to be an improvement in clarity and structure over the previous prototype-based inheritance model.

Zero Parameters

Previously in ES6, it was possible to use default values for function parameters, as using default values required a function to be invoked with a set value.

Default Parameters Example

function greet(name = "Guest") {
    console.log(`Hello, ${name}!`);
}


As seen in the example, nothing is passed to the `greet` function, so `name` will take on the default value of `"Guest"` in this case. This means we need not have any manual checks or conditional statements inside it.

Rest and Spread Operators

In programming, the sole purpose of flaws is to persuade the two most powerful operators 'rest operator' (i.e '…') and 'spread operator' (i.e. '…') which merge all flaws into the curtains.

1. Rest Operator: The rest parameter makes it possible to pack multiple values into a single array and uses the arrays of the function parameters.

Rest Operator Example

function sum(...numbers) {
    return numbers.reduce((acc,num) => acc + num),0);
}


Here, `numbers` that are parameters of the `sum` function are packed into one array.

2. Spread Operator: The spread operator, the reverse of the rest operator, packs certain properties of arrays or objects into a new entity of its own. It is useful while invoking methods or while declaring new arrays or objects.

Spread Operator Example

let arr = [1, 2, 3];
let newArr = [...arr, 4, 5];


So here, all the values inside 'arr' along with newly added '4' and '5' have been incorporated into `newArr`.

Modules

JavaScript had no concept of modules prior to ES6. The major advantage of modules is in the organization and maintainability of a large code base as you can partition and decompose your code into smaller and more manageable files.

Example of how to export a function or variable declared in a module is as follows:

Exporting Module Example

// math.js 
export function add(a, b) {
    return a + b;
}


And to import the exported function into another file, it is done as follows:

Importing Module Example

// app.js
import { add } from './math.js';
console.log(add(2, 3)); // Output: 5


In computer programming, especially in JavaScript, modules are very handy as they provide an organized way of writing code and limit the complications that arise due to global variables and namespace pollution.

Promise

Promises are a new feature that was added in ECMAScript 6 to work with functions with asynchronous execution. A promise is an implicit declaration that a certain value may not be available at this point in time but sometime in the future it would be resolved and there would be a value. Whenever an asynchronous operation is to be performed, using promises is much easier due to the fact that they can be chained together with the use of the `.then()` and `.catch()` methods.

Promise Example

let myPromise = new Promise((resolve, reject) => {
    let success = true;
    if (success) {
        resolve("Task completed successfully");
    } else {
        reject("Task failed");
    }
});

myPromise.then(result => {
    console.log(result);
}).catch(error => {
    console.log(error);
});


0
0
Article
养花风水
9 hours ago
养花风水
The aspect of how data can be managed in a web application is among the key features any web developer has to master. One of the most widely adopted formats that is used is JSON (Javascript Object Notation). JSON has a lightweight structure, it is human friendly, and it can be easily converted into javascript objects. The format is practically a standard when it comes to exchanging information between a client and a web server. Thus, to manage data connections, when developing an application, be it an API or a data's inner storage, working with JSON is fundamental.

This article covers the basic concepts related to JSON, its relationship with JavaScript, and the use of JSON within an application.

What is JSON?

JSON is short for Javascript Object Notation. This is a textual format used to represent structured data using the notion of objects which are composed of a set of key-value pairs. Although it is a language neutral format, it is mostly used with Javascript because it is quite straightforward to serialize javascript objects into JSON format and the other way around.

An ordinary object in JSON is constructed using multiple pairs of keys and values. In every single case, the keys are in strings while values may include: String , Number , Arrays , Booleans or even other objects. All of these key statutes are enclosed in a pair of curly braces "{ }" and each statute is separated from the other regulation by a comma. As an example here is a basic format for a JSON object:

Basic JSON Object Example

{"name": " "John","age":"30","isStudent" - false}

In this example:

- For example, "name" can be identified as the Key while "Jewelo's Shining" is the value for that key.

- "age" has the value of 30 and can also be defined as a key.

- While isStudent has a value of false

JSON Syntax Rules

A few essential elements must be maintained while creating a JSON code to operate it effectively and accurately:

1. The object is always kept inside braces `{ }`.

2. Array is used to keep in Partnerhesis `[ ]` along with items that have multiple values.

3. Every Key is required to be a string enclosed inside double quotations i.e. `""`.

4. For every value: it can be either a boolean value, an array of strings, an object, a number or a null value.

5. Every Key- value pair has a relationship which is defined with a semi colon i.e. carved out with` : `.

You can find a more complicated JSON representation that contains arrays and objects:

Complex JSON Example

{ "name": "Alice","age": 25,"hobbies": ["reading", "hiking", "coding"],"address": {"street": "123 Maple St.","city": "Wonderland"}}

In this example, `hobbies` is an array and the other key called `address` is an object.

JSON to JS objects

When dealing with JSON in JavaScript, one of the major requirements is to transform JSON data into something that will be a JavaScript object and can be easily used. This is achieved using the `JSON.parse()` method which is provided by the language.

The `JSON.parse()` method uses one parameter which is a JSON string and returns a suitable JavaScript object. We demonstrate the conversion of a JSON string to a JavaScript object in the snippet below:

Parsing JSON to JavaScript Object

let jsonString = '{"name": "Alice", "age": 25}';
let obj = JSON.parse(jsonString);
console.log(obj.name);  // Output: Alice
console.log(obj.age);   // Output: 25

In the example above, the variable `jsonString` contains a string in a JSON format and enclosed in double quotes. The `JSON.parse()` approaches this string as a JavaScript object allowing `name` and `age` to be properties of an object.


How To Convert Javascript Objects Into Json Format

There are instances when a server needs to receive data from a JavaScript code, or say a file needs to be stored, either ways, the content must be converted to a JSON format. Certainly, this can be done by making use of `JSON.stringify()` function, that is converting a JavaScript object to a JSON object's string.

With the following code, we will be able to apply the `JSON.stringify()` method.

Stringifying JavaScript Object to JSON

let person = {name: "Bob",age: 30,isStudent: false};
let jsonString = JSON.stringify(person);
console.log(jsonString);  // Display: '{"name":"Bob","age":30,"isStudent":false}'

This way, the method `JSON.stringify` transforms a JavaScript `person` variable which is a javascript object into a string in json format that can be sent to a server or saved within a file.

Retrieving And Sending JSON Objects Through Web Apps

In web development it won't be a surprise to say that APIs, that is Application Programming Interfaces, are all over and they tend to receive and transmit data in a JSON format. Although, it does seem rather common such as making an asynchronous request to a server.
One common way of retrieving JSON data is by using the `fetch()` function, which is an asynchronous request and returns a promise. Here is an instance of fetching a JSON data and utilizing it:

Fetching JSON Data Example

fetch("https://api.example.com/data")
.then(response => response.json())  // A method that converts the response body// as JSON, which is a response format to // note as well
.then(data => {
    console.log(data); // Add user defined logic
})
.catch(function (error){
    console.log("Error: " + error);
});

In this example, notice the following:

- An HTTP request is executed through the use of the `fetch()` function which passes the designated URL.

- In the `response`, JSON data is parsed and retrieved through the use of the `response.json()` method.

- A Javascript object is also retrieved in the form of a resultant object assigned to the variable 'data'.

- This object can now be used for further manipulating, editing, or displaying.

Manipulating JSON in Javascript on the Server-Side

In fact, javascript isn't limited to the client-side only. Node.js is one alternative where JavaScript handles the server-side client requests. Just like client-side java script, when using JavaScript server-side APIs or working with databases, JSON is also crucial. You may create, read or write JSON files in Node.js utilizing the built-in `fs` (file system) module.

Let's learn how to read and write JSON data with the `fs` module in Node.js with help of the following example:

Reading and Writing JSON in Node.js

const fs = require('fs');
// Reading JSON from a file
fs.readFile('data.json', 'utf8', (err, data) => {
    if (err) {
        console.log(err);
        return;
    }
    let jsonData = JSON.parse(data);  // Converts JSON string into JavaScript object    
    console.log(jsonData);
});
// Writing JSON to a file
let newPerson = { name: "Charlie", age: 28 };
fs.writeFile('newData.json', JSON.stringify(newPerson), 'utf8', (err) => {
    if (err) {
        console.log(err);
    } else {
        console.log("Data has been written to the file.");
    }
});

In this case:

- The `fs.readFile()` function takes the JSON data from a file and `JSON.parse()` function converts the JSON string data into JavaScript objects.

- `fs.writeFile()` function saves a file in which the JavaScript object is transformed into a JSON string using `JSON.stringify()`.

0
0
Article
养花风水
9 hours ago
养花风水
One of the most difficult concepts that you will encounter in programming is dealing with asynchronous operations. Asynchronous code management in Javascript is important since it helps the applications in such tasks like pulling data from the server, reading files, performing operations which require time. Javascript language facilitates this with the help of promises and use of the async await syntax.

We will provide an overview of these two terms,ones that you will often hear in JavaScript, promises and async/await and discuss their contribution to a better way of writing JavaScript.

What are Promises?

In the programming universe, it is often said that Javascript is the only true asynchronous programming language, this is due to the fact that Javascript contains a myriad of functionality and components that allow for deeper use tailoring such as TIMEOUTS. A promise is one of those components or components that allow an asynchronous request to be made from one component to another, javascript is built around the concept of promises whether you realize it or not it's blended within out the language the same way as Proxies are.

Javascript promises could be said as a Javascript object which aids in the commanding and controlling of other objects, whether they encourage progress or result in failure, depending on how you see them. The concepts behind Javascript promises are China based, using them is simple, generally two command code loops are constructed to issue commands, based on the objects attributes and the output one loop becomes primary enabling the two to speak and the message being sent rounds. This feature is monumental for building and enhancing further functionality down the line enabling far smoother dealing.

When working with asynchronous requests, for instance this could range from network requests to simple database calls, you wouldn't expect it to be instantaneous, hence functional codes are constructed to enable other operations to be carried out while the primary requests are outstanding, bands around the primary request will block secondary loops once that primary request output is recognized , allowing for clean and efficient coding without the use of excessive nested loops.

In computing, the outcome of a promise falls in one of the three categories:

1. Pending: A promise that is issued for the first time will be in the "pending" stage. An operation is still underway.

2. Fulfilled: A promise that has been successfully resolved. A result has been achieved and the operation is completed.

3. Rejected: A promise that has not reached its success is marked as rejected. It can also mean an error or failure was the cause.

The following syntax is used to create a promise: `new Promise()`. This syntax has a function called the executor, which encases the asynchronous task. The two parameters accepted by the executor function are `resolve` and `reject`. When `resolve` is invoked, the task was concluded successfully. However, if it fails, then the `reject` function initiates, indicating that the task has failed.

Here is the basic structure of a promise,

Promise Structure

let promise = new Promise(function(resolve, reject){
// Asynchronous operation
let success = false;
// A piece of code that determines if a success or failure simulation will be fired
if(success) {
    resolve("Operation was successful");  // The promise is fulfilled
} else {
    reject("Operation failed");  // The promise is rejected
}
});

promise
.then(function(result) {
    console.log(result); // If resolved, show the success message.
}).catch(function(error) {
    console.log(error); // If rejected, show the error message.
});
After completing the creation of the promise, you may, however, use the ".then ()" method to add functions to the piecing that you will carry out in the event in case the promise is satisfied. Utilizing the ".catch ()" function aids in solving complications that arise whenever the promise is unsatisfied.


How To Chain Promises

As observed, chaining multiple promises one after the other is made possible by the powerful Promises. Multiple asynchronous operations can be chained using `.then`. The successive asynchronous operations are invoked in the order in which they are supposed to be executed.

Here's an example of how chaining works:

Promise Chaining Example

fetchDataFromAPI().then(function(response) {
    return processData(response); // Returning new promise
})
.then(function(processedData) {
    return saveData(processedData); // Returning another promise
})
.catch(function(error) {
    console.log("Error: " + error);
});
In the above example, clearly we can see every other `then` block starts off with a new promise and whichever `then` block comes later can only be executed if the promise preceding it is completed. .Finally, Penny's shoes can only be ordered if – any of the promises in the chain are undone and fail the test, chain-fail bubble-matches shoes undying phones the success of an otherwise percent.

What is Async/Await?

As far as hybridizing the ways of handling asynchronous tasks is concerned, `async` and `await` in JavaScript go a step further, as they extend Pseudo Code, using pseudo logic and utilizing multiple tasks in order to expand for better overall performance of code.

- Function 'async': An 'async' function can be defined as that function which always results in a promise being returned. The definition of the 'async' keyword is also found before the function containing the definition, meaning that a function has the capacity to perform asynchronous operations directly.

- Await: 'Async' functions contain the 'await' keyword which is used to suspend the function's execution until the task is complete.

As a result of using 'await', one mustn't have to perform all the finicky handling of an unwrapped promise thanks to all the unhandled rejection mess. The biggest drawback of using Promises is their over complication. Instead of having multiple nested callback functions, which may be avoided when there is a promise, the use of 'try...catch' is essential every time a promise is created.

Below is a clear example illustrating the combined usage of `async` and `await` keywords at the same time:

Async/Await Example

async function fetchData() {
    let response = await fetch("https://api.example.com/data");
    let data = await response.json();
    return data;
}

fetchData().then(function(result){
    console.log(result);
}).catch(function(error){
    console.log("Error: " + error);
});
In this example, the `await` keyword defers the execution of the `fetchData()` function until the promised `fetch` call is completed and only then resumes the next line which is a `response.json()` call. Overall, controlling logic flow for asynchronous code is made a lot easier when using async/await compared to plain promises.

Async/Await for Error Handling

Another day you sit down to write code in JavaScript and you know you have to deal with errors. Errors are part of the reliable code and are crucial aspects that need management. Errors when using promises can be handled by the `.catch()` method. Answering the question `how async/await works`, promise errors using the `async/await` syntax you have to use `try...catch` blocks and it will be handled like normal synchronous code.

0
0
Article
养花风水
9 hours ago
养花风水
Every programming language comes with its set of challenges and errors. These errors may arise due to several reasons, such as incorrect syntax, an unexpected behavior of certain code, or even due to improper input from a user. Just as other languages, in JavaScript too, there are ways to detect, deal with and recover from such errors. It is due to the mechanisms of error handling that a program can work in a required manner even in the case of failure of some component or an external source.

In JavaScript, error handling is done via the use of the `try`, `catch`, `throw`, and `finally` constructs. These enable the programmer to write the code that is able to manage errors and prevents the program from closing down in an unexpected manner.

Categories Of Errors Found in Java Script

Before we get into particulars of error handling in Java, it is better to start with identification of types of errors or mistakes that are found in JavaScript. Looking at it generally, there are three broad division of errors found in JavaScript:

1. Haphazard Errors: These errors occur when the Java Script code is not written according to the correct grammar. For instance if an opening bracket is missed or a comma is out of place, syntax error will be raised by the browser and urge the code not to be successfully executed.

2. Runtime Errors: Runtime errors are those thrown up during the program execution. Missing values, invalid operations, and wrong logic are some of the factors which might result in such errors. An attempt to divide a number by zero is a common example of a runtime error.

3. Logical Errors: Logical errors are quite different from Syntax errors or Runtime errors. A logical error occurs in a situation when the program was able to run completely but at the end it produced faulty and/or results. It is somewhat easier for an executable code to exist without errors while employing logic but harder for a human to be able to detect this logical error embedded in it.

Even though it is quite unavoidable to prevent mistakes from occurring, JavaScript has many mechanisms that one can use to give graceful degradation.

The Try and Catch Statement

The `try` and `catch` statement is Javascript's favorite backbone. In this method one would be able to 'attempt' a particular code, and if that code does not run smoothly, then you use the 'catch' statement to run an alternate code in that case.

The structure is as follows:

try-catch Syntax

try { 
 // Code that may cause an error 
} catch (error) { 
 // Code to handle the error 
}
- Try Block: The part of the code that has the potential to throw an error is placed inside the `try` block. The code is run in normal manner and the `catch` block is executed only if no error occurs.

- Catch Block: Once you've made the syntax and language as per the required standard, proceed to verify and test it, if any bug occurs during such testing, JavaScript catches it in the catch block. The catch block takes an argument which is the error object and contains information such as why it has gone bad.

For a better understanding of this concept, let's illustrate with an example.

try-catch Example

try {
    let result = 10 / 0; // This will always raise an error of executing a divide by zero statement
} catch (error) {
    console.log("Error: " + error.message); // This will log the error message
}
In this example, the run time error is generated only when a division by zero attempt is made and then the respective error message is printed by the system.

The Throw Statement

Use the `throw` statement to introduce your own errors in javascript. It would make sense in practice if there is something that hasn't gone according to plan in your code, you can throw a custom error. You can employ the `throw` statement with either an error or a string to underline the error.

The syntax for throwing an error is:

Throwing a Custom Error

throw new Error("This is a custom error message");
By using the constructor of the `Error` object, you can add a message property to the error that states what went wrong. You can throw an error whenever you want based on your requirements whenever there is an unforeseen circumstance other than a runtime error or syntax error.

Below is the code throwing a custom error:

Throwing a Custom Error in a Function

function checkAge(age) { 
if (age < 18) { 
throw new Error("Age must be 18 or older."); 
} 
console.log("Age is valid"); 
} 
try { 
checkAge(16); 
} catch(error) { 
console.log(error.message); // Outputs: Age must be 18 or older. 
}
In this case, we call the `checkAge` method and pass an age less than 18, which will throw a custom error instead of going to the next console statement. This custom error can then be caught and piped to the `catch` block to be handled.

The Finally Block

In JavaScript, `finally` blocks can be added to run after a `try` or `catch` block without caring about whether an error was thrown or not. The `finally` block is particularly beneficial in instances where certain clean up tasks need to be performed at the end such as deleting temporary files or closing a file once the `try` block has been executed.

The way in which a `finally` block is used has the following syntax:

try-catch-finally Syntax

try {
    // Code with a chances of failing
} catch (error) {
    // Managing the error
} finally {
    // Code which runs regardless of code above throwing an error or not
}
No matter if the `try` block was successful in the above code or not, `finally` would run and the example uses that `finally` to hide the error that was previously caught by the `try` block. For instance, if you attempt to open a file without success, when using network applications, a resource could be created without the operation being effective.

try-catch-finally Example

try {
    let file = openFile("example.txt");
    // Perform some operations on the file
} catch (error) {
    console.log("An error occurred: " + error.message);
} finally {
    closeFile(file); // Close the file no matter the try block being a success or failure
}
In this case, since the error with the `try` block now has to be enforced within the `finally` block, this means the `try` block could forever or never be a success. The `finally` should enforce the last action which is to close the file and the `closeFile`'s functionality should be `finally` whether open or closed.


Error Objects

As an error occurs, an event will be generated in a JSON format which could be considered to be an object. This JSON object should contain such properties as `message` – an explanation as to what fails in the code which is caused by the `try` block.Most importantly about errors, everything that has an outline or that could contribute as a source to an error has to be a common factor such as `name` – This specifically contains the name of the source which scratches where the only part possible to throw an error is.

You can use these elements to see what caused the exception. For example:

Accessing Error Object Properties

try { var x = 10 / 0;} catch (error) {
console.log("Error name: " + error.name); //Produces: Error name: Error
console.log("Error message: " + error.message); //Produces: Error message: Infinity
console.log("Stack trace: " + error.stack); //So this returns the stack trace
}
0
0
Article
养花风水
9 hours ago
养花风水

Learn About JavaScript Arrays and Objects

When it comes to computer programming, data also has to be maintained and retrieved in a systematically effective manner. One of the key features of JavaScript is its ability to handle various forms of data structures. Out of all these, objects and arrays tend to be the most frequently used structures for data storage. Now both of these are basic parts of the JavaScript language, and are crucial in the development of active and user-friendly websites. In this article we are going to explain two Javascript data structures, their main features and how they are implemented using Javascript.

What are JS objects?

In JavaScript, this data structure is called objects and is used for grouping information and data about an entity or a person. They are handy and let you bundle analogous items of data together using key-value pairs. A key which can be also called a property is always a string, while the value characterises all other types of data including numbers, strings, arrays and objects among others.

Objects are models that imitate the real world and its aspects. For example, you can utilize an object to refer to a person with values such as: his or her name, age as well as occupation where those form the defining characteristics of the object.

An object in JavaScript is embodied in the form "{" using curly braces, containing key's and value's member separated by comma. Each key appears and is written with a colon. A value follows that colon.

To illustrate, a simple object with a book as its it may include:

Creating a Simple Object

let book = {
    title: "To Kill a Mockingbird",
    author:"Harper Lee",
    year:1960
};
In the above instance, the object `book` comprises three properties: `title`, `author` and `year`. Each one of these has a value assigned to it. For the property `title`, the value assigned is `"To Kill a Mockingbird"`; for the `author`, the area value is `"Harper Lee,"` and for `years`, the number assigned is `1960`.

Accessing and Modifying Object Properties

When an object is made, its properties can be accessed with the help of its definitions with dot notation or bracket notation methods.

1. Dot Notation: In this case, the property name is written immediately after a period (`.`).

Accessing Object Property with Dot Notation

console.log(book.title); // To Kill a Mockingbird
2. Bracket Notation: This is helpful when the property name is not constant (for example it is placed in some variable) or the property name has space or special characters.

Accessing Object Property with Bracket Notation

console.log(book["author"]); // Author: Harper Lee
A value can be assigned this way in order to change an existing property value:

Modifying an Object Property

book.year=1961; // Changes Year to 1961
console.log(book.year); // Year : 1961
A new property can be created in an object at anytime all that is needed is to assign the value to that property:

Adding a New Object Property

book.genre="Fiction"; // Creates new Property
console.log(book.genre); // Outputs: Fiction

What are JavaScript Arrays?

In JavaScript an Array is used to store ordered collections of values. An array may consist of a number of elements and each of the elements may be either a number, a string, an object or even another array. Arrays are zero-based index collections meaning they begin with a numeric index of 0.

Array structures in JavaScript can be represented using square brackets and separated by a comma. For example, one simple representation of an array in JavaScript is:

Creating a Simple Array

let colors = ["red", "blue", "green", "yellow"];

Thus, in this example it can clearly be observed that the `colors` array contains elements `red` `blue` `green` and `yellow`, which means this `colors` array comprises four items in it all of which can be accessed through their index positions with the first item `"red"` being zero index, the second item which is `"blue"` being first index and so on.

Accessing and Modifying Array Elements

The position of an item within an array is known as the index and based upon this index the individual elements in an array can be retrieved. However, with this there is a key difference between an array and an object with objects you can use both dot notation and bracket notation but in the case of arrays you will always have to use the bracket.

Accessing Array Elements

console.log(colors[0]); // Results in red
console.log(colors[2]); // Answer is green
A specific index can be assigned a new value — thus modifying an array element:

Modifying Array Elements

colors[1] = purple; // New value is purple for the second aspect (blue)
console.log(colors[1]); // The answer is: purple
You are free to place a new index pointing beyond the end of an array to include other elements:

Adding New Array Elements

colors[4] = 'orange'; // When combined with other colors makes orange fifth
console.log(colors[4]); // The answer is: orange

Comparing Relation of Objects and Arrays

Both objects and arrays are used to store a chunk of data but the difference is how they retrieve that data or even the organization of data in the first place. An object should be used when you want to store key-value pairs, where the key is a string and the value can be any data type. Objects are great for representing real life objects with their properties and their characteristics. Whereas, arrays are best suited for ordered collection of items where each item is pointed to by a number. Arrays are perfect for storing a list which has items in it such as: numbers, names or even objects.

Think about a situation when you are keeping records of a few books. Let's say you want to save information about these books in a key-value manner. For instance, the key could be `title`, `author`, `year`, etc. In that case, you would have to implement an array of objects. In this case, the array would contain the books and each element of the array would be one book. The properties of the array elements would be the details of the book.

Array of Objects Example

let books = [
            {
                title: "1984",
                author: "George Orwell",
                year: 1949
              },
              {
                  title: "Brave New World",
                  author: "Aldous Huxley",
                  year: 1932
              }
]
Here, for instance, `books` are made two items array after the modification and are array of objects where each object `title`, `author`, `year` are keys respectively.

Iterating Over Arrays and Objects

In JavaScript, there are arrays and objects and you can access their values by looping them.

1. Iterating over Arrays: The most common approach to run through an array is by using `for` statement or `forEach()`. For loop uses the index to run an array element and `forEach`, it automatically runs the entire array.

Looping Through an Array

for (let i = 0; i < colors.length; i++) {
    console.log(colors[i]);
}
As described in the first example in the next section, `for...in` is one of the methods that allow a developer to iterate through all the properties of an object.

Looping Through an Object

for (let key in book) {
    console.log(key + ": " + book[key]);
}
This method is simply iterating through the science of the object `book` and will display each property with its associated value of that property in the object.

0
0
Article
养花风水
9 hours ago
养花风水
As a part of the process of developing websites, one aim that you always strive to achieve is to make the end product interactive. This can primarily be done using events in JavaScript. This is because it is through events that web pages are able to respond to user inputs such as clicks and movements of the mouse, movement and strokes of the keyboard among many others. There are many ways in which these events can be managed with the help of JavaScript making it easier for developers to build interactive web applications. In this piece, we shall focus on what events are in JavaScript, how they work and how you can make use of events using event listeners to prevent users from interacting with your web page.

Events definition in Javascript

In regard to JavaScript, an event basically means every single interaction or action that the user or the browser makes use of within the webpage which mostly makes use of both the mouse and the keyboard. These events include such acts as:

- Clicking a button

- Moving the mouse

- Whenever a key on the keyboard is pressed

- Hovering an element

- Submitting a form

- Loading a web page

The events mentioned above are in terms of action that a web page will be able to respond to. When such actions occur, JavaScript can capture these events and execute specific code in response. This way, applications built in Java may be interactive and entertaining to use.

Types of Events

Various events occur in a web application depending on the actions performed by a user. Among the most frequent are the following:

- Click: Occurs when a mouse cursor clicks on a particular element.

- Mouseover: Occurs when the mouse pointer is positioned over an element.

- Mouseout: Occurs when the pointer is moved from over an element.

- Keydown: Occurs when a particular key on the keyboard is pressed

- Keyup: Occurs when a certain key of the keyboard is released.

- Submit: Occurs when a user submits a form.

- Load: Occurs when the page or an image is completely displayed.

- Focus: Occurs when an input field is clicked on.

The great advantage of these events is their effectiveness in ensuring user interactivity and the availability of multiple handling techniques in JavaScript

Event Listeners

In order to respond to events, JavaScript has event listeners. This is a function that waits for a certain action on an HTML tag. If an action takes place like you click on an element the function is executed. Event handlers of different types in JavaScript can be created as functions and attached to an HTML element as an event listener.

Adding The Listeners Of Events

In JavaScript, you can add event listeners to HTML elements with the `addEventListener()` method. With this method, you can tell the script which kind of events you are interested in, for example, "click" or "keydown", and which function will be executed when such an event occurs.

To provide an event listener the following steps should be followed:

addEventListener() Syntax

element.addEventListener(event, function, useCapture);
- `element`: The event listener will be added to that particular DOM element.

- `event`: The event type like "click" or "keydown".

- `function`: The function that should be executed as a listener for the event.

- `useCapture` (optional): It is a flag to tell whether during the capturing phase the event should be captured or not. The default value for this flag is `false`.

For example, to attach a click event listener to a button, you would write:

Adding Click Event Listener Example

let button = document.getElementById("myButton");

button.addEventListener("click", function () {
    alert("Button was clicked!");
});
In the above code, the event listener calls the function when there is a click on button with the ID `myButton` and the function shows an alert.

Event Propagation

An event at the top most document in the DOM tree and the event at the target and all the elements in between are what event propagations work on. There are two ways in which an event can propagate:

1. Capturing Phase: An event that travels down from the root down to the target element.

2. Bubbling Phase: A target element that travels all the way up the root.

In most cases, a bubbling phase is a type of event which gets executed first and this method only applies when there is a need to focus on a singular element in the event. So in layman terms an event in a tab will burn up as soon as the pointer hovers onto another element.

To illustrate, if the event from a child and parent target overlaps, the latter will always get their trigger later. Now here is a simple scenario, if you added two event listeners on the child and parent element then the child listener will go off first (during the bubbling phase).

The Event can be set off without alerting any other elements using the `stopPropagation()` method. This is handy when there is no need to merge other elements into the event and only a specific one suffices.


Event Object

An event object is created by the browser automatically as soon an event is initiated. The event object essentially has cool stuff about the type of event, which element caused it, and what else is related to the event.

You can have access to the event object if you declare it as a parameter in the event handler function. For instance:

Accessing Event Object

element.addEventListener("click", function(event) {
   console.log(event.type); // Will display the type of event which occurred, for example "click"
});
Some of the event object's properties which can be helpful are:

- `event.target`: A particular DOM element that raised the event is referred to as the event target.

- `event.clientX` and `event.clientY`: Mouse position in pixels with respect to the viewport.

- `event.key`: During a keyboard event, this is the key that was pressed.

Removing Event Listeners

Removing an event listener that has been added is sometimes required and JavaScript gives you the possibility to do so through the use of the `removeEventListener()` method. Just like its counterpart `addEventListener()`, `removeEventListener()` accepts the same parameters: the specific event and the callback.

For instance, if you need to delete a click event listener that has been previously assigned, you would write something like this:

Removing Event Listener Example

button.removeEventListener("click", myFunction);
Make sure to note that the one passed to `removeEventListener` must be identical to the same one that was passed to `addEventListener`. This explains why anonymous functions can't be removed in this way.

Event Delegation

The event delegation pattern is a useful pattern in making it easier to deal with events on several elements. Instead of attaching separate event listeners to each one of the elements, it is possible to attach a single event listener to a parent element. This parent element will receive events from its child elements and it is therefore possible to handle events in a lot of elements with a single event listener.

For instance, if there is a list of items and there is a need to detect when each item is clicked, instead of setting an event listener on every `<li>` element, an event listener can be placed on the outsourcing `<ul>` tag.

Event Delegation Example

let list = document.getElementById("myList");

list.addEventListener("click", function(event) {
    if (event.target.tagName === "LI") {
        alert("Item clicked: " + event.target.textContent);
    }
});
0
0
Article
养花风水
9 hours ago
养花风水

Functions in JavaScript: A Comprehensive Overview

The function is a concept that is in every discipline of programming in a particular way. With the functions, a programmer can turn segments of a code that accomplish specific tasks into pieces of code that can be used repeatedly. Functions in JavaScript are also very extensive and fundamental because they help in the structuring of the code. Whether you are thinking about making websites or building applications, it is imperative that you master how you can handle the creation of functions in JavaScript, as you will have to apply this knowledge frequently.

What does Function mean in Java Script?

A function in JavaScript is a piece of code that is associated with a specific operation, its given code. After a function has been created, there is no need to create it again, but instead, you can call it any time using the call or invoke keyword if you want to execute that function. Tasks are completed faster through the use of functions because there is no need to write the same source code continuously.

The input of a function also called 'argument' can be in the form of values or might be given and the output produced as a product return. Functions can be viewed as a low level building block of code that assists in creating highly structured programs or code in an aspect oriented way. Instead of attacking large tasks head on, when you have functions at your disposal, you could take them and divide them into small, more understandable tasks.

Introduction to Functions

First, to define a function in JavaScript you employ the keyword "function" followed by the name then add the parenthesis plus the braces. Therefore, whatever you want the function to execute will be added between the braces.

The syntax of the function from a high level looks like this.

Function Syntax

function functionName() {
    // Code you want to be run
}
For instance, a function might be defined say as "sayHello" in this format

sayHello Function Example

function sayHello() {
    console.log("Hello, world!");
}
In this instance, the function: `sayHello` has no arguments and when called it does one task which is outputting a sentence "Hello, World".

Invoking a Function

So, once a function is defined, the function can be called from anywhere in the code. Add the name of the function together with the parenthesis and this will invoke the function. Additionally, if the function expects arguments, those are also included in the parentheses while calling the function.

From the example above the procedure for invoking the `sayHello` function would be:

Invoking a Function

sayHello();//this will print to the console "Hello, World!"
So, when executing the program and the engine detects the function call, it will find the definition of the function and all code that is defined in the body of that function will be executed.

Arguments and Parameters

When calling a function, you may also notice the existence of parameters. Because they serve as placeholders, two terms need elaboration here. The first is when you supply a function with parameters or arguments; arguments are the values supplied to a function.

Each of the parameters is defined in the function declaration running the basic structure as before and placing the required items to be enclosed in a pair of brackets. For example, if a function is meant to greet a person by their name, it can be defined with a parameter called the `name` such as:

Function with Parameter Example

function greet(name) {
    console.log("Hello, " + name + "!");
}
In the case above, `name` is one of the parameters `greet` function contains. The next time an argument has been transferred to the function, before it is invoked, it will be assigned to the appropriate parameter, `name`, so it reads as follows:

Invoking Function with Argument

greet("John"); // Lets say John is a person whose details this program has his name

Moreover, in some instances, what has been explained above can be considered more generic; for instance, you are free to transfer random names that alter every consecutive time the function is called. This helps applications and programs that utilize this functionality to work more smoothly, as they do not require users to be limited in a blanket approach. For example:

Invoking Function with Different Arguments

greet("Alice"); // Outputs "Hello, Alice!"
greet("Bob"); // Outputs "Hello, Bob!"

Return Values

However, as some functions cannot cause things to be done and at the same time produce desired outputs, other functions do return a value by performing a calculation that has a specific necessity and sending or passing such a value to the part of the program or global scope that invoked the function. This is done using the `return` keyword.

The output of a function may be used outside of that given function owing to its return value. For example, suppose you wish to implement a function which calculates the sum of two values and displays the answer. In that case, you would define the function like so:

Function with Return Value Example

function add(a,b)
{
    return a + b;
}
Here, function `add` receives data two data – `a` and `b` – and computes their sum. You could then provide inputs and receive an output through the function as follows:

Invoking Function and Storing Result

let sum = add(5, 3); // sum will be now 8
console.log(sum); // Will print 8 on the console
Any result of the function call can be stored inside variables for later use. For instance, in the above example, the output of the computer could be saved in a variable called `sum`.

Function Expressions

The use cases of a function declaration were mentioned above, but along with that, function declaration is also possible using function expressions in javascript. The term function expression refers to defining a function and assigning that function to some variable.

Let's take this as an example:

Function Expression Example

const multiply = function(a, b) {
    return a  b;
};
In this case, the variable `multiply` holds a function which is capable of multiplying two numbers. This means you can call this function just like you would a function that was declared with the `function` keyword in javascript. it is used as shown in the example below.

Invoking Function Expression

console.log(multiply(4, 2)); // This will output 8
Function expressions are particularly valuable when you want to pass a function into another function, or to return a function from another function.

Arrow Functions

After the ES5 standard, arrow functions are one of the additions made to javascript ES6, arrow functions use a different way of writing functions in javascript in a more progressive and shortened form. An arrow function is a function expression accompanied by a pair of parentheses and an arrow between the parameters and the function body.

Here's how you can write the same `add` function but instead of a normal function you can use an arrow function:

Arrow Function Example

const add = (a,b) => {
 return a + b;}
For very simple functions, if they only consist of a single expression, you could even leave out the curly braces and the keyword 'return':

Simplified Arrow Function

const add = (a, b) => a + b;
Arrow functions come in handy when you have to define small anonymous functions. But because arrow functions also use this keyword, they can be inappropriate in more complex situations because they behave differently.

Scope of Functions

Each function in java script operates with its own scope which determines the extent to which a certain variable can be used. Variables defined within the confines of a function are accessible only within that specific function and not outside and are termed as local. On the contrary, global variables which have been defined outside a function can be used anywhere in the program.

When using a variable it is particularly important to understand its scope as it may help protect against errors. Scope restricts the use of a variable to the block in which it is defined, hence, a variable that is declared within a function is said to be local to the function and can only be referenced within the particular function:

Local Variable Example

function test() {
    let x = 10;
    console.log(x); // This will output 10
}

console.log(x); // This will result in an error because x is not defined outside the function
However, a global variable in javascript can be used in any part of the program irrespective of where it is defined. For instance the following code shows a variable `x` which is attached to the window and can be used in any block of code:

Global Variable Example

let x = 5;

function test() {
    console.log(x); // This will output 5
}
0
0
Article
养花风水
9 hours ago
养花风水
The Document Object Model, or DOM, is one of the most important components when it comes to web development in general. It is a representation of a web page in HTML format. More specifically, a document object consists of the content, structure, and the style of a web page, all of which can be changed at any time. JavaScript is the language enabling such actions on the document object. Such knowledge is most crucial when building interactive and dynamic websites. This article will read more about how JavaScript language can be helpful in DOM manipulations in order to create an interesting user experience on the website.

What Exactly Is The DOM?

The DOM is a programming interface for web documents. It takes an HTML or XML document and creates a document object model of it as a tree structure with the element of a webpage in it represented as a node. These nodes can be changed in order to dynamically alter the content, the structure or the style of the page and therefore a mode of interactivity by allowing the modification in response to various user actions.

The document is represented as an intricate hierarchy according to the standards determined by the DOM. The tree structure has a root level which is denoted as the document node which as a rule of thumb encapsulates the entire web page. This level has various other nodes as its children such as element nodes, text nodes and attribute nodes among numerous others. By performing actions on these nodes, a user is successfully able to change how their webpage looks and performs in its functions.

The HTML elements within the webpage can be switched and altered in terms of their attributes or content using various javascript methods.

Accessing DOM Elements

Getting the desired outcome will first require you to access the right HTML elements and then only the changes can be made. Numerous Javascript methods as well as functions assist in element selection in the DOM. From searching for the element using tag name or class or even id or a combination of elements or their relations, all is possible using the following methods.

1. getElementById: Every web page has unique ids and this is how pages identify each other. Since in most cases Id's have to be unique on a page this specific method is super fast and easy.

getElementById Example

let element = document.getElementById("myElement");
2. getElementsByClassName: If you wish to select and modify any of the elements in bulk. For selecting such elements one might have to refer to a specific class as the method selects all elements which share certain characteristics. The method returns live HTML Collection as in if anyone removes a class it is automatically updated.

getElementsByClassName Example

let elements = document.getElementsByClassName("myClass");
3. getElementsByTagName: This method selects all elements with a specified tag like `div`, `p`, or `span`. As with `getElementsByClassName`, this method also returns a live HTMLCollection.

getElementsByTagName Example

let elements = document.getElementsByTagName("p");
4. querySelector: The method allows you to include the first element that matches a specific CSS selector. When compared with the previous methods, it is a more flexible way of selecting elements since it allows lots of CSS selectors.

querySelector Example

let element = document.querySelector(".myClass");



5. querySelectorAll: This method is similar to `querySelector`, except that instead of returning a single element, it returns a NodeList which contains all the elements that match the selector.

querySelectorAll Example

let elements = document.querySelectorAll("div.myClass");

Modifying HTML Elements

Once you have accessed an HTML element using JavaScript, you are free to change its content or modify its attributes. Element properties can be modified in several ways:

1. Changing the Element's Text Content: You can change the inner text of an element with the use of the `textContent` property. This is mainly useful for dynamically changing paragraphs, headings or any text within divs.

Changing Text Content Example

element.textContent = "New content here!";
2. Changing HTML Content: If you want to keep the HTML structure within an element but aim to enhance it, then you have to use the `innerHTML` property. It gives you the access to substitute any content in an element by inserting HTML tags again.

Changing HTML Content Example

element.innerHTML = "New HTML content!";
3. Changing Attributes: The `setAttribute` method gives you an option to change the attributes of an element for example class, id and even the `src` for an image. In the same way, you can find the value of an attribute with the help of `getAttribute` method.

Changing Attributes Example

element.setAttribute("class", "newClass");
let srcValue = element.getAttribute("src");
4. Changing Styles: It is possible to change an element's inline styles including its class via `style` property which gives the access to the internal CSS of the particular element such as colors, margins to be changed as well as font size.

Changing Styles Example

element.style.color = "blue"; 
element.style.fontSize = "20px";

Creating and Inserting Elements

JavaScript enables you to have new elements of HTML created and integrated into the DOM on the go. This is especially relevant for while list appending new items or form fields addition that depend on the user actions.

1. New Elements Creation: You can utilize the `document.createElement` method to create new elements in the Web form. For instance, to create a new `
` element, you can do the following.

Creating New Elements Example

let newDiv = document.createElement("div");
2. Element Appending: After creating a new element, it can be appended to the Document Object Model (DOM) tree using the `appendChild` method. Appending is where the newly created element is added as the last child to a selected parent node.

Appending Elements Example

parentElement.appendChild(newDiv);
3. Inserting Elements at a Particular Position: In case you want more flexibility regarding placing the newly added content, you can make use of methods like `insertBefore`. The `insertBefore` method inserts the new node before the reference node as a child of the specified parent node.

Inserting Elements Example

parentElement.insertBefore(newDiv, referenceElement);

Deleting Elements

Another operation that one can perform in the DOM is deleting an element. For instance, in JavaScript, there is a `removeChild` method that allows a user to remove elements from its parent. Otherwise, you can also use the method `remove` directly on the element that you want to remove.

Removing Elements Example

parentElement.removeChild(element); // Removes the element from its parent
element.remove(); // Removes the element itself

Addons

Removing elements is quite a task to do, but it is also significant. It is worth learning - using the understanding of examples: how to remove an element `x` from the page, regardless of whether a parent is given to that element or not. For instance let us consider how we can remove an element `x` from an arbitrary parent `y`, if that parent exists on the page. Note, at this juncture we focus solely on JavaScript. Once we figure out how to directly we will use a properly written code.

0
0
Article
养花风水
10 hours ago
养花风水
Many look at Javascript as a different programming language, but in reality, it is all that you need for web development with its advanced features as it supports the creation of highly interactive web pages. So, if scripting and programming appear to be foreign concepts to you, it's quite crucial that you comprehend the fundamentals before further expanding your skill set. As it is such a core technology of the web, knowing the fundamentals of Javascript is crucial for any web based developer. Therefore, as our first topic, let's explore the essential core basics of Javascript starting from its syntax and moving forward, to its variables and operators as they are key elements for any web developer's arsenal.

JavaScript Syntax

When approaching any language that involves high levels of programming, the first rule of thumb is mastering its grammar which is called Syntax. Each sequence of code that forms requests has its own structural rules which are called syntax. In this way, Javascript is similar to English, as it has its own particular grammar that needs to be followed.

The language structures used in JavaScript are simple and easy to learn, which makes it an attractive language for novices. The fundamental syntax of a JavaScript statement is outlined in the following way:

Statements:

In most cases, JavaScript source code consists of an indefinite number of statements, each of which analyzes something. A statement is usually issued for a computer to do a specific task. In JavaScript, every statement ends with a ; On the other hand, semicolons are not mandatory in JavaScript although it is a good convention to place them at the end of every statement as a rule.

Whitespace:

Canonical English sentences contain proper spacing between words, and for JavaScript code, proper spacing and indentation also improve the readability of the code. While these items, such as spaces, tabs, or newlines, are mostly not regarded by the JavaScript language interpreter, developers employ them for improving the code's legibility.

Comments:

When writing code using JavaScript, it is possible to add comments on the code. These are short pieces of text which the interpreter does not execute but is meant to describe what the code does. There are two types of comments:

Single-line comments: Which uses the two slash marks //.

Multi-line comments: Which uses the slash and asterisk marked / and the asterisk and slash marked /.

Case Sensitivity:

JavaScript is case sensitive; a variable or a function that is written in lower case is distinct from a function or a variable that appears in upper case. For instance, the variable and Variable would be regarded as two different identifiers.

Case in point: Blocks that contain code in JavaScript are enclosed in a pair of curly braces. These blocks could be such as a function, a loop or simply a conditional statement. Without proper use of the curly braces, it becomes quite difficult to understand where the limits of such code blocks are drawn.

Knowing some of the basic syntax details, you are now in a position to begin writing a reasonable JavaScript code. So, we now proceed to variables, which are very useful when it comes to holding data and changing it.

Rules Governing the Use of JavaScript Variables

For JavaScript, the term variable refers to an electronic address where one will keep the information. Put in simple terms, a variable can be viewed as an entity that can take different forms in the shape of a number, string, or even an object. The use of variables empowers data and techniques in the program to be organized and structured.

Variable Declaration:

In JavaScript, you can create a variable by using one the three keywords: var, let, const. So, each word has a function:

Var: The var keyword was the most reliable means of initializing a variable in JavaScript. However, it has been largely superseded by let and construction purposes in modern JavaScript due to its function-scoping behavior.

Let: The let keyword is used when you want to create variables which will later be re-declared. It is block-scoped hence the variable is only available within a section of code in which it was created.

Const: To create a constant - a variable that cannot be assigned a new value after it has been assigned a value only once use the const keyword. It is also block scoped.

Variable Value Assignment:

Once you have declared a variable, you can give it a value using the assignment operator (=). The value can be typed in as string, number, boolean, array and many others. For instance:

Variable Assignment Example

let ethicalBasesValue = 30;

const person = "John"
Here, variable key ethicalBasesValue takes the value of 30 while variable key person takes the value of John as a string. Take note that a person is of constant meaning its value cannot be altered.

Variable Types:

Variables are at the core of any programming language. In javascript, we have different data types which a variable can be assigned. These include but are not limited to:

Results obtained from user input, for example, Hello world which can be stored in a variable as a string: string variables

Mathematical values, for example, 36 or even a fraction like 0.3333: number variables

True or false – dependencies of a variable: boolean variables.

Types of objects – variables can contain several data types that are stored in a list.

Associative arrays – pairs of values under one name, enabling the user to store data or rather make definitions: object variables.

In order to write any sophisticated javascript code, it would be crucial to know how variables are declared as well as used. Now, let us take time to look at javascript operators in particular.

Operators in JavaScript

Operators in java allow users to execute certain commands and perform specific tasks using variables and values of various kinds. The language incorporates various sorts of operators, each designed to accomplish a certain objective.

Arithmetic Operators:


This type of operator is designed for mathematical operations and performs various tasks over mathematical sets of numbers. This type of operator comprises:

The function of this operator is to sum two statistical values. If a user wants to add two numbers together they would use this instruction: addition operator.

This operates by decreasing arithmetic values. A lesser value is obtained by taking away another value over which a user has control.: subtraction operator.

This is a function ensuring that 2 values and their correlation are maintained mathematically. This is an operator when a user wants to multiply two values.: multiplication operator.

The operator works or operates when a user wishes to divide one value or value set by another. It divides 1 set of statistics by another set of statistics.: division operator.

This is another mathematical operator that lets the user identify the remainder left after one set of numbers has been divided by another.: modulus operator.

The function of this operator is to add one to a specified number. It's usually applied when a user wants to increase a value by one unit.: increment operator.

When a value falls below one, this operator comes into use. It is sometimes manipulated when a user wants to decrease the value of a number by one.: decrement operator.

Assignment Operators:

To put it simply, this class of operators is responsible for giving a value to variables. The simplest of the assignment operators is the equal sign =, but there are other assignment operators that perform a combination of assignment and other work:

+=: It adds a value to a variable and assigns it the new value of the variable.

-=: It takes away a value from a variable and assigns it the assigned value.

*=: It takes a variable, multiplies it by a value and assigns the new value.

/=: Does it define the concept of division in words. It takes a variable and divides it by the value assigned.

Comparison Operators:

This is the type of operators that check variables, get two values or more of them, and return either true or false. Among the comparison operators we can find:

==: this symbol represents equality in mathematics.

===: it is known as strict equality. It checks the value as well as the variable type.

!=: is a sign of non – similarity and when placed hierarchically in an expression denotes not equality.

>: "greater than" in mathematics means one figure is larger than the other figure symbolised by the greater than sign.

<: this symbol represents the opposite of the greater than sign.

>=: in reverse studies, this is a combination of greater than or equal to sign.

<=: Greater than or equal to sign with a reverse meaning.

Logical Operators:

These are used when there are multiple conditions and the requirement is to merge them together. There are also some prominent logical operators:

&& (AND): this is a logical conditional operator. It is only true when both conditions are true.

|| (OR): The logic behind it is that there are multiple conditions but at least one of those conditions needs to be true.

! (NOT): This is a logical negation operator, its meaning in simple terms would be reversed.

0
0
Article
Elite Article
FeedBack

You have any problems or suggestions, please leave us a message.

Please enter content
Set
VIP
Sign out
Share

Share good articles, GFinger floral assistant witness your growth.

Please go to the computer terminal operation

Please go to the computer terminal operation

Forward
Insert topic
Remind friend
Post
/
Submit success Submit fail Picture's max size Success Oops! Something wrong~ Transmit successfully Report Forward Show More Article Help Time line Just Reply Let's chat! Expression Add Picture comment Only support image type .JPG .JPEG .PNG .GIF Image can't small than 300*300px At least one picture Please enter content