Basic JavaScript concepts

This tutorial covers some basic JavaScript concepts and provides examples to help you understand and practice.

  1. Variables and Data Types:
    Variables are used to store and manipulate data in JavaScript. There are different data types in JavaScript, including numbers, strings, booleans, arrays, and objects.
// Number
let age = 25;

// String
let name = "John";

// Boolean
let isStudent = true;

// Array
let numbers = [1, 2, 3, 4, 5];

// Object
let person = {
  name: "John",
  age: 25,
  isStudent: true
};
  1. Functions:
    Functions are blocks of reusable code that perform specific tasks. They can take parameters and return values.
function greet(name) {
  console.log("Hello, " + name + "!");
}

greet("John");
  1. Conditional Statements:
    Conditional statements allow you to make decisions based on certain conditions. The most common ones are if statements and switch statements.
let num = 10;

if (num > 0) {
  console.log("Positive");
} else if (num < 0) {
  console.log("Negative");
} else {
  console.log("Zero");
}
  1. Loops:
    Loops are used to repeatedly execute a block of code. The most commonly used loops are for loops and while loops.
for (let i = 0; i < 5; i++) {
  console.log(i);
}

let count = 0;
while (count < 5) {
  console.log(count);
  count++;
}
  1. Arrays:
    Arrays are used to store multiple values in a single variable. They can hold values of different data types and can be accessed using indices.
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.length);
console.log(numbers[2]);
numbers.push(6);
console.log(numbers);
  1. Objects:
    Objects are used to store multiple values as key-value pairs. They allow you to represent complex data structures.
let person = {
  name: "John",
  age: 25,
  isStudent: true
};

console.log(person.name);
console.log(person["age"]);
person.location = "New York";
console.log(person);
  1. String Manipulation:
    Strings are used to represent text in JavaScript. You can perform various operations on strings, such as concatenation, slicing, and converting case.
let str = "Hello, World!";
console.log(str.length);
console.log(str.toUpperCase());
console.log(str.slice(0, 5));
console.log(str.indexOf("World"));
  1. Math Operations:
    JavaScript provides built-in Math object and various methods for mathematical operations.
let num1 = 5;
let num2 = 3;

console.log(num1 + num2); // Addition
console.log(num1 - num2); // Subtraction
console.log(num1 * num2); // Multiplication
console.log(num1 / num2); // Division
console.log(num1 % num2); // Modulus
console.log(Math.pow(num1, num2)); // Exponentiation
console.log(Math.sqrt(num1)); // Square root
console.log(Math.round(3.7)); // Rounding
console.log(Math.random()); // Random number between 0 and 1

Leave a Reply

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