Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

22 September 2019

JavaScript Fundamentals

Pre requisites:

 Download Editor for java script like Visual Studio Code from below link:
https://code.visualstudio.com/

Download node js from below link:
https://nodejs.org/en/download/

Operator Precedence can be observed in below link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence



Let keyword scope is limited to the code block, but var keyword scope is not limited.

Example of let:
if(true) { let foo = 9; } console.log(foo); //output : error if(true) { let foo = 9; } console.log(foo); // output : 9
So it is preferable to use let over var.

REST Parameters:
REST parameters must be last elements in the parameter list of function
function sendCars(...carIds) {
carIds.forEach(id => console.log(id));
}
sendCars(100,200,555);
//output: 100 200 555

typeof method examples:
<pre>
typeof(1)  // number
typeof(true) //boolean
typeof("hello") // string
typeof(function() {}); //function
typeof({}); // object
typeof(null); //object
typeof(undefined); // undefined
typeof(NaN); //number
</pre>

common type conversions:
foo.toString();  // convert to string
Number.parseInt('55');  // convert to integer
Number.parseFloat('55.99');  // convert to float
Controlling loops:
for(let i=0;i<4;i++) { if(i===2) { continue; } console.log(i); } // output: 0 1 3 for(let i=0;i<4;i++) { if(i===2) { break; } console.log(i); } // output: 0 1
De-structuring of Arrays and Objects:
[a,b] = arr;    // arr is array like let arr = [10, 20];

({a, b} = obj); // obj contents are a=10, b=20 let obj = {a=10,b=20};

Operators: The best practice is to use triple equal operation which compare type as well. === is called strict equality check, it will compare value as well as type. == will only check/compare value. for example console.log(1===true) will print false, because 1 is of type integer and true is of type boolean. let abc='123'; console.log (abc===123) //output is false. abc is of type string, 123 is of type integer but if we use console.log(abc==123) // output is true. because it will do type conversion like integer 123 is converted to string and compared with abc.  === will not do type conversion.

if(a==b) if(var1 != var2) { }
if(a===b) if(var1 !== var2) { }
 
unary operators:
let year =1967;
console.log(++year); //output: 1968
 
let year = 1967
console.log(year++); // output: 1967
 
&&, || and ! operators work similar to Java.
 
