//Завдання 1.Cтворіть об'єкт person за допомогою конструктора з полями name: "John",age: 25
let person = { name: "John", age: 25 };

console.log("Завдання 1 ====================================");

console.log("person", person); // Виведе {name: "John", age: 25}

//Завдання 2. Cтворіть об'єкт personLarge який буде мати такі ж поля як person ,
// та вкладений об'єкт address з полями  street: "123 Main St", city: "New York", country: "USA",
let personLarge = {
  name: "John",
  age: 25,
  //використовуємо деструктурізацію на об'єкті person
  //створюємо об'єкт address
  address: {
    street: "123 Main St",
    city: "New York",
    country: "USA",
  },
};

console.log("Завдання 2 ====================================");
console.log("personLarge", personLarge); // Виведе
// personLarge {
//   name: 'John',
//   age: 25,
//   address: { street: '123 Main St', city: 'New York', country: 'USA' }
// }

//Завдання 3: Створіть функцію, що повертає новий об'єкт з тими ж властивостями, що й переданий у якості аргумента об'єкт.

var animal = {
  type: "Dog",
  breed: "Labrador Retriever",
};

// Функція для створення нового об'єкта з тими ж властивостями
function copyObject(obj) {
  // Використовуємо синтаксис деструктурізації {...person} для створення нового об'єкта з тими ж властивостями
  const animal1 = { ...animal };
  // Повертаємо новий об'єкт
  return animal1;
}

console.log("Завдання 3 ====================================");

console.log("copyObject(animal)", copyObject(animal)); // Виведе { type: 'Dog', breed: 'Labrador Retriever' }

////Завдання 4. Перевірте наявність властивості в об'єкті за допомогою оператора in.
let fruit = {
  name: "Banana",
  color: "Yellow",
};
// Функція для перевірки наявності властивості в об'єкті
function hasProperty(obj, property) {
  // Використовуємо оператор "in" для перевірки наявності властивості
  for (const property in fruit) {
    // Запишимо умову якщо властивість існує повертає текст Property ${property} exists,
    if ("Banana") {
      const { name } = property;
      return `Property ${property} exists`;
    } else {
      return `Property ${property} does not exist`;
    }
  }

  // інашке повертаємо Property ${property} does not exist.
}

console.log("Завдання 4 ====================================");
console.log(hasProperty(fruit, "name")); // Виведе "Property name exists."
console.log(hasProperty(fruit, "taste")); // Виведе "Property color does not exist."

// Завдання 5: Створіть функцію, що отримує об'єкт і виводить на консоль всі його ключі та значення.
let country = {
  name: "United States",
  capital: "Washington, D.C.",
};
// Функція для виведення всіх ключів і значень об'єкта
function printKeysAndValues(obj) {
  // Проходимося по всіх ключах об'єкту за допомогою циклу "for in"
  for (const key in country) {
    console.log("Key:", key, "Value:", country[key]);
  }
  // Виводимо ключ та значення на консоль
}

console.log("Завдання 5 ====================================");
printKeysAndValues(country);
// Виведе
// Key: name, Value: United States
// Key: capital, Value: Washington, D.C.

// Завдання 6: Видаліть властивість з об'єкта за допомогою оператора delete.
let movie = {
  title: "Inception",
  director: "Christopher Nolan",
};
// Функція для видалення властивості з об'єкта
function deleteProperty(obj, property) {
  // Використовуємо оператор "delete" для видалення властивості
  delete movie.director;

  // Повертаємо об'єкт
  return movie;
}

console.log("Завдання 6 ====================================");
console.log(deleteProperty(movie, "director")); // Виведе { title: 'Inception' }

//Завдання 7: Використайте ключове слово this в об'єкті.
// Створюємо об'єкт
let user = {
  name: "John",
  age: 25,
  // Створюємо метод introduce, який за допомогою ключового слова this має повернути такий рядок
  introduce() {
    return `My name is ${this.name} and I am ${this.age} years old.`;
  },

  // My name is John and I am 25 years old.
  // introduce: `My name is ${user.name} and I am ${user.age} years old.`,
};

console.log("Завдання 7 ====================================");
// Викликаємо метод introduce об'єкта user
user.introduce;
// Розкоментуйте рядок нижче після виконня завдання для перевірки
console.log(user.introduce());
// Виведе My name is John and I am 25 years old.

// Завдання 8: Створіть функцію, яка додає нове поле до об'єкту.
let book = {
  title: "To Kill a Mockingbird",
  author: "Harper Lee",
};

