Published on

Javascript Notes

Authors
What is JavaScript?

JavaScript is the programming language of the web. Before it used to be a client-side language but the definition now has changed.

JavaScript was developed by Brendan Eich in 1995. It has become an ECMA standard (a standard for scripting language) in 1997.

Over the last 10 years, Node.js has enabled JavaScript programming outside of web browsers and now it's one of most used programming language among software developers.

Before it used to be only web, in current scenario you can JS to make desktop and mobile apps also.

"Java v/s JavaScript"

The name "JavaScript" is little bit misleading. One of the question most of the beginner ask how Java is related to JavaScript. And it's one of worst comparison ever. JS is completely different from Java programming language. It's like comparing a car with carpet.

Usage and History

  • Web Browsers
  • Applications
    • Desktop - Electron
    • Mobile - Cordova
    • Server - Node.js
What is ES6/ES7

ECMAScript - European Computer Manufacturers Association Script

  • History / Versions
    • 1995 - Created
    • 1997 - Standardizing
    • 1999 - ECMAScript 3
    • 2009 - ECMAScript 5
    • 2015 ECMAScript 2015 (ES6)
    • Yearly updates since then

Tools that we need

  • NodeJS
  • Code Editor - Sublime, Atom, VSCode
  • Browser - Chrome

NodeJs should be installed in your system. If you haven't installed please google how to install it in your system. Same goes with code editor and browser.

I personally use VSCode for almost everything. But you can choose any code editor you want.

So I have created one folder in my desktop called JS. And inside that folder I have created one file named helloWorld.js

Here you can see I am executing the code like this. I have just console logged Hello World !. It's like print function in other programming language.

VSCode has integrated terminal, as you can see I have used the command node to execute the file. You can also do the same. Make sure Node is installed in your system.

1.Basics of Variables & Constant's

// Anything following double slashes is an English-language comment.
// Read the comments carefully: they explain the JavaScript code.

// A variable is a symbolic name for a value.
// Variables are declared with the let keyword:
let x; // Declare a variable named x.

// Values can be assigned to variables with an = sign
x = 0; // Now the variable x has the value 0
x; // => 0: A variable evaluates to its value.

// JavaScript supports several types of values
x = 1; // Numbers.
x = 0.01; // Numbers can be integers or reals.
x = "hello world"; // Strings of text in quotation marks.
x = "JavaScript"; // Single quote marks also delimit strings.
x = true; // A Boolean value.
x = false; // The other Boolean value.
x = null; // Null is a special value that means "no value."
x = undefined; // Undefined is another special value like null.

Two other very important types that JavaScript programs can manipulate are objects and arrays. We will talk about that later.

Constants - variable that cannot change
  • const
    
    • Must be initiated - const x = 2
Variable Declarations
  • let;
    
  • var
    
    • undefined before declaration

2.Operators

// Operators act on values (the operands) to produce a new value.
// Arithmetic operators are some of the simplest:
2 + 2; // => 4: addition
4 - 2; // => 2: subtraction
2 * 2; // => 4: multiplication
4 / 2; // => 2: division
points[1].x - points[0].x; // => 1: more complicated operands also work
"53" + "2"; // => "532": + adds numbers, concatenates strings

// JavaScript defines some shorthand arithmetic operators
let count = 0; // Define a variable
count++; // Increment the variable
count--; // Decrement the variable
count += 2; // Add 2: same as count = count + 2;
count *= 3; // Multiply by 3: same as count = count * 3;
count; // => 6: variable names are expressions, too.

// Equality and relational operators test whether two values are equal,
// unequal, less than, greater than, and so on. They evaluate to true or false.
let x = 4,
  y = 5; // These = signs are assignment, not equality tests
x === y; // => false: equality
x !== y; // => true: inequality
x < y; // => true: less-than
x <= y; // => true: less-than or equal
x > y; // => false: greater-than
x >= y; // => false: greater-than or equal
"four" === "five"; // => false: the two strings are different
(false ===
  (x > y)(
    // => true: false is equal to false

    // Logical operators combine or invert boolean values
    x === 4
  ) &&
  (y === 5)(
    // => true: both comparisons are true. && is AND
    x > 4
  )) ||
  y < 5; // => false: neither comparison is true. || is OR
!(x === y); // => true: ! inverts a boolean value
Equality operators
  • (var1 == var2) - JS will attempt to convert to matching types for comparison
  • (var1 === var2) - No conversion, types must be equal. 'Strict Equality'