Block Scope:
if(5===5) { let msg = "Good Morning"; console.log(msg); // Good Morning } console.log(msg); //error -------------------------------- let name='outside'; if(1===1) { let name = 'inside'; console.log(name); // output is inside } console.log(name); //output is outside
Immediately Invoked Function Expressions: It is also called java script function executes as soon as it is defined. It is also called self executing anonymous function design pattern. Ex:
let app = (function()
{ let carId = 123;
console.log('in function');
return {};
})();
console.log(app);  // output:  in function  {}
let app = ( function() {
let getId =10;
return({getId:getId});
})();
console.log(app.getId);  // output: 10
----------------------------------------------- let O = { carId : 123, getId : function() { return this.carId; }; }; console.log(o.getId()); // output: 123
Arrow Functions
arrow functions make function declarations concise
(i) let aa = () => 123; console.log(aa()); // output: 123 (ii) let bb = (prefix, suffix) => { return(prefix + "madhu"+suffix); }; console.log(bb("mr","sudhan")); Output: Mr Madhu Sudhan
Default Parameters even if we do not pass a value for default parameters it will take them,
let bb = function(aa,bb="balls") { return(aa+bb); }; console.log(bb("one", "ball")); // one ball console.log(bb("two")); // output: two balls
JSON ( Javascript object notation) ---------------------------------- Example of JSON.stringify method which will convert / return string from JSON object A common use of JSON is to exchange data to/from a web server. When sending data to a web server, the data has to be a string.Convert a JavaScript object into a string with JSON.stringify().
var obj = { name: "John", age: 30, city: "New York" }; var myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON; Example of JSON.parse method which will extract JSON object fom string. let jsonIn = ` [ {"carId": 123}, {"carId": 456}, {"carId": 789} ] `; let carIds = JSON.parse(jsonIn); console.log(carIds); // output: this will print object notation of jsonIn. Initially it was string now it become json object.
Array methods
// html code
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <h1>javascript practice</h1>
    <p id="demo1" onclick="testFilter()">click here to filter example</p>
    <br>
    <p id="demo2" onclick="testFind()">click here to find example</p>
  </body>

</html>
 
// javascript code // filter example, returns list of array elements matching criteria let carList = [ { id:1,model:"amaze"}, {id:2,model:"m800"}, {id:3,model:"Hyndai i10"} ]; let findCar = carList.filter( car => car.model==="m800"); function testFilter() { document.getElementById("demo1").innerHTML = JSON.stringify(findCar); } // find method returns only first instance of the match from the array let empList = [ {id:1,name:'madhu',dept:'devOps'}, {id:2, name:'manikanth', dept:'P&T'} ]; let findEmployee = empList.find(employee => employee.name === 'manikanth'); let employeeString = JSON.stringify(findEmployee); function testFind() { document.getElementById("demo2").innerHTML = employeeString; } //The forEach() method executes a provided function once for each element var array1 = ['a', 'b', 'c']; array1.forEach(function(element) { console.log("Element value :"+element); }); //output //javascript practice //[{"id":2,"model":"m800"}] //{"id":2,"name":"manikanth","dept":"P&T"}
class usage in javascript
// class example class Car { constructor(id) { console.log(id); } } let car = new Car(10); // output is 10 //class example 2: setting local variable of class and updating it outside of class class Vehicle { constructor(id) { this.id = id; console.log(this.id); } } let vehicle = new Vehicle(20); vehicle.id = 200; console.log(vehicle.id); // class example 3 : using methods in class class CarVehicle { constructor(id) { this.id = id; } identify() { return `Car Id: ${this.id}`; } } let carVehicle = new CarVehicle(123); console.log( carVehicle.identify() ); // 123 ------------------------------------------ Example 1 on Inheritance: class Vehicle { constructor() { this.type = 'car'; } start() { return `Starting: ${this.type}`; } } class Car extends Vehicle { } let car = new Car(); console.log( car.type ); // car console.log(car.start()); // Starting car Example 2 on Inheritance: class Vehicle { constructor() { this.type = 'car'; } start() { return `Starting: ${this.type}`; } } class Car extends Vehicle { start() { return 'In subclass+ super.start()'; } } let car = new Car(); console.log( car.type ); // car console.log(car.start()); // In subclass Starting car //Module: Each class need to be placed in separate file and each file is a module now. //export the class in the file to make sure we can import or re-use in different file. // code in models directory car.js export class Car { constructor(id) { this.id = id; } } // import the module in different file. import { Car } from './models/car.js'; let car = new Car(123); console.log( car.id );
Advanced Concepts in JavaScript
window object
location object
document object

document.getElementById('elementId');

document.getElementsByClassName('className');

document.getElementsByTagName('tagName');

let element = document.getElementById('elementId');
element.textContent = 'new text';

eleent.style.color = 'blue';


-----------------------------------
//try, catch, finally
----------------------------------
try {
let car = newCar;
}
catch(error) {
console.log('error: ', error);
}
finally {
console.log('this always executes');
}


-----------------------
//user defined errors
-----------------------
try {
// code here...
throw new Error('my custom error');
}
catch(error) {
console.log('error: ', error);
}
finally {
console.log('this always executes');
}

------------------------------
// jQuery get and post examples
// install jquery package using 'npm install jquery'
------------------------------

// jQuery and HTTP GET
import $ from 'jquery';
$.get("http://myid.mockapi.io/api/v1/users",
       data => console.log('data: ', data)
 );

//jQuery and HTTP Post
import $ from 'jquery';

let user = {
    name: 'Mark Zamoyta',
    
  avatar: 'mark.jpg'
};


let promise = $.post(
"http://z5b32a4fd82407e001413f1df.mockapi.io/api/v1/users", user
);


promise.then(
data => console.log('data: ', data),
 error => console.log('error: ', error)
);

----------------------------------------------
// Handling submit event
---------------------------------------------
--------------------
// JS Code
--------------------

import $ from 'jquery';

let form = document.getElementById('user-form');

 form.addEventListener('submit', event => {

 let user = form.elements['user'];
 let avatarFile = form.elements['avatar-file'];

 let posting = {
  user: user.value,
  avatarFile: avatarFile.value
 };
 
 let promise = $.post(
  "http://5b32a4fd82407e001413f1df.mockapi.io/api/v1/users", posting
 );
 promise.then(
     data => console.log('success: ', data),
     error => console.log('error: ', error)
 );
 

 event.preventDefault();

});
 
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Fundamentals</title>
</head>
<body>

<h3>JavaScript Fundamentals</h3>
<form action="/somepath" method="post" id="user-form">
  <input name="user" placeholder="User Name"/>
  <span id="user-error"></span>
  <br>
  <input name="avatar-file" placeholder="Avatar File"/>
  <span id="avatar-error"></span>
  <br>
  <button type="submit">Submit</button>
</form>
</body>
</html>
 

12 September 2019

Java Script : Getting Started

To practice java script code use below online editor
http://plnkr.co/  --> click on 'launch editor' --> you would observe sample




settings are available on right hand side, using this we can do basic settings on plunker editor:


Java script is Case Sensitive.

Basic Hello World program

Add below line in script.js and click on run for output. You would see output in console of browser (press F12).
Example 1:
console.log("Hello World!!");

Example 2:
let aa = "this is",
     bb = "example";
console.log(aa,bb);


Output in console of browser: this is example

Example 3:
let aa = 10.00;
let bb = 20.00;
console.log(aa+bb);
output: 30

Example 4:
let aa = 10.00;
let bb = "20.00";
console.log(aa+bb);
output: 1020.00

Operations in Java Script:
It is similar to java / c all of the + - * / % works as expected similar to other object oriented languages.

Comments in JavaScript:
// this is a comment
let name = "madhu";

or

// this is comment 1
//this is comment 2
let name = "madhu";

or

/* this is comment 1
this is comment 2     */
let name = "madhu";

or

let answer = 32;   // this is freezing point
console.log(answer);

 Boolean Data Types: 

let flag = true;
console.log(flag, typeof(flag));
output: true  "boolean"

Difference between undefined and null:
when  a variable is declared without any value then its value is undefined.
let x;
console.log(x);
output:   undefined  // we can not assign undefined to a variable.

null can be assigned to a variable using our source code.

declaring and accessing array:

let a = [];
console.log(a[0]);  // undefined

let a = ["a1","a2","a3"];

console.log(a[0]);
console.log(a[1]);
console.log(a[2]);
console.log(a);

let a = [1,2,3,4];
console.log(a);
console.log(a.length);

let values = [];
 values.push(1);
values.push(2);
values.push(3);
console.log(values);
output: [1,2,3]

let values = [1,2,3];
values.pop();
console.log(values);
output: [1,2]

let values = [1,2,3];
let result = values.pop();
console.log(result);
output: 3 // this will work similar to stack push and pop by removing last inserted item (LIFO).

let values = [1,2,3,44];
let result = values.shift();
console.log(result, values);
output: 1, [2 3 44]

splice() method used to delete the elements in given range also insert some elements.

let values = [1,2,3,4,5];
let result = values.splice(0,1);
console.log(values);
output: [2,3,4,5] // from 0th index delete one element

let values = [1,2,3,4,5];
let result = values.splice(0,1,6,7);
console.log(values);
output: [6,7, 2,3,4,5] // from 0th index delete one element, then insert 6 & 7.

we have several methods on arrays as specified here.

Player Cards Game Phase 1 for POC:
let deck = [ "Ace of Spades",
                   "Two of Spades",
                   "Three of Spades"];
let playerCards = [ deck[0], deck[2]];

console.log("Welcome to BlackJack");
console.log("You are dealt:");
console.log("     "+playerCards[0]);
console.log("     "+playerCards[1]);

Program flow:

let text = 'Hyderabad';
let num = 7;
if(text === 'Hyderabad')
{
num = 17;
}
console.log(num);
output: 17

what qualifies false in javascript:
false
0
NaN
null
undefined
"" // two double quotes with empty value
'' // two single quotes with empty value

If else example:
let state = 'TS';
let taxPer = 7;
if(text ==='TS')
{
taxPer = 17;
}
else
{
taxPer = 10;
}
console.log(taxPer);
output: 17

Switch Statement:

let state = 'TX';

switch (state)
case 'NY' : 
console.log("NY");
break;
case 'TX':
console.log("TX");
break;
default:
console.log("default");
break;
} 

