Introduction to JavaScript

JavaScript is a high-level, interpreted programming language which is mainly created to interact with the web browsers. It is one of the core technologies of the World Wide Web.

  • JavaScript is a client-side language which means, it runs in the user’s browser.
  • It enables interactive web features such as image sliders, form validations, animations, and more.
  • JavaScript is used on both the front-end and back-end.
  • JavaScript reacts to user actions like clicks, scrolls, and keyword inputs.
  • It supports object-oriented programming for better structure and reusability.
JavaScript Tutorial for Beginners

Variable and Data Types

Variables are used to store data. In JavaScript we can declare variable from three ways var, let, const.

var: It is function-scoped which means it is available throughout the function where it’s declared. It allows redeclaration within the same scope. Modern JavaScript avoids this.
let: It is block-scoped which means it is only available within the nearest set of curly braces {}. It does not allows redeclaration in the same scope.
const: It is also block-scoped just like let. Redeclaration is not allowed in the same scope. It must be assigned a value at declaration, it is used for values that should not change.

Data Types: JavaScript is a dynamically typed language, meaning you don’t have to specify data types when declaring variables.

JavaScript
let username = 'bob'; //String
let age = 30; //Number
let isLoggedIn = true; //Boolean
let score; //Undefined
let emptyValue = null; //Null
let user = { name: "Alice", age: 30}; //Object
let numbers = [1, 2, 3]; //Array

Operators

JavaScript operators are used to perform operations on values and variables.

1. Arithmetic Operators: These operators are used for math operations (+, -, *, /, %, ++, –).
2. Assignment Operators: These operators are used to assign values (=, +=, -=, *=, /=, %=).
3. Comparison Operators: These operators are used to compare values (==, ===, !=, !==, >, <, >=, <=).
4. Logical Operators: These operators are used for Boolean logic (&&, ||, !).
5. String Operators: + is also used for join strings.

Conditional Statements & Loops

Conditional statements are used to make decisions.

JavaScript
//if statement
if (age >= 18){
  console.log("Adult");
  }
  
//if...else
if (score >= 50){
  console.log("Pass");
} else {
  console.log("Fail");
}

//else if
if (marks >= 90) {
  console.log("A Grade");
} else if (marks >= 75) {
  console.log("B Grade");
} else {
  console.log("Try Again");
}

//switch statement
let day = "Mon";
switch (day) {
  case "Mon": console.log("Monday"); break;
  case "Tue": console.log("Tuesday"); break;
  default: console.log("Other day");
}

Loops are used to run code multiple times.

JavaScript
//for loop
for (let i = 1; i <= 5; i++) {
  console.log(i);
}

//while loop
let i = 1;
while (i <= 5) {
  console.log(i);
  i++;
}

//do...while loop
let i = 1;
do {
  console.log(i);
  i++;
} while (i <= 5);

//for...of (loops through arrays)
let fruits = ["apple", "banana"];
for (let fruit of fruits) {
  console.log(fruit);
}

//for...in (loops through object keys)
let user = { name: "Ali", age: 25 };
for (let key in user) {
  console.log(key + ": " + user[key]);
}

Arrays

Arrays in JavaScript are a type of object used to store multiple values in a single variable. They can hold elements of any type (strings, numbers, objects, even other arrays), and their size is dynamic, meaning they can grow or shrink as needed.

JavaScript
//1. Declaration & Creation
let fruits = ['apple', 'banana', 'cherry'];
console.log('Original array:', fruits);

//2. Accessing Elements
console.log('First fruit:', fruits[0]);
console.log('Last fruit:', fruits[fruits.length - 1]);

//3. Modifying Elements
fruits[1] = 'blueberry';
console.log('After modifying second fruit:', fruits);

//4. Adding & Removing Elements
fruits.push('date');        // Add to end
fruits.unshift('avocado');  // Add to start
fruits.pop();               // Remove from end
fruits.shift();             // Remove from start
console.log('After push, unshift, pop, shift:', fruits);

//5. Searching Elements
console.log('Includes cherry?', fruits.includes('cherry'));
console.log('Index of blueberry:', fruits.indexOf('blueberry'));

//6. Looping Through Array
console.log('Looping with forEach:');
fruits.forEach((fruit, index) => {
  console.log(`${index}: ${fruit}`);
});

//7. Slice & Splice
let sliced = fruits.slice(0, 2); // does not change original
console.log('Sliced (0-2):', sliced);

fruits.splice(1, 1, 'kiwi'); // replaces 1 item at index 1
console.log('After splice:', fruits);

//8. Map & Filter
let upperFruits = fruits.map(fruit => fruit.toUpperCase());
let bFruits = fruits.filter(fruit => fruit.startsWith('b'));
console.log('Uppercased:', upperFruits);
console.log('Fruits starting with "b":', bFruits);

//9. Sort & Reverse
let sortedFruits = [...fruits].sort(); // copy then sort
let reversedFruits = [...fruits].reverse();
console.log('Sorted:', sortedFruits);
console.log('Reversed:', reversedFruits);

//10. Reduce (Sum example with numbers)
let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log('Sum of numbers:', sum);

Objects

Objects are collections of key-value pairs. They are used to represent structured data.
1. Keys in objects are always strings or symbols.
2. Values can be any type: string, number, array, object, function, etc.
3. Objects are mutable, and they are passed by reference.

JavaScript
//Object Declaration & Creation
let person = {
  name: "John",
  age: 30,
  isStudent: false,
  hobbies: ["reading", "sports"],
  address: {
    city: "New York",
    zip: "10001"
  },
  greet: function () {
    console.log("Hello, I'm " + this.name);
  }
};

//Accessing Properties
console.log(person.name);        // Dot notation: John
console.log(person["age"]);      // Bracket notation: 30
console.log(person.address.city); // Nested access: New York

//Modifying & Adding Properties
person.age = 31;                 // Modify existing
person.email = "john@example.com"; // Add new

//Deleting Properties
delete person.isStudent;
console.log(person.isStudent); // undefined

//Methods (Functions Inside Objects)
person.greet(); // Hello, I'm John

//Looping Through Object Properties
for (let key in person) {
  console.log(key + ":", person[key]);
}

//Object Methods & Utilities
let keys = Object.keys(person);     // ['name', 'age', 'hobbies', ...]
let values = Object.values(person); // ['John', 31, ['reading', 'sports'], ...]
let entries = Object.entries(person); // [['name', 'John'], ['age', 31], ...]

console.log(keys);
console.log(values);
console.log(entries);

//Object Destructuring
let { name, age, address } = person;
console.log(name);    // John
console.log(address.city); // New York

//Object Copying
let copy = Object.assign({}, person);
let clone = { ...person }; // Spread operator (shallow copy)

//Checking Property Existence
console.log("email" in person); // true

Will update soon….

Scroll to Top