Unary operators

  • ++count or count++ - Increment
  • --var or var-- - Decrement
  • +var - string to numertical type
  • -var - negation, changes sign of numeric type

Logical (Boolean) operators

  • && - AND
  • || -- OR
  • ! NOT, convert to bool, flip

Relational Operators

  • Compared by ASCII
  • >, >=- greater than, greater than or equal to

  • <,<= - less than, less than or equal to

Conditional Operators

  • ? used in shorthand if

  • condition ? exprIfTrue : exprIfFalse
    
    • ex: console.log((5>4) ? 'yes' : 'no'); // yes

Assignment Operators

-+=, -=, /=, *=, %=

  • <= - shift bits to left
  • >>= - shift bits to right
  • >>>= - shift but keep the sign

typeof()

  • Returns a string
typeof 1; // 'number'
typeof true; // 'boolean'
typeof "Hello"; // 'string'
typeof function () {}; // 'function'
typeof {}; // 'object'
typeof null; // 'object'
typeof undefined; // 'undefined'
typeof NaN; // 'number'
// NaN - not a number

Common Type Conversions

  • Convert to string - foo.toString();
  • String to integer -Number.parseInt('55');
  • String to number - Number.parseFloat('55.99');

Controlling Loops

  • Use breakto get out of a loop
  • Use continue to finish iteration (without rest of body)

3. Functions and Scope

Function scope
  • Variables that can be accessed with a function of a nested function
  • *lifetime*
  • If not available in function, looks to parent function
Block scope
  • { } not in a function

  • Using letfor block scope

  • No block scope for var, no such thing for these

  • IIFE's - Immediately Invoked Function Expression

  • ex:

    (function () {
      console.log("in function");
    })();
    // can return values this way
    let app = (function () {
      let cardId = 123;
      console.log("in function");
      return {};
    })();
    
    console.log(app);
    // [Function: app]
    

Closures

  • Keeping a function, it's variables and nested function in scope

  • ex:

    let app = (function () {
      let cardId = 123;
      let getId = function () {
        return cardId;
      };
      return {
        getId: getId, //  reference
      };
    })();
    console.log(app.getId());
    // 123
    

The this keyword

  • Context for the function

  • ex:

    let o = {
      carId: 123,
      getId: function () {
        return this.carId;
      },
    };
    console.log(o.getId());
    // 123
    
    • Context can change, ie this value can change

Arrow Functions

  • Function declarations

    • Arrow function symbol:=>
    • let getId = () => 123; //no params
  • More examples

    let getId = (prefix) => prefix + 456;
    console.log(getId("ID: ")); // ID: 456
    
    let getId = (prefix, suffix) => prefix + 456 + suffix;
    console.log(getId("ID: ", "!")); // ID: 456!
    
    // with braces / return keyword required
    let getId = (prefix, suffix) => {
      return prefix + 456 + suffix;
    };
    // same result as previous
    
    // use with underscore:
    let getId = (_) => 456;
    

Arrow functions do NOT have their own this<value. thisrefers to enclosing context

Default Parameters

  • ex:

    let trackCar = function (carId, city = "NY") {
      // using backticks for interpreting variables
      console.log(`Tracking ${carId} in ${city}.`);
    };
    
  • Like other defaults, must be on right side.

  • Default overwritten if defined.

4.Objects and Arrays

Destructuring Arrays

  • Assign values in array to variables
let carIds = [1, 2, 5];
let [car1, car2, car3] = carIds;
// with rest parameters:
let car1, remainingCars;
[car1, ...remainingCars] = carIds;
// log
// 1 [2, 5]

Destructuring Objects

  • instead of [ ] for objects
let car = { id: 5000, style: "convertible" };
let { id, style } = car;
// log
// 5000, convertible
  • Put destructuring in ( ) if variables already declared
let id, style;
({ id, style } = car);

Spread Syntax

  • Take array, spread out elements for parameters
  • Similar to rest syntax, does the opposite
let carIds = [100, 300, 500];
startCars(...carIds);
  • Can iterate through arrays and strings

Constructor Functions

  • Examples

    function Car() {} // capitalized name as convention`
    let car = new Car();
    
  • function Car(id) {
      this.carId = id;
    }
    let car = new Car(123);
    console.log(car.carId); // 123
    
  • Method: function run on an object

    function Car(id) {
      this.carId = id;
      this.start = function () {
        console.log("Start: " + this.carId);
      };
    }
    let vehicle = new Car(123);
    vehicle.start(); // Start: 123
    

Prototypes

// using previous example
Car.prototype.start = function () {
  console.log("Start: " + this.carId);
}; // single copy, instead of one function for each object
  • Expanding Objects using Prototypes
    • Give new functionality to objects
String.prototype.hello = function () {
  return this.toString() + " Hello";
};
console.log("foo".hello()); // foo Hello

Javascript Object Notation (JSON)

let car = {
  id: 123,
  style: "convertible",
};
console.log(JSON.stringify(car));
// { "id": 123, "style": "convertible" }
// Array to JSON
let carIds = [{ carId: 123 }, { carId: 456 }, { carId: 789 }];
console.log(JSON.stringify(carIds));
//  [{ "carId": 123 }, { "carId": 456 }, ...]
// Parsing JSON:
let jsonIn = [{ carId: 123 }, { carId: 456 }, { carId: 789 }];
let carIds = JSON.parse(jsonIn);
// log: [ { carId: 123 }, { carId: 456 }, { carId: 789 } ]

Array Iteration

Examples:

carIds.foreach((car) => console.log(car));
carIds.foreach((car, index) => console.log(car, index));

//  only some elements
let convertibles = carIds.filter((car) => car.style === "convertible");

// every case. find, condition, T/F, all elements
let result = carIds.every((car) => car.carId > 0); // true

// retrieve first instance matching condition
let car = carIds.find((car) => car.carId > 500);

Classes and Modules

  • Class Basics
class Car {}
let car = new Car();

Constructors and properties

  • constructor - function executed when new instance of a class is created
class Car() {
    constructor(id) {   // constructor
        this.id = id;   // property
    }
}   // car.id to access property directly

Methods

  • No function keyword needed

    • Example within class Car
    identify(params) {
        return `Car Id: ${this.id}`;
        // dont need `this` to access
    }
    

Inheritance

  • Example:
class Car extends Vehicle {
  constructor() {
    super(); // refers back to parent Vehicle
  }
  start() {
    return "In Car Start" + super.start();
  }
}

Creating and Importing a Module

  • Create & Export
    • export class Car { ... }
  • Import
    • import { Car } from './models/car.js'

Window Object

  • Global object
  • Properties
    • document
    • location
    • console
    • innerHeight
    • innerWidth
    • pageXOffset
    • pageYOffset
  • Methods
    • alert()
    • back()
    • confirm()
  • Events
    • ( not common )
  • gGlobal object, must refer when dealing with modules

Timers

  • fire asynchronously

    • setTimeout(); // once
    • >setInterval(); // repeatedly
    let timeoutId = setTimeout(function () {
      console.log("1 second paused");
    }, 1000);
    // cancel clearTimeout(timeoutId); // or clearTimeout(id);
    

Location object

  • Properties
    • href (URL)
    • hostname
    • port
    • pathname
    • search
  • Methods
    • assign()
    • reload() ex: location.href or document.location.href

Document Object

  • Properties
    • body
    • forms
    • links
  • Methods
    • createElement()
    • createEvent()
    • getElementById()
    • getElementsByClassName()
  • Events
    • onload
    • onclick
    • onKeypress

Selecting DOM Elements

  • Common:
    • document.getElementById('elementId');
    • document.getElementByClassName('className');
    • document.getElementByTagName('tagName');

Modifying DOM Elements

Example:

let el = document.getElementById("elementId");
el.textContent = "new text here";
el.setAttribute("name", "nameValue");
el.classList.add("myClassName");
el.style.color = "blue";

Promises and Error Handling

Errors in Javascript

  • let car = newCar; // reference error, execution stops
  • Error Handling with try and catch
try {
  let car = newCar;
} catch (error) {
  console.log("error: ", error);
}
// continue execution
  • With finally (always executes)

    • finally { console.log('this always executes'); }
      
  • Developer defined errors

    • try {
          throw new Error('any custom error');
      }
      
  • Creating a Promise

    • Temporary holder for a value you will retrieve after asynchronous call
    let promise = new Promise(function (resolve, reject) {
      setTimeout(resolve, 100, "someValue");
    });
    
  • Setting a Promise

    promise.then(
        value => console.log('fulfilled: ' + value);
        error => console.log('rejected: ' + error);
    );
    

Chrome Dev Tools and Security

  • Network >> bundle.js file
  • Sources >> Watch, etc
  • Don't store sensitive info on browser

Security and the eval() function

  • JS Global eval() function will execute whatever is passed
  • Avoid eval() altogether? Script tags?

Preventing Man-in-the-Middle Attacks

  • Code put into HTML between server and intended client
  • Use SSL, use HTTP header
  • Cookie attributes: Secure and HttpOnly