Code Monkey home page Code Monkey logo

javascript-revision's Introduction

Javascript Revision

Index

Sr. No Topic Name
1. Javascript
2. Adding JS to the HTML
3. Javascript datatypes
4. Variables, Constants, NAN and Comments
5. Short hand Notation, Ternary operator and Template string
6. Loose vs Strict Comparison
7. Type Conversion
8. Conditional Statements , Switch, Loops in JS
9. Break and Continue
10. Functions and Methods
11. Arrow Function =>
12. Callback Methods
13. Date and Time object in JS
14. Object literals, Array, Set, String and Map in JS
15. DOM (Document Object Manipulation)
16. Regular Expression
17. More ES6 JS Features (like spread, rest etc)
18. Throwing and Catching Error
19. Objects and Classes in JS
20. Local Storage
21. Async JS
22. Callback functions and Fetch API
23. Promises and Async and Await

1. JavaScript

JavaScript often abbreviated as JS, is a programming language that confirms to the ECMAScript specification.JavaScript is :-

  • High-level
  • Just-in-time compiled
  • Multi-paradigm
  • Dynamic typing

It has curly-bracket syntax, prototype-based object-orientation, and first-class functions.

2. Adding JS to the HTML file

Internal

To write JS code in same HTML file.

<script>
    code blocks..
</script>

External

When JS code is written in different file.

<script src = 'JS file location with name eg. /a.js'>
</script>

3. JS Datatypes

  • Numbers : To describe any numbers.
  • String : To describe any sequence of characters.
  • Boolean : To describe True or False.
  • Null : Explicity set a variable with no value.
  • Undefined: For Variables that have not yet been defined.
  • Object : To describe real world objects.
  • Symbol : To uniquely identify objects.
let age = 21;                   // Number
let lastName = "Krishna";       // String
let fullName = {firstName:"Narayan", lastName:"Krishna"};           // Object
let checkFlag = true           // Boolean
let fav                        // Undefined
let symbolOne = Symbol()       // Symbol

git checkout JS_Datatypes //includes more examples in index.html

4. Variables, Constants, NAN and Comments

Variables and Constants

var (block the use of block scope), let and const were used for storing variables.

According to ECMA script :-

  • let : for using variables
  • const : for using constant value

Comments

Comments are used for describing our code.

/* Multi line 
   Comment */

// Single Line Comment

NaN

In JS NaN stands for Not a Number.

5. Short hand Notation, Ternary operator and Template string

  • Short hand notation is used for assigning values.
  • Template string is used for formatting string.
    Syntax :
`Sequence of characters ${variable_name}`
  • Ternary operator is used to shortend conditional statement.
    Syntax :
Conditional statement ? code blocks if true : code blocks if false or else code blocks   

Some Examples :-

// Short hand notation

/* +=, *=, /=, %= 
   eg. a+=1 is a = a+1
*/

let a = 5, b = 5
a+=1
console.log(a)
b = b+1
console.log(b)

// Template string
   let name = 'Narayan'
   let greet = `My name is ${name} and hello.`
   console.log(greet)

// Ternary Operator
   let pass = true
   pass ? 'gate open' : 'gate closed'

6. Loose vs Strict Comparison

Loose comparison : Doesn't type check and denoted by ==

Strict Comparision: Does type check and denoted by ===

let age = 25

console.log(age=='25') //loose comparision

//Strict comparision
console.log(age===25) 
console.log(age==='25')

7. Type Conversion

It is used to convert one datatype to another if possible.
Examples :-

let score = '100'
let check = True
console.log(score)

//Type conversion to number
score = Number(score)
console.log(score)

//Type conversion to boolean
check = Boolean(check)
console.log(check)

//Type conversion to string
score = String(score)
console.log(score)

8. Conditional Statements , Switch, Loops in JS

Conditional Statements

Syntax :-

if (condition){
    code block..
}

else if (condition){
    code block..
}

else {
    code block..
}

Switch in JS

Syntax :-

switch(variable_name){
    case 1: code block..
            break
    case 2: code block..
            break
    .
    .
    .
    case n: code block..
            break

    default: code block that always executes
            break
}

Loops in JS

To iterate elements. Syntax :-

// while loop : Iterate when condition is true

while(condition){
    code block..
}

// do while loop : Iterate at least one time wheither condition is true or not.

do{
    code block..
}while(condition)

// for loop

for (let i = start_value; i<stop_value; i++ /* jump over value */ ){
    code block..
}

// for of and for each loop

// for of loop

for (let element of arr){
    console.log(element)
}

//forEach loop

array_name.forEach(function_name /* Function that executes for every element in array_name */)

9. Break and Continue

Break : Break out of the loop.

Continue : Goes to the next iteration and also don't execute the code for ongoing iteration.

Keywords used - break , continue

10. Functions and Methods

Functions

Functions are used to use same block of code multiple times without writing whole code again and again.

Methods are the functions used inside the class. Syntax :-

// Function Declaration

function function_name (){
    // block of codes....
}

// Function Expression

const function_name = function(){
    // block of codes
}

// Function call

function_name()

11. Arrow Function =>

Arrow function is used to shortend function declaration.

Syntax :-

const function_name = () => {
    // code block
    return value
}

12. Callback Methods

When function is pass as an argument to an another funtion then the function that is an argument is called callback function.

Syntax :-

function callback_function_name(){
    // block of code...
}

function function_name(callback_function_name){
    callback_function_name(value)
}