for () loop:
for(let i=0;i<10;i++)
{
console.log(i);
}

while loop:
let i=10;
while(i<=10)
{
console.log(i);
i--;
}

Functions:
Example 1:
function showMessage()
{
 console.log("hello world");
}

showMessage();

Example 2:
function showMessage(name,age)
{
console.log("Hello"+name, age);
}

showMessage('madhu',37);
output: Hello madhu 37
showMessage('madhu');
output: Hello madhu undefined

Example 3:
// function returning values
function ageCalculator(year)
{
if (year > 1980)
return 30;
else if(year > 1970)
return 40;
else
return 50;
}

Example 4:
//variable scope, scope is limited to its function.

function tripleSum(number)
{
let output = number*3;
return output;
}
console.log(tripleSum(3)); // print 9
console.log(output); // output variable is undefined (error)

Objects:

Example 1:
let student = {
name : "madhu",
rollno : 1224,
dept : "csit",
active : false
};
console.log(student.name);  // madhu
console.log(student.rollno); // 1224
console.log(student.active); // false 

Example 2:
//passing objects to functions
let card = {
suit : "diamonds",
value : "queen"
};
function changeSuit(card)
{
card.suit = "spades";
}

changeSuit(card);
console.log(card.suit);
}

Example 3:
//array of objects
let cards = 
[
{
name : 'aa',
id : 123
},
{
name : 'bb',
id : 124
}
];
console.log(cards[1].id); //output is 123

