start learning
Image 1

Basics Javascript Examples

simple example of JavaScript code that demonstrates the basic syntax and concepts :
In this example, we first define a variable message and assign it the value "Hello, world!". We then log the value of the variable to the console using the console.log() function.

Next, we define a function square that takes a single parameter x and returns the square of that value. We then call the function with an argument of 5 and log the result to the console.

Some key concepts demonstrated in this example include:

Variable declaration and assignment using the let keyword
Basic data types like strings and numbers
Logging to the console using console.log()
Function declaration, parameter passing, and return values

Hello World

This code displays the message "Hello World!" in the console window of a web browser or Node.js environment.

Variables


let message = 'Hello';
const name = 'John';
console.log(message + ' ' + name);

This code defines two variables, message and name, and then concatenates them to form the message "Hello John", which is then displayed in the console window.


Arrays


let numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}

This code defines an array of numbers and then uses a for loop to iterate over each element of the array and display it in the console window.


Functions


function add(a, b) {
  return a + b;
}
console.log(add(2, 3));

This code defines a function that takes two parameters, a and b, and returns their sum. The function is then called with arguments 2 and 3, and the result 5 is displayed in the console window.


Objects


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

This code defines an object person with properties name and age, as well as a method greet that displays a greeting using the name property. The greet method is then called on the person object, resulting in the message "Hello, my name is John" being displayed in the console window.


Conditionals


let age = 25;
if (age >= 18) {
  console.log('You are an adult');
} else {
  console.log('You are a child');
}

This code defines a variable age and then uses an if statement to check if it is greater than or equal to 18. If it is, the message "You are an adult" is displayed in the console window. Otherwise, the message "You are a child" is displayed.


Loops


for (let i = 1; i <= 10; i++) {
  console.log(i);
}

This code uses a for loop to display the numbers from 1 to 10 in the console window.


DOM Manipulation


let button = document.querySelector('button');
button.addEventListener('click', function() {
  alert('Button clicked!');
});

This code selects a button element from the HTML document and adds a click event listener to it. When the button is clicked, an alert message "Button clicked!" is displayed.


Promises


function getData() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve('Data received');
    }, 2000);
  });
}
getData().then(function(data) {
  console.log(data);
});

This code defines a function getData that returns a promise that resolves after 2 seconds with the message "Data received". The then method is then used to log the message to the console when the promise is fulfilled.


Error Handling


function divide(a, b) {
  if (b === 0) {
    throw new Error('Cannot divide by zero');
  }

Error handling is the process of detecting, diagnosing, and resolving programming errors (or bugs) within a software application. In JavaScript, error handling involves detecting and responding to runtime errors that occur during the execution of a program.


Error Handling Methods

There are several ways to handle errors in JavaScript, including :
Using try...catch blocks: This is a basic way to handle errors in JavaScript. You place the code that might cause an error inside a try block, and catch the error with a catch block. For example: csharp


try {
  // Some code that might cause an error
} catch (error) {
  // Handle the error
}

Throwing errors: You can manually throw an error in JavaScript using the throw statement. This is useful if you want to create your own custom error messages or if you want to stop the execution of a program when a certain condition is met. For example: javascript


    if (someCondition) {
  throw new Error('An error occurred');
}

Using error objects: In JavaScript, errors are represented by objects. You can create your own custom error objects by extending the built-in Error object. For example: kotlin


class CustomError extends Error {
  constructor(message) {
    super(message);
    this.name = 'CustomError';
  }
}

Using error codes: You can also use error codes to identify different types of errors in your program. This can be useful if you want to display specific error messages to the user based on the type of error that occurred. For example: Javascript


const ERROR_CODES = {
  INVALID_INPUT: 1,
  NETWORK_ERROR: 2,
  SERVER_ERROR: 3,
};
function handleError(errorCode) {
  switch (errorCode) {
    case ERROR_CODES.INVALID_INPUT:
      console.error('Invalid input');
      break;
    case ERROR_CODES.NETWORK_ERROR:
      console.error('Network error');
      break;
    case ERROR_CODES.SERVER_ERROR:
      console.error('Server error');
      break;
    default:
      console.error('Unknown error');
  }
}