Javascript language

We given a information and tutorial of Javascript language to help you for learning the web development. So, Read the information carefully and watch the tutorial to better understand for getting a skill and knowledge about the javascript language.


Javascript (Scripting language)

Javascript is a programming language which is commonly used for server-side to provide the interactivity to the website. It is a versatile language which means it can be used for both client-side and server-side. It controls the user interface, events, asynchronous operations and DOM (Document Object Model) of the website.


Basic concepts

Variables

Variables are used to declare the data or value.

Here are the types of variables as given - 
  • var - It is a keyword which is used to declare the variables that are function-scoped or globally-scoped.
var age = 20;

  • let - It is a commonly used keyword to declare the values.
let name = "Codi boy";

  • const - It is used to declare the constant variables.
const PI = 3.14;


Datatypes

Datatypes are used to categorize the values like number, string, boolean and others as given below - 
  • Number - It represents the integer and floating value.
let num = 10;
let pi = 3.14;

  • String - It represents the text which enclosed in (' ') single and (" ") double quotes.
let name = "Codi boy";
let message = "Hello World!";

  • Boolean - It represents the value logic as true or false.
let isActive = true;
let isHidden = false;

  • Null - It represents the null or empty value.
let value = null;


Operators

Operators are symbols that used to perform the operations on variables.

Here are the types of operators as given below -

1) Arithmetic operator
Arithmetic operators are used to perform the mathematical operations.
  • Addition ("+") - Used to add two numbers.
let sum = 10 + 20; // sum is 30

  • Subtraction ("-") - Used to subtract the number from one to another.
let diff = 20 - 10; // difference is 5

  • Multiplication ("*") - Used to multiply the two numbers.
let multiply = 10 * 20; // result is 50

  • Division ("/") - Used to divide the numbers.
let quotient = 20 / 5; // quotient is 4

  • Remainder ("%") - It returns the remainder of a division operation.
let remainder = 11 % 3; // remainder is 2

2) Assignment Operator
Assignment operator is used assign the values to the variables.

let x = 10; // x is assigned the value 10

3) Comparison Operator
Comparison operator is used to compare the two values which returns the result as true or false.

let isEqual = (10 == 10); // isEqual is true
let notEqual = (20 == 10); // notEqual is false

4) Logical Operator
Logical Operator is used to combine conditional statements.

let x = 10;
let y = 5;
let result = (x > 5 && y < 10); // result is true
let result = (x > 5 || y > 10); // result is true
let result = !(x > 5); // result is false (x > 5 is true, !true is false)

5) Unary Operator
Unary operator is used to work with single operand.

let x = "10";
let y = +x; // y will be 10
let x = 5;
let y = -x; // y will be -5


6) Conditional Operator
It is used to write the conditional statements.

let age = 20;
let message = (age >= 18) ? "Adult" : "Minor";
console.log(message); // Outputs: "Adult"


Control flow

Control flow is used to execute the statements in a script. It executes the programs as per operations.

1) Conditional statements
  • if statement - It executes the block of code if a condition is true.
if (condition) {
    // code block to be executed if condition is true
} else {
    // code block to be executed if condition is false
}

  • else if statement - It allows to specify the new condition if the previous condition is false.
if (condition1) {
    // code block to be executed if condition1 is true
} else if (condition2) {
    // code block to be executed if condition2 is true
} else {
    // code block to be executed if none of the conditions are true
}

  • switch statement - It executes the code blocks that are matching cases.
switch (expression) {
    case value1:
        // code block
        break;
    case value2:
        // code block
        break;
    default:
        // code block
}

2) Loops
  • for loop - It executes a block of code at a specified number of times.
for (initialization; condition; iteration) {
    // code block to be executed
}

  • while loop - It executes a block of code as long as a condition is true.
while (condition) {
    // code block to be executed
}

  • do...while loop - It executes the block of code before checking the condition.
do {
    // code block to be executed
} while (condition);

3) Branching statements
Branching statements are used to break out the conditions and statements.
  • break statement - It is used to terminate the execution of a condtions.
for (let i = 0; i < 5; i++) {
    if (i === 3) {
        break; // exits the loop when i is 3
    }
    console.log(i); // prints 0, 1, 2
}

  • continue statement - It skips the current condition and continues with next condition.
for (let i = 0; i < 5; i++) {
    if (i === 2) {
        continue; // skips iteration when i is 2
    }
    console.log(i); // prints 0, 1, 3, 4
}

  • return statement- It is used to exit the current function and returns the a value to the calling function.
function multiply(a, b) {
    if (b === 0) {
        return 0; // returns 0 if b is 0
    }
    return a * b; // returns the product of a and b
}


Function

Functions are used to encapsulate the block of code that can called and executed repetedly. Function are used with function keyword and used inside the parentheses "()" and function body is enclosed within "{}" curly braces.

// Function declaration
function greet(name) {
    console.log(`Hello ${name}!`);
}

// Calling the function
greet('Codi boy'); // Output: Hello Codi boy!


Array

Array is used to store the same types of data including numbers, strings, objects, etc.

// Array literal
let languages = ['HTML', 'CSS', 'JS'];

// Using Array constructor
let numbers = new Array(1, 2, 3, 4, 5);


Objects

Objects are used to store the collection of key-value pairs. It allows to represent the complex and organize the data using the curly braces "{}" and separated with commas.

// Example of an object
let person = {
    name: "Codi boy",
    age: 20,
    isStudent: false,
    greet: function() {
        console.log(`Hello, my name is ${this.name}`);
    }
};