Go to wiki and search for Built-in Objects for more information.

Example 4:
// NaN 
let a = 2/0;
console.log(Number.isNaN(a));  // true
DOM
Document Object Model: defines how data on webpage is organized and manipulated.
Example 1:
//changing paragraph text
HTML
<p id="text-area"></p>

JavaScript
let paragraph = document.getElementById('text-area');
paragraph.innerText = "This is paragraph text…"; 


Example 2:
HTML
<button id="okButton">Ok</button>
 

JavaScript::
let okButton = document.getElementById('ok-button');
okButton.addEventListener('click', function() {
// code goes here
});


Example 3:
// ::Removing and adding elements back:: javascript

let paragraph = document.getElementById('text-area');
paragraph.style.display = 'none'; // remove it
paragraph.style.display = 'inline'; // add it back

Demo of our learnings:
HTML code:
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
    <h1 id="title">Blackjack</h1>
    <h4>by Mark Zamoyta</h4>

    <p id="text-area">Welcome to Blackjack!</p>
    <button id="new-game-button">New Game!</button>
    <button id="hit-button">Hit!</button>
    <button id="stay-button">Stay</button>
   
    <script src="blackjack-m6.js"></script>
   
  </body>

</html>
 


java script code: 
// // Blackjack // by Mark Zamoyta // // Card variables let suits = ['Hearts', 'Clubs', 'Diamonds', 'Spades'], values = ['Ace', 'King', 'Queen', 'Jack', 'Ten', 'Nine', 'Eight', 'Seven', 'Six', 'Five', 'Four', 'Three', 'Two']; // DOM variables let textArea = document.getElementById('text-area'), newGameButton = document.getElementById('new-game-button'), hitButton = document.getElementById('hit-button'), stayButton = document.getElementById('stay-button'); // Game variables let gameStarted = false, gameOver = false, playerWon = false, dealerCards = [], playerCards = [], dealerScore = 0, playerScore = 0, deck = []; hitButton.style.display = 'none'; stayButton.style.display = 'none'; showStatus(); newGameButton.addEventListener('click', function() { gameStarted = true; gameOver = false; playerWon = false; deck = createDeck(); shuffleDeck(deck); dealerCards = [ getNextCard(), getNextCard() ]; playerCards = [ getNextCard(), getNextCard() ]; newGameButton.style.display = 'none'; hitButton.style.display = 'inline'; stayButton.style.display = 'inline'; showStatus(); }); hitButton.addEventListener('click', function() { playerCards.push(getNextCard()); checkForEndOfGame(); showStatus(); }); stayButton.addEventListener('click', function() { gameOver = true; checkForEndOfGame(); showStatus(); }); function createDeck() { let deck = []; for (let suitIdx = 0; suitIdx < suits.length; suitIdx++) { for (let valueIdx = 0; valueIdx < values.length; valueIdx++) { let card = { suit: suits[suitIdx], value: values[valueIdx] }; deck.push( card ); } } return deck; } function shuffleDeck(deck) { for (let i = 0; i < deck.length; i++) { let swapIdx = Math.trunc(Math.random() * deck.length); let tmp = deck[swapIdx]; deck[swapIdx] = deck[i]; deck[i] = tmp; } } function getCardString(card) { return card.value + ' of ' + card.suit; } function getNextCard() { return deck.shift(); } function getCardNumericValue(card) { switch(card.value) { case 'Ace': return 1; case 'Two': return 2; case 'Three': return 3; case 'Four': return 4; case 'Five': return 5; case 'Six': return 6; case 'Seven': return 7; case 'Eight': return 8; case 'Nine': return 9; default: return 10; } } function getScore(cardArray) { let score = 0; let hasAce = false; for (let i = 0; i < cardArray.length; i++) { let card = cardArray[i]; score += getCardNumericValue(card); if (card.value === 'Ace') { hasAce = true; } } if (hasAce && score + 10 <= 21) { return score + 10; } return score; } function updateScores() { dealerScore = getScore(dealerCards); playerScore = getScore(playerCards); } function checkForEndOfGame() { updateScores(); if (gameOver) { // let dealer take cards while(dealerScore < playerScore && playerScore <= 21 && dealerScore <= 21) { dealerCards.push(getNextCard()); updateScores(); } } if (playerScore > 21) { playerWon = false; gameOver = true; } else if (dealerScore > 21) { playerWon = true; gameOver = true; } else if (gameOver) { if (playerScore > dealerScore) { playerWon = true; } else { playerWon = false; } } } function showStatus() { if (!gameStarted) { textArea.innerText = 'Welcome to Blackjack!'; return; } let dealerCardString = ''; for (let i=0; i < dealerCards.length; i++) { dealerCardString += getCardString(dealerCards[i]) + '\n'; } let playerCardString = ''; for (let i=0; i < playerCards.length; i++) { playerCardString += getCardString(playerCards[i]) + '\n'; } updateScores(); textArea.innerText = 'Dealer has:\n' + dealerCardString + '(score: '+ dealerScore + ')\n\n' + 'Player has:\n' + playerCardString + '(score: '+ playerScore + ')\n\n'; if (gameOver) { if (playerWon) { textArea.innerText += "YOU WIN!"; } else { textArea.innerText += "DEALER WINS"; } newGameButton.style.display = 'inline'; hitButton.style.display = 'none'; stayButton.style.display = 'none'; } }