JavaScript Programming Exercises and Code Examples

Fee Payment Logic

let feePaid = true;
let underLimitAbsences = true;
let canTakeExam = feePaid && underLimitAbsences;
console.log(canTakeExam);

Grading System

let nota;
let piket = 100;
if (piket > 100) {
  console.log("Piket nuk jane te sakta");
} else if (piket >= 95) {
  nota = 10;
} else if (piket >= 85) {
  nota = 9;
} else if (piket >= 75) {
  nota = 8;
} else if (piket >= 65) {
  nota = 7;
} else if (piket >= 55) {
  nota = 6;
} else if (piket >= 45) {
  nota = 5;
} else if (piket >= 0) {
  nota = 4;
} else {
  console.log("Piket nuk jane te sakta");
}
console.log("Nota eshte: ", nota);

Mathematical Operations

let sum = 0;
for (let number = 0; number <= 10; number++) {
  if (number % 2 == 0) {
    sum = sum + number;
  }
}
console.log("Sum is = ", sum);

Authentication Logic

let username = "admin";
let password = "1234";
if (username === "admin" && password === "1234") {
  console.log("Log in successful");
} else {
  console.log("Log in unsuccessful");
}

Finding the Maximum Value

let n1 = 44, n2 = 12, n3 = 5, max;
if (n1 >= n2 && n1 >= n3) {
  max = n1;
} else if (n2 >= n1 && n2 >= n3) {
  max = n2;
} else {
  max = n3;
}
console.log("max: ", max);

Object Manipulation

  • Create an object with your data.
  • Add a phone number property.
  • Remove the age property.
let erionSelimi = { emer: "Erion", mbiemer: "Selimi", mosha: 42 };
erionSelimi.nrCel = "0691234567";
delete erionSelimi.mosha;
console.log(erionSelimi);

Factory and Constructor Functions

function createStudent(emri, mbiemri, dega, viti) {
  return { emri, mbiemri, dega, viti, info() { console.log(this.emri, this.mbiemri, this.dega, this.viti); } };
}

function CreateStudent(emri, mbiemri, dega, viti) {
  this.emri = emri;
  this.mbiemri = mbiemri;
  this.dega = dega;
  this.viti = viti;
  this.info = function () { console.log(this.emri, this.mbiemri, this.dega, this.viti); };
}

Object Copying and Merging

let erioni = { emer: "Erion", mbiemer: "Selimi" };
let arsen = { ...erioni, emer: "Arsen" };

let erion = { name: "Erion", age: 42 };
let job = { employer: "UMT", title: "Professor" };
let info = { ...erion, ...job };

String and Date Handling

function getDomain(email) {
  return email.slice(email.indexOf("@") + 1);
}

function getDayOfWeek(birthDate) {
  const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  return days[new Date(birthDate).getDay()];
}

Classes and Inheritance

class Car {
  constructor(name, year) { this.name = name; this.year = year; }
  age() { return new Date().getFullYear() - this.year; }
}

class Student extends Dega {
  constructor(dega, emer, mbiemer) { super(dega); this.emer = emer; this.mbiemer = mbiemer; }
}

Array Methods: Filter, Map, and Reduce

const notat = [4, 10, 8, 4, 6, 5, 9];
const notaKaluese = notat.filter(n => n > 4);
const average = notat.reduce((a, b) => a + b, 0) / notat.length;