// Функція для додавання нового поля до об'єкту
function addField(obj, newField, value) {
  // Додаємо нове поле до об'єкту з допомогою квадратних дужок
  obj["year"] = 1960;
  // Повертаємо об'єкт
  return book;
}

console.log("Завдання 8 ====================================");
console.log(addField(book, "year", 1960)); // Виведе { title: 'To Kill a Mockingbird', author: 'Harper Lee', year: 1960 }

// Завдання 9: Деструктуруйте об'єкт в нові змінні.
let laptop = {
  brand: "Dell",
  model: "XPS 13",
};
// Функція для деструктуризації об'єкту
function destructureObject(obj) {
  // Використовуємо деструктуризацію для створення нових змінних з властивостей об'єкту і отримуємо з нього змінні brand та model
  let { brand, model } = laptop;
  // Повертаємо нові змінні  в форматі 'Brand: ${brand}, Model: ${model}'
  return `Brand: ${brand}, Model: ${model}`;
}

console.log("Завдання 9 ====================================");
console.log(destructureObject(laptop)); // Виведе Brand: Dell, Model: XPS 13

// Завдання 10: Змініть значення полів об'єкту, що знаходяться в масиві об'єктів.

// Створюємо масив об'єктів userList, першим елементом якого буде об'єкт name:"Jack",role:"reader", а другим об'єкт name: "Jane", role: 'admin'

let userList = [
  { name: "Jack", role: "reader" },
  { name: "Jane", role: "admin" },
];
// Функція для зміни ролі всіх осіб у масиві
function changeRole(array, newRole) {
  // Ітеруємося по масиву об'єктів за допомогою циклу "for of"

  for (let rolle of userList) {
    for (let newRol in {}) {
      if (role) {
        role = "editor";
      }
      return "editor";
    }
    console.log(userList);
  }
  // Змінюємо роль кожного користувача на нове ім'я

  // Виводимо об'єкт на консоль
  return userList;
}

console.log("Завдання 10 ====================================");
changeRole(userList, "editor");
// Виведе
// { name: 'Jack', role: 'editor' }
// { name: 'Jane', role: 'editor' }

// Завдання 11: Використовуйте вкладені об'єкти для зберігання більш складної інформації.
// Створюємо об'єкт з вкладеним об'єктом
let product = {
  productName: "Smartphone",
  price: 699,
  manufacturer: {
    companyName: "Tech Corp",
    country: "USA",
  },
};
// Функція для виводу деталей людини
function printProductDetails(obj) {
  // Використовуємо деструктуризацію для отримання значень productName, price i також значень companyName, country вкладеного об'єкту manufacturer
  let {
    productName,
    price,
    manufacturer: { companyName, country },
  } = product;
  // Виводимо productName, price, companyName та country на консоль
  console.log(productName, price, companyName, country);
}

console.log("Завдання 11 ====================================");
printProductDetails(product); // Виведе Smartphone 699 Tech Corp USA

// Завдання 12: Показати, що об'єкти будуть дорівнювати один одному лише тоді, коли одному об'єкту присвоїти значення іншого.
// Створіть об'єкт два об'єкти planet1 та planet2 з полями   name: "Земля",radius: 6371,

let planet1 = { name: "Земля", radius: 6371 };
let planet2 = { name: "Земля", radius: 6371 };

// Функція для перевірки рівності об'єктів
function compareObjects(obj1, obj2) {
  // Виводимо результат порівняння об'єктів

  return { planet1 } === { planet2 };
  // Присвоємо obj2 значення об'єкту obj1
  obj1 = obj2;
  return obj1 === obj2;

  // Виводимо результат порівняння об'єктів
}

console.log("Завдання 12 ====================================");
compareObjects(planet1, planet2); // Виведе
//false
//true

// Завдання 13: Використовуйте деструктуризацію зі значенням за замовчуванням у аргументах функції для об'єкта.
let car = {
  brand: "BMW",
  year: 2022,
};
// Створюємо функцію, яка приймає об'єкт як аргумент і використовує деструктуризацію зі значенням за замовчуванням
// brand за замовчуванням призначемо Unknown, year за замовчуванням призначемо 0, country за замовчуванням призначемо Unknown

function showCarInfo({
  brand = "Unknown",
  year = 0,
  country = "Unknown",
} = {}) {
  // Повертаємо об'єкт зі значеннями властивостей
  return `brand: ${brand}, year: ${year}, country: ${country}`;
}