// Accessing object properties
console.log(person.name);     // Output: Alice
console.log(person.age);      // Output: 30
console.log(person.isStudent);// Output: false

// Calling object method
person.greet();               // Output: Hello, my name is Alice


DOM (Document Object Model)

DOM manipulation is the process of updating the structure and style of a webpage.

1) Accessing Elements
To access elements in the DOM, it includes some methods -
  • document.getElementById - It is used to access the element by the Id.
  • document.getElementByClassName - It is used to access the element by the class name.
  • document.getElementByTagName - It is used to access the element by the tag name.
  • document.querySelector - It is used to access the first element that matches the css selector.
// Get element by ID
let element = document.getElementById('myElement');

// Get elements by class name
let elements = document.getElementsByClassName('myClass');

// Get elements by tag name
let tags = document.getElementsByTagName('div');

// Get the first element that matches a CSS selector
let firstElement = document.querySelector('.myClass');

// Get all elements that match a CSS selector
let allElements = document.querySelectorAll('p');


2) Manipulating content
Some properties like "innerHTML", "textcontent" and "innerText" are used to manipulate the content of HTML elements.

// Changing inner HTML content
element.innerHTML = 'New Content';

// Changing text content
element.textContent = 'Text Content';

// Changing visible text (ignores styles)
element.innerText = 'Visible Text';

3) Modifying Attributes
"setAttribute", "getAttribute" and "removeAttribute" are used to modify the attributes of the HTML elements.

// Set attribute
element.setAttribute('class', 'newClass');

// Get attribute
let classValue = element.getAttribute('class');

// Remove attribute
element.removeAttribute('class');

4) Styling Elements
"style" property is used change the style of HTML elements.

// Change CSS styles
element.style.backgroundColor = 'blue';
element.style.color = 'white';
element.style.fontSize = '20px';

5) Creating and Appending Elements
Properties like "createElement", "appendChild" and "insertBefore" are used to create new HTML elements.

// Create a new element
let newElement = document.createElement('div');
newElement.textContent = 'New Element';

// Append to an existing element
document.body.appendChild(newElement);

// Insert before an element
let referenceElement = document.getElementById('referenceElement');
document.body.insertBefore(newElement, referenceElement);

6) Event Handling
Event listeners are used to handle the events such as clicks, key presses, etc.

// Add event listener
element.addEventListener('click', function() {
    console.log('Element clicked');
});

// Remove event listener
element.removeEventListener('click', eventHandlerFunction);


Asynchronous Javascript

Asynchronous Javascript is the execution model where the operation are performed independently. It allows to handle the tasks such as fetching data from a server and executing the operations with a specific time after the main execution.

1) Callbacks
Callbacks are used to execute the code after the completion of a particular operation. The callback functions are passed as arguments to another function.

function fetchData(callback) {
    setTimeout(function() {
        callback("Data fetched successfully");
    }, 2000); // Simulating a delay of 2000 milliseconds (2 seconds)
}

function processData(data) {
    console.log(data);
}

fetchData(processData); // Output after 2 seconds: "Data fetched successfully"

2) Promises
Promises provides the structured way to handle asynchronous opertions as compared to the callback functions. 

function fetchData() {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            resolve("Data fetched successfully");
        }, 2000);
    });
}

fetchData()
    .then(function(data) {
        console.log(data); // Output after 2 seconds: "Data fetched successfully"
    })
    .catch(function(error) {
        console.error(error);
    });

3) Async/Await
"async" and "await" keywords are used to work with asynchronous code in a synchronou way which make it easier to write and execute the code.

async function fetchAndProcessData() {
    try {
        let data = await fetchData();
        console.log(data); // Output after 2 seconds: "Data fetched successfully"
    } catch (error) {
        console.error(error);
    }
}

fetchAndProcessData();


Error Handling

Error Handling is used to handle the errors of the code using try and catch blocks.

async function fetchData() {
    try {
        let response = await fetch('https://api.example.com/data');
        if (!response.ok) {
            throw new Error('Failed to fetch data');
        }
        let data = await response.json();
        return data;
    } catch (error) {
        console.error(error);
        throw error; // Propagate the error up the call chain
    }
}

fetchData()
    .then(function(data) {
        console.log(data);
    })
    .catch(function(error) {
        console.error('Error occurred:', error);
    });


Comments

Comments are used to add explanation for understanding the code and they are not shown on browser.
To write comments,"//" are used in the starting.

// This is a comment.
let x = 5;  // Variable assignment


Example -

HTML and CSS

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }
        h1 {
            color: #333;
        }
        input[type="text"], button {
            padding: 10px;
            font-size: 16px;
            margin-bottom: 10px;
        }
        #output {
            font-size: 18px;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <h1>JavaScript Example</h1>
    <p>Welcome to this JavaScript example page!</p>

    <label for="nameInput">Enter your name:</label>
    <input type="text" id="nameInput">
    <button onclick="displayGreeting()">Display Greeting</button>

    <div id="output"></div>

    <script src="script.js"></script>
</body>
</html>

Javascript

function displayGreeting() {
    // Get the value entered in the input field
    let name = document.getElementById('nameInput').value;

    // Construct the greeting message
    let greeting = `Hello, ${name}! Welcome to JavaScript!`;

    // Display the greeting message in the output div
    let outputDiv = document.getElementById('output');
    outputDiv.textContent = greeting;
}

Output -

HTML CSS JS Basic Example


Watch this tutorial to learn javascript from basic to advanced -

Source - Apna college (Youtube)


Also Check this :-
Compiler to run projects- HTML CSS JS Online Compiler 

If you have any confusion or query, then feel free to ask us on coding community.

Learn more and practice more🚀