Javascript Basic Examples

Here are some examples of JavaScript that span different ideas and features:

An introduction to JavaScript syntax, control structures, arrays, objects, asynchronous programming, DOM manipulation, and contemporary ES6 capabilities is given in these examples. These ideas can be developed further to create more intricate applications.

Basic Syntax and Functions

Here, We will see the basic syntax and functions.

// Basic syntax example
let greeting = 'Hello, world!';
console.log(greeting);

// Function example
function add(a, b) {
    return a + b;
}

let sum = add(2, 3);
console.log('Sum:', sum);

Here, we will create a basic syntax of greeting using the keyword as “Hello World” and printing the output using console.log. The key word console.log is using to print the output of the JS code.

Then, we will create a function add and it assigns the sum. it called the add function and return the sum of two numbers.

Control Structures

Different actions can be carried out depending on certain conditions by using conditional statements as if-else

Use if to declare a code block that will run if a given condition is met.
If the same condition is false, use else to designate a block of code to be run.
If the first condition is false, use else if to define a new condition to test.

for loop repeatedly runs a section of code through.

// If-else statement
let number = 10;

if (number > 0) {
    console.log('The number is positive.');
} else if (number < 0) {
    console.log('The number is negative.');
} else {
    console.log('The number is zero.');
}

// For loop
for (let i = 0; i < 5; i++) {
    console.log('Iteration:', i);
}

Array Objects

An array is a type of variable that has the capacity to store several values.

Here, How to add the object into the array. it is also called the function and along with array obiects.

// Array example
let fruits = ['Apple', 'Banana', 'Cherry'];
fruits.push('Orange');  // Add item to the array

fruits.forEach(function(fruit) {
    console.log(fruit);
});

// Object example
let person = {
    name: 'John',
    age: 30,
    greet: function() {
        console.log('Hello, my name is ' + this.name);
    }
};

console.log('Person name:', person.name);
person.greet();

Asynchronous JavaScript (Promises and async/await)

Asynchronous functions are those that execute concurrently with other functions.

A function that uses async returns a Promise.

A function that uses await waits for a Promise.

“Producing code” refers to writing code that requires time.

“Consuming code” refers to code that needs to wait for an outcome.

An object that connects producing and consuming code is called a promise.

// Promise example
let promise = new Promise(function(resolve, reject) {
    let success = true;  // Simulate success or failure
    if (success) {
        resolve('Operation was successful.');
    } else {
        reject('Operation failed.');
    }
});

promise
    .then(function(message) {
        console.log(message);
    })
    .catch(function(error) {
        console.error(error);
    });

// async/await example
async function fetchData() {
    try {
        let response = await fetch('https://api.example.com/data');
        let data = await response.json();
        console.log('Data:', data);
    } catch (error) {
        console.error('Error fetching data:', error);
    }
}

fetchData();

DOM Manipulation

Working with the Document Object Model (DOM) is a crucial part of using JavaScript to interact with webpages.

// Selecting and manipulating DOM elements
document.addEventListener('DOMContentLoaded', function() {
    let button = document.querySelector('button');
    let output = document.querySelector('#output');

    button.addEventListener('click', function() {
        output.textContent = 'Button was clicked!';
    });
});

ES6 Features (Arrow Functions, Template Literals, Destructuring)

JavaScript gained several new capabilities with ES6 (ECMAScript 2015), which increased the language’s functionality and ease of writing.

// Arrow function
let multiply = (a, b) => a * b;
console.log('Multiply:', multiply(2, 3));

// Template literals
let name = 'Alice';
let greeting = `Hello, ${name}!`;
console.log(greeting);

// Destructuring
let user = {
    username: 'johndoe',
    email: 'johndoe@example.com'
};

let { username, email } = user;
console.log('Username:', username);
console.log('Email:', email);

These are the some basic examples of javascript. In detail, we will see the next tutorial. Happy Coding!!!…

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top