// Online Javascript Editor for free
// Write, Edit and Run your Javascript code using JS Online Compiler
/*console.log("Welcome to Programiz!");
console.log("Hello World!");*/
// in-line comment - Comment at the end of a code
/* This is a multi
line comment. */
number = 9;
/* ------------------------------------------------------ */
/* data types - undefined, null, boolean, string, symbol,
number and object */
/* Variable declaration types in Javascript */
var MyName = "Shankhaneel" // applicable everywhere
let ourName = "FreeCodeCamp" //applicable only within its scope
const pi = 3.14 // fixed value of teh variable
var a
var b = 9;
a = b; //assignment to a variable
var a = 5;
var b = 10;
var c = "This is a ";
a = a+1;
b = b+5;
c = c + "String!";
console.log(a);
console.log(b);
console.log(c);
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
----------------------
/* ---------------------------------------------- */
var StringVar = "I am a \"double quoted string\" " // use double quotes inside
double quotes by using \ in front of them
console.log(StringVar)
/* *** CODE OUTPUTS
\' single quote
\" double quote
\n new line
\r carriage return
\b backspace
\f form feed
***** */
var MyStr = "firstline \n\t\second line\n thirdline";
console.log(MyStr)
var NewStr = "This is the start. "+"This is the end" //concatenate string
console.log(NewStr)
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
------------------
/* ---------------------------------- */
var lastNameLength = 0;
var lastname = "Basak";
lastNameLength = lastname.length; // string length
console.log(lastNameLength);
/*---------------------------------------------------------*/
// Setup
let firstLetterOfLastName = "";
const lastName = "Lovelace";
// Only change code below this line
firstLetterOfLastName = lastName[0]; // Change this line
console.log(firstLetterOfLastName)
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
----------------------------------
/*----------------------------------------------------------------*/
/* WordBlank game */
function wordBlanks(myNoun,myAdjective,myVerb,myAdverb) {
var result = "";
result = "My "+ myNoun
return result;
}
console.log(wordBlanks("dog","big","runs","fast"));
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
----------
/*-----------------------------------------------------------*/
//arrays
var myArray=["Quincy",23];
var myArray=[["bulls",12],["red sox",15]];
var myArray=["Quincy",23];
var ArrayVal= myArray[0]
console.log(ArrayVal)
// Arrays can be changed by entering in their index value //
var myArray=[["bulls",12],["red sox",15]];
var ArrayVal= myArray[0][1];
console.log(ArrayVal);
var myArray=[["bulls",12],["red sox",15]];
myArray.push(["CSK",10],["DC",0]); //append at the end of array
console.log(myArray);
myArray.pop(); // delete last array element
console.log(myArray);
myArray.shift(); // delete first array element
console.log(myArray);
myArray.unshift("Harry"); // add array element at the beginning
console.log(myArray);
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
------------
/*------------------------------------------------------------------- */
//Functions
function FunctionName(){
console.log("Hello gain JS!")
};
FunctionName();
function FunctionName(a,b){
console.log("Hello gain JS!" +" "+ (a-b))
};
FunctionName(10,5);
—----------------------------------------------------------------------------------
------------------------------------------
/* Variables defined within a function have local scope
Variable outside a function have global scope */
var myVar = 10;
function VarDec(){
var neVar = 20
console.log(neVar)
}
//console.log(neVar); // get an error as not defined
function timesFive(num){ // return keyword use
return num * 5
}
console.log(timesFive(5))
var processed;
function processedArg(num){ //passing an arguement with return example
return (num+3)/5
}
processed = processedArg(7)
console.log(processed)
/* create a function to perform que i.e. remove an item from start in array
and add an item at the end of array */
function queueArray(arr,num){
arr.push(num);
return arr.shift();
}
var testArr = [1,2,3,4,5];
console.log("Before: "+ JSON.stringify(testArr));
console.log(queueArray(testArr,6));
console.log("After: "+ JSON.stringify(testArr));
/* ------------------------------------------------------------------------- */
function isitTrue(val){
if(val) {
return "Yes, it is true";
}
return "No, its false";
}
console.log(isitTrue());
function isitTrue(val){
if(val != 10) {
return "Yes, it is true";
}
return "No, its false";
}
console.log(isitTrue(5));
/* using === or !== as strict comparison so that third = checks datatype */
function isitTrue(val){
if(val=== 12) {
return "Yes, it is true";
}
return "No, its false";
}
console.log(isitTrue('12'));
//logical statement and && and operator //
function checkLogic(val){
if (val<=25 && val>= 10){
return "True";
}
return "False";
}
console.log(checkLogic(15));
—----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
--
// Online Javascript Editor for free
// Write, Edit and Run your Javascript code using JS Online Compiler
console.log("Welcome to Programiz!");
var Names = ["Hole in One","Eagle","Birdie","Par","Bogey","Double Bogey","Go Home"]
function golfscore(par,strokes){
if (strokes == 1){
return Names[0];
} else if (strokes <= par - 2){
return Names[1];
} else if (strokes == par - 1){
return Names[2];
} else if (strokes == par){
return Names[3];
} else if (strokes = par + 1){
return Names[4];
} else if (strokes = par + 2){
return Names[5];
} else if (strokes >= par + 3){
return Names[6];
}
}
console.log(golfscore(5,4));
/*------------------------------------------------------------*/
// Switch cases in Javascript
function caseInSwitch(val) {
var answer = "";
switch (val) {
case 1:
answer = "Alpha";
break;
case 2:
answer = "Beta";
break;
case 3:
answer = "Gamma";
break;
case 4:
answer = "Delta";
break;
default:
answer =" Stuff";
break;
}
return answer;
}
console.log(caseInSwitch(1));
//Muliple inputs with same output in a switch statement
function caseInSwitch(val) {
var answer = "";
switch (val) {
case 1:
case 2:
case 3:
answer = "Gamma";
break;
case 4:
case 5:
case 6:
answer = "Delta";
break;
default:
answer =" Stuff";
break;
}
return answer;
}
console.log(caseInSwitch(2));
/* Multiple if else if statements can be replaced with switch cases as well for
efficiency */
/* ------------------------------------------------------------- */
function returnBooleanVal(a,b){ //return Boolean output
if (a < b) {
return true;
}
else {
return false;
}
}
console.log(returnBooleanVal(5,7));
/* OR */
function returnBooleanVal(a,b){ //return Boolean output
return (a < b);
}
console.log(returnBooleanVal(5,7));
// return a function early
function abTest(a,b){
if (a<0 || b<0){
return undefined;
}
return(Math.round(Math.sqrt((Math.sqrt(b)+Math.sqrt(a),2))));
}
// card game simulation
var count = 0;
function cc(card){
switch(card){
case 2:
case 3:
case 4:
case 5:
case 6:
count ++;
break;
case 10:
case "K":
case "Q":
case "J":
case "A":
count --;
break;
}
var holdbet = "Hold";
if (count>0){
holdbet = "Bet";
}
return count + " " + holdbet;
}
cc(2), cc(3), cc("K");
console.log(cc(3));
/* ------------------------------------------------------ */
// Objects and Properties in JS
var ourDog = {
"name" : "rocky",
"legs" : 4,
"tails" : 1,
"friends" : ["everything"]
};
var nameValue = ourDog.name;
console.log(nameValue);
var leg = "legs";
console.log(ourDog[leg]);
ourDog.name = "Rocky Road"; // renaming a property in an object
ourDog.sound ="bow-wow";// adding a property in an object
console.log(ourDog.name);
delete ourDog.sound;// delete property from an object
//Objects can be used instead of a multiple switch cases
function phoneticLookup(val){
var lookup = {
"alpha":"Adams",
"beta":"Boston",
"gamma":"Chicago",
"delta":"Denver",
};
result = lookup[val];
return result;
}
console.log(phoneticLookup("alpha"));
// Nested Objects
var myStorage = {
"car": {
"inside":{
"glovebox":"maps",
"passenger":"crumbs"
},
"outside": {
"trunk":"jack"
}
}
};
var gloveBoxContents = myStorage.car.inside["glovebox"];
console.log(gloveBoxContents);
/* ------------------------------------------------------ */
// Record Collection Object Code
var collection = {
2548: {
albumTitle: 'Slippery When Wet',
artist: 'Bon Jovi',
tracks: ['Let It Rock', 'You Give Love a Bad Name']
},
2468: {
albumTitle: '1999',
artist: 'Prince',
tracks: ['1999', 'Little Red Corvette']
},
1245: {
artist: 'Robert Palmer',
tracks: []
},
5439: {
albumTitle: 'ABBA Gold'
}
};
// Only change code below this line
var collectionCopy = JSON.parse(JSON.stringify(collection));
function updateRecords(id, prop, value) {
if (value === "") {
delete collection[id][prop];
} else if (prop === "tracks") {
collection[id][prop] = collection[id][prop] || [];
collection[id][prop].push(value);
} else {
collection[id][prop] = value;
}
return collection;
}
updateRecords(2468,"tracks","test");
console.log(updateRecords(5439, 'artist', 'ABBA'));
/*
-----------------------------------------------------------------------------------
-- —--------------------------------- */
//Iterate using while loops
var myArray =[];
i = 0;
while (i<5){
myArray.push(i);
i++;
}
console.log(myArray);
//Iterate using for loops
var ourArray = [];
for (var i = 1; i < 6; i++) {
ourArray.push(i);
}
console.log(ourArray);
//Iterate through an array using for loop
var ourArr =[9,10,11,12];
var ourTotal = 0;
for (var i = 0; i < ourArr.length ; i++) {
ourTotal = ourTotal + ourArr[i];
}
console.log(ourTotal);
var product = 1;
function multiplyAll(arr){
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
product = product * arr[i][j];
}
}
return product;
}
var obj = multiplyAll([[1, 2], [3, 4], [5, 6]]);
console.log(obj);
// Profile Lookup Challenge using Javascript
var contacts = [
{
firstName: "Akira",
lastName: "Laine",
number: "0543236543",
likes: ["Pizza", "Coding", "Brownie Points"],
},
{
firstName: "Harry",
lastName: "Potter",
number: "0994372684",
likes: ["Hogwarts", "Magic", "Hagrid"],
},
{
firstName: "Sherlock",
lastName: "Holmes",
number: "0487345643",
likes: ["Intriguing Cases", "Violin"],
},
{
firstName: "Kristian",
lastName: "Vos",
number: "unknown",
likes: ["JavaScript", "Gaming", "Foxes"],
},
];
function lookUpProfile(name, prop) {
// Only change code below this line
for(var i=0; i < contacts.length ; i++){
if(contacts[i].firstName === name){
return contacts[i][prop] || "No such property";
}
}
// Only change code above this line
return "No such contact"
}
console.log(lookUpProfile("Akira", "likes"));
/*
-----------------------------------------------------------------------------------
--------------- */
// Parse Int function in JS
// ParseInt function takes a string value and returns an integer value
function ConvertToInteger(str){
return parseInt(str);
}
console.log(ConvertToInteger("56"));
// ParseInt function convert any string value to an integer of any base with an
additional arguement that would be the base of the number
function ConvertToBaseTwo(str){
return parseInt(str,2);
}
console.log(ConvertToBaseTwo("111"));
/*
-----------------------------------------------------------------------------------
--------------- */
//Ternary operators and their nesting
function checkSign(num){
return num>0 ? "positive" : num<0 ?"negative":"zero";
}
console.log(checkSign(-10));
/*
-----------------------------------------------------------------------------------
---------------- */
//Class syntax
function makeClass(){
class vegetable {
constructor(name){
this.name = name;
}
}
return vegetable;
}
const Vegetable = makeClass();
const carrot = new Vegetable('carrot');
console.log(carrot.name);