console.log("Завдання 13 ====================================");
console.log(showCarInfo(car)); // Виведе { brand: 'BMW', year: 2022, country: 'Unknown' }

// Завдання 14: Додайте нову властивість до вбудованого об'єкту Array через літерал.
// Створюємо функцію, яка буде додавати нову властивість до масиву
function addProperty(array) {
  // Додаємо нову властивість customProperty до прототипу Array зі значенням myProperty
  // Повертаємо переданий масив з новою властивістю
}

console.log("Завдання 14 ====================================");
// Створимо масив newArr з новою властивістю за допомогої нашої функції в яку передамо [1, 2, 3, 4, 5]

// Розкоментуйте рядок нижче після виконня завдання для перевірки
// console.log(newArr.customProperty); // Виведе myProperty 

Javascript Online Compiler

Write, Run & Share Javascript code online using OneCompiler's JS online compiler for free. It's one of the robust, feature-rich online compilers for Javascript language. Getting started with the OneCompiler's Javascript editor is easy and fast. The editor shows sample boilerplate code when you choose language as Javascript and start coding.

About Javascript

Javascript(JS) is a object-oriented programming language which adhere to ECMA Script Standards. Javascript is required to design the behaviour of the web pages.

Key Features

  • Open-source
  • Just-in-time compiled language
  • Embedded along with HTML and makes web pages alive
  • Originally named as LiveScript.
  • Executable in both browser and server which has Javascript engines like V8(chrome), SpiderMonkey(Firefox) etc.

Syntax help

STDIN Example

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line){
    console.log("Hello, " + line);
});

variable declaration

KeywordDescriptionScope
varVar is used to declare variables(old way of declaring variables)Function or global scope
letlet is also used to declare variables(new way)Global or block Scope
constconst is used to declare const values. Once the value is assigned, it can not be modifiedGlobal or block Scope

Backtick Strings

Interpolation

let greetings = `Hello ${name}`

Multi line Strings

const msg = `
hello
world!
`

Arrays

An array is a collection of items or values.

Syntax:

let arrayName = [value1, value2,..etc];
// or
let arrayName = new Array("value1","value2",..etc);

Example:

let mobiles = ["iPhone", "Samsung", "Pixel"];

// accessing an array
console.log(mobiles[0]);

// changing an array element
mobiles[3] = "Nokia";

Arrow functions

Arrow Functions helps developers to write code in concise way, it’s introduced in ES6.
Arrow functions can be written in multiple ways. Below are couple of ways to use arrow function but it can be written in many other ways as well.

Syntax:

() => expression

Example:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const squaresOfEvenNumbers = numbers.filter(ele => ele % 2 == 0)
                                    .map(ele => ele ** 2);
console.log(squaresOfEvenNumbers);

De-structuring

Arrays

let [firstName, lastName] = ['Foo', 'Bar']

Objects

let {firstName, lastName} = {
  firstName: 'Foo',
  lastName: 'Bar'
}

rest(...) operator

 const {
    title,
    firstName,
    lastName,
    ...rest
  } = record;

Spread(...) operator

//Object spread
const post = {
  ...options,
  type: "new"
}
//array spread
const users = [
  ...adminUsers,
  ...normalUsers
]

Functions

function greetings({ name = 'Foo' } = {}) { //Defaulting name to Foo
  console.log(`Hello ${name}!`);
}
 
greet() // Hello Foo
greet({ name: 'Bar' }) // Hi Bar

Loops

1. If:

IF is used to execute a block of code based on a condition.

Syntax

if(condition){
    // code
}

2. If-Else:

Else part is used to execute the block of code when the condition fails.

Syntax

if(condition){
    // code
} else {
    // code
}

3. Switch:

Switch is used to replace nested If-Else statements.

Syntax

switch(condition){
    case 'value1' :
        //code
        [break;]
    case 'value2' :
        //code
        [break;]
    .......
    default :
        //code
        [break;]
}

4. For

For loop is used to iterate a set of statements based on a condition.

for(Initialization; Condition; Increment/decrement){  
//code  
} 

5. While

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while (condition) {  
  // code 
}  

6. Do-While

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {  
  // code 
} while (condition); 

Classes

ES6 introduced classes along with OOPS concepts in JS. Class is similar to a function which you can think like kind of template which will get called when ever you initialize class.

Syntax:

class className {
  constructor() { ... } //Mandatory Class method
  method1() { ... }
  method2() { ... }
  ...
}

Example:

class Mobile {
  constructor(model) {
    this.name = model;
  }
}

mbl = new Mobile("iPhone");