//Функция, которая возвращает куб числа. Число передается параметром.
// let num = 2;
// function func(num) {
//   return Math.pow(num, 3)
// }

// console.log(func(num))

//Функция, которая отнимает от первого числа второе и делит на третье.
// function math(a,b,c) {
//   return (a-b)/c
// }
// console.log(math(100,50,5))

//Сделайте функцию, которая принимает параметром число от 1 до 7, а возвращает день недели на русском языке.
// let day = 1;
// function dayString(day) {
//   switch(day){
//     case 1: console.log('Понедельник')
//     break;
//     case 2: console.log('Вторник')
//     break;
//     case 3: console.log('Среда')
//     break;
//     case 4: console.log('Четверг')
//     break;
//     case 5: console.log('Пятница')
//     break;
//     case 6: console.log('Суббота')
//     break;
//     case 7: console.log('Воскресенье')
//     break;
//     default: 
//     console.log('У вас какая неделя?')
//   }
// }
// dayString(day)

//Сделайте функцию, которая параметрами принимает 2 числа. 
//Если эти числа равны - пусть функция вернет true, а если не равны - false.
// function comparison(a,b) {
//   if (a === b) {
//     return console.log(true)
//   } else {
//     return console.log(false)
//   }
// }

// comparison(1,1)

//Дан массив с числами. Создайте из него новый массив, где останутся лежать только положительные числа. 
//Создайте для этого вспомогательную функцию isPositive(), 
//которая параметром будет принимать число и возвращать true, если число положительное, 
//и false - если отрицательное.
// let arr = [1, 2, 3, -1, -2, -3];

// function isPositive(num) {
// 	if (num >=0) {
// 		return true;
// 	} else {
// 		return false;
// 	}
// }
// let newArr = [];
// for (let i = 0; i <= arr.length; i++) {
// 	if (isPositive(arr[i])) {
// 		newArr.push(arr[i]);
// 	}
// }
// console.log(newArr);

//Функция, принимает два аргумента: массив и число. 
//Вывести массив, у которого каждый элемент умножен на это число
// function getDigitsSum(array, num) {
//   return array.map(item => item*num);
// } 

// console.log(getDigitsSum([1,2,4],3))

//Передано число в аргумент функции. Найти сумму цифр этого числа.
// function main(number) {
//   let year = number.toString().split('')
// let yearN = []
// for (let i=0; i< year.length; i++) {
//     let num = +year[i]
//     yearN.push(num)
// }
// console.log('number:', number)
// console.log('year:', year)
// console.log('yearN:',yearN.reduce((item, acc) => item + acc));
// }

// main(123456) 

//Функция для получения случайного целого числа в заданном диапазоне.
// такая функция называется стрелочной
// ~~ - это сокращение для `Math.floor()` - округление числа до целого в меньшую сторону
// `Math.random()` возвращает случайное число от 0 до 1
const getRandomInt = (min, max) => Math.floor((min + Math.random() * (max - min + 1)))

console.log(`Случайное целое число в диапазоне от 0 до 100: ${getRandomInt(0, 100)}`)

//Функция для преобразования километров в мили
const km = 5

const f = 0.621371

const m = km * f

console.log(`${km} километров - это ${m.toFixed(2)} миль`)


//Функция для определения того, каким является число: положительным, отрицательным или нулем
// сигнатура обычной функции
// фигурные скобки имеют принципиальное значение,
// обозначая блоки кода
function isPosNeg(n) {
 // если
 if (n > 0) {
   return 'Positive'
 // иначе если
 } else if (n === 0) {
   return 'Null'
 // иначе
 } else {
   return 'Negative'
 }
}
console.log(isPosNeg(5))


//Функция для определения того, каким является число, четным или нечетным
// тернарный оператор
// условие ? истина : ложь
// обратите внимание, что в `JS` имеется 2 оператора равенства
// старайтесь всегда использовать `===`
const isOddEven = (n) => (n % 2 === 0 ? 'Even' : 'Odd')

console.log(isOddEven(5))

//Функция для определения наибольшего числа
function getLargestNum(n1, n2, n3) {
 if (n1 >= n2 && n1 >= n3) {
   return n1
 } else if (n2 >= n1 && n2 >= n3) {
   return n2
 } else {
   return n3
 }
}

console.log(getLargestNum(1, 3, 2)) // 3

// существует встроенная функция
console.log(Math.max(3, 1, 2))





 

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");