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>
 

No comments:

Post a Comment