13. Date and Time object in JS

To use date and time in javascript.

Syntax :-

const date_variable_name = new Date() // Date constructor

14. Object literals, Array, Set, String and Maps in JS

Object literals

Have Multiple Props (i.e multiple variables or functions).

Syntax :-

let object_literal_name = {
    prop_1 : '...';
    prop_2 : '...';
    .
    .
    .
}

// To access props from object literal
object_literal_name.prop_1

Array

Ordered collection of elements.

Syntax :-

let array_name = []

let array_name = new Array( /* no. of elements */ )

// Some array methods

array_name.length
array_name.pop()
array_name.push()
array_name.sort()
array_name.reverse()
array_name.map(function_name)

String

Sequence of characters.

Syntax :-

let string_name = ''

// Some methods

string_name.toUpperCase()
string_name.trim()
string_name.startsWith()
string_name.replace(s1, s2)
string_name.slice()
string_name.substr()
string_name.indexOf()

Set

Unordered collection of elements, O(1) time complexity.

Syntax :-

let set_name = new Set()

// Some methods

set_name.has()
set_name.add()
set_name.size
set_name.delete()
set_name.values()

Map

Mix of Array and Set, Have keys and values also override similar keys.

Syntax :-

let map_name = new Map()

// Some methods

map_name.get('key_name')
map_name.set('key_name', value)
map_name.delete('key_name')
map_name.size
map_name.has('key_name')
map_name.clear()
map_name.entries()

15. Document Object Manipulation

  • Main Part of webpage manipulation through JS.
  • Interaction with HTML through JS.
  • "document" object

Document Object Model

DOM

Grabbing element through code

document.querySelector() // . represents class, # represents id 
document.querySelectorAll()
document.getElementById() // Single Element grab
document.getElementByClassName() // Multiple items of same class grab
document.getElementByTagName()

element_name.innerText = ` `
element_name.innerHTML = ` `
element_name.setAttribute('style','color : green')
element_name.getAttribute('attribute_name')

HTML Collection and Node list

HTML Collection Node List
Collection of HTML elements Collection of document nodes
Can be access through name, id, index Can be accesed by their index number

Event handling

To add functionality to events that can be mouse or keyboard event.

.addEventListener('event', function())

Window object is global object and is defaultly used.

16. Regular Expression

It is used for string pattern matching.

Example :-

let test_ex = 'Krishna'
const pattern = /^[a-z]{6,}$/ // /-> start and end; ^-> start; [a-z]-> a to z;{ }->length; $->end;

console.log(pattern.test(test_ex))

17. More ES6 JS Features (like spread, rest )

  • rest is used for packing or bundling of multiple variables.
  • spread is used for unpacking ir unbundling of multiple variables.

Syntax :-

...variable_name // rest : converts from group of numbers to array and spread : converts from array to group of numbers

18. Throwing and Catching Error

Error handling.

Syntax :-

try {
    // block of code
}
throw new Error() 

catch(err){
    // Error handling
}

finally{
    // block of code executes regardless of try/catch. 
}

19. Objects and Classes in JS

Implementation of real world objects and their structure/blueprint. It is a modern JS feature and is working along with prototypes to provide OOPS concept.

Syntax :-

// class

class ClassName{
    constructor(attributes){
        // Initialization of class
        this.attributes = attributes
    }

}

// object

let object_name = new ClassName()
// the 'new' keyword creates a new empty object {} and binds the value of 'this' to the new empty object.

// Subclasses and Inheritance

class SubClassName extends ParentClassName{
    constructor(attributes,inherited_attributes){
        super(inherited_attributes)
        this.attributes = attributes
    }
}

20. Local Storage

It provide local storage to store and retrive data from the browser.

// Store data in local storage

localStorage.setItem('key_of_the_object','value_of_the_object')

// Get data from local storage

let variable_name = localStorage.getItem('key_of_the_object')

// Updating the data

localStorage.setItem('key_name','value')

// or

localStorage.key_name = 'value'

// Deleting data

localStorage.removeItem('key_name')

localStorage.clear() // to delete all file

21. Async JS

Asynchronous model allows multiple things to happen at the same time while in synchronous model things happens one at a time.

AJAX

  • Asynchronous Javascript And XML
  • No page reload/refresh
  • XML is replaced by JSOn

How AJAX Works ?

AJAX uses XMLHttpRequest object to accomplish no page reload. Data can be transferred in any format http is not neccesary.

Working of AJAX :-

const xhr = new XMLHttpRequest()     // Create an object
xhr.open('GET/POST','file_name',true)// Open the object
xhr.onprogress = function_name // What to do when in progress
xhr.onload = function_name // What to do when response is ready
xhr.send() // send the request

22. Callback functions and Fetch API

Callback Function

Function passes or executes after completion of first function.

Callback Hell, phenomenon that occurs due to nesting of callbacks. To avoid it we use promises in JS.

Fetch API

Three steps :-

  • fetch data
  • take response promise
  • access data

Syntax :-

fetch(location_of_resource) // return promise
.then((response)=>{
    console.log('resolved_response')
    return response.json()
})
.then(data=>{
    console.log(data)
})
.catch(error=>{
    console.log(error)
})

23. Promises and Async and await

Promises returns :-

  • pending
  • resolved
  • rejected

Async and Await

Gives more readabilty to async JS code.

Syntax :-

async function function_name(){
    const function_name_1 = await fetch('')
}

javascript-revision's People

Contributors

xxalchemist avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.