// FUNCTION EXERCISES - SOLUTIONS // Functions are an extremely important part of understanding how to program // and they also allow for an ideal way of testing out your general JavaScript // knowledge. // These problem statements are sourced from codingbat.com, // a great website to practice your code! // The problems will gradually get harder and harder. // // PROBLEM 1: SLEEPING IN // // Write a function called sleepIn that takes in two boolean parameters: weekday // and vacation. // // The parameter weekday is true if it is a weekday, and the parameter vacation is // true if we are on vacation. We sleep in if it is not a weekday or // we're on vacation. Return true if we sleep in. So some example input and output: // // sleepIn(false, false) → true // sleepIn(true, false) → false // sleepIn(false, true) → true function sleepIn(weekday, vacation) { if(!weekday && !vacation) return true; else if(weekday && !vacation) return false; else if(!weekday && vacation) return true; else return false; } // // PROBLEM 2: MONKEY TROUBLE // // We have two monkeys, a and b, and the parameters aSmile and bSmile indicate if // each is smiling. We are in trouble if they are both smiling or if neither of // them is smiling. Return true if we are in trouble. // // Example Input and Output // // monkeyTrouble(true, true) → true // monkeyTrouble(false, false) → true // monkeyTrouble(true, false) → false function monkeyTrouble(aSmile, bSmile) { if((aSmile && bSmile) || (!aSmile && !bSmile)) return true; else return false; } // // PROBLEM 3: STRING TIMES // // Given a string and a non-negative int n, return a larger // string that is n copies of the original string. // // Example input and output: // // stringTimes("Hi", 2) → "HiHi" // stringTimes("Hi", 3) → "HiHiHi" // stringTimes("Hi", 1) → "Hi" function stringTimes(str, n) { for(i=0 ; i<n ; i++) { str+=str; } return str; } // PROBLEM 4: LUCKY SUM // Given 3 numerical values, a b c, return their sum. However, if one of the values is // 13 then it does not count towards the sum and values to its right do not count. // So for example, if b is 13, then both b and c do not count. // // Hint (Explore using multiple return statements inside a single function!) // // Example input and output // // luckySum(1, 2, 3) → 6 // luckySum(1, 2, 13) → 3 // luckySum(1, 13, 3) → 1 function luckySum(a, b, c){ if(a==13) return 0; else if(b==13) return a; else if(c==13) return a+b; else { return a+b+c; } } // PROBLEM 5: // // You are driving a little too fast, and a police officer stops you. Write code to // compute the result, encoded as an int value: 0=no ticket, 1=small ticket, // 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 // and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. // Unless it is your birthday -- on that day, your speed can be 5 higher in all cases. // // Here are some example inputs and outputs: // // caught_speeding(60, false) → 0 // caught_speeding(65, false) → 1 // caught_speeding(65, true) → 0 function caught_speeding(speed, is_birthday){ //Code Goes Here } // BONUS: MAKE BRICKS // // We want to make a row of bricks that is goal inches long. We have a number of // small bricks (1 inch each) and big bricks (5 inches each). Return true if it // is possible to make the goal by choosing from the given bricks. This is a // little harder than it looks and can be done without any loops in a single line! // // If you can't figue this one out, don't worry, that's why its a bonus! // // makeBricks(3, 1, 8) → true // makeBricks(3, 1, 9) → false // makeBricks(3, 2, 10) → true function makeBricks(small, big, goal){ //Code Goes Here }
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.
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.
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);
});
Keyword | Description | Scope |
---|---|---|
var | Var is used to declare variables(old way of declaring variables) | Function or global scope |
let | let is also used to declare variables(new way) | Global or block Scope |
const | const is used to declare const values. Once the value is assigned, it can not be modified | Global or block Scope |
let greetings = `Hello ${name}`
const msg = `
hello
world!
`
An array is a collection of items or values.
let arrayName = [value1, value2,..etc];
// or
let arrayName = new Array("value1","value2",..etc);
let mobiles = ["iPhone", "Samsung", "Pixel"];
// accessing an array
console.log(mobiles[0]);
// changing an array element
mobiles[3] = "Nokia";
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.
() => expression
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);
let [firstName, lastName] = ['Foo', 'Bar']
let {firstName, lastName} = {
firstName: 'Foo',
lastName: 'Bar'
}
const {
title,
firstName,
lastName,
...rest
} = record;
//Object spread
const post = {
...options,
type: "new"
}
//array spread
const users = [
...adminUsers,
...normalUsers
]
function greetings({ name = 'Foo' } = {}) { //Defaulting name to Foo
console.log(`Hello ${name}!`);
}
greet() // Hello Foo
greet({ name: 'Bar' }) // Hi Bar
IF is used to execute a block of code based on a condition.
if(condition){
// code
}
Else part is used to execute the block of code when the condition fails.
if(condition){
// code
} else {
// code
}
Switch is used to replace nested If-Else statements.
switch(condition){
case 'value1' :
//code
[break;]
case 'value2' :
//code
[break;]
.......
default :
//code
[break;]
}
For loop is used to iterate a set of statements based on a condition.
for(Initialization; Condition; Increment/decrement){
//code
}
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
}
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);
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.
class className {
constructor() { ... } //Mandatory Class method
method1() { ... }
method2() { ... }
...
}
class Mobile {
constructor(model) {
this.name = model;
}
}
mbl = new Mobile("iPhone");