JavaScript

Home Footer

Operators- arithenatic, logical comparison

Logical Operators and or not

FUNCTIONS - declare and invoke(call)

way of creating a function 1 - function Declaration

  1. funcion keyword
  2. fun name
  3. parameter
  4. body
  5. EXAMPLE - function fnName(parameter){body}

way of creating a function 2 - function EXpression

  1. keyword - let/var
  2. variable name
  3. function keyword- function
  4. parameter
  5. body
  6. EXAMPLE - let fnName = function(parameter){body}

Function - Parameters and Arguments

Return Keyword

Let's say that I want to display the result of my function into the main webpage! We haven't talked about Dom manipulation, so spare me with that. I'm going to give you some some scenarios why this function is not performing the way we want it. That's the scenario, number one. And also, what about say that? Oh, no, I don't want this play my result into the page, but instead I want to display it inside an elect. How can we do that? In that way, we need what is called the return keyword, because a function with no return and only consol.log is not giving out anything. Its just printing the thing in console tab.
So the return keyword is used to exit a function and return a value to the caller. Here comes. So one point of return is it is used to exit a function. And then if a value is present in the return, it is going to give out to the variable we assign a function to The return keyword is essential for creating functions that return value. So without return keyword, function will only be able to perform actions but not return values to the caller. This would limit the usefulness of a functions and make them much less powerful. so when you return sommething from teh function, now you can use the returned value anywhere in the javascript to display on screen,lets say alert(fnName(argument)) and you can displlay the returned value in alert section of website. Thsts amazing

STRINGS

Ways of creating a string

  1. using string literal "" or ''
  2. using the constructor function i.e.
    const name = new String("something");
    this will return a way different form of string proved in the javascript code snippet below:
  3. const myName = "John";
    const firstName = new String("John");
    const result = myName === firstName;
    console.log(result);
    This code will give false!!!Yeass, though John and John are similar, due to they are different forms of string literals! . but if you did
    const result = myName == firstName;
    instead the answer will be TRUE! because now the datatypes of "John" will not be matched instead just the string.

String Concatenation

  1. using + operator : str1+str2
  2. using concat method : const result = str1.concat(str2);

JS Template Literals

  1. String literals ""
  2. back tick literals- this is multiline string that is all the enters will be considered ``
  3. template string
  4. INTERPOLATION - to use a variable inside the string

String length - it takes white spaces into consideration!

const str = "Hell ";
str.length;
this will give 12

Some String functions

  1. trim - to remove white spacings
  2. toUpperCase
  3. toLowerCase
  4. indexOf
  5. split(ch,3) - to split every charachter in the string w a specific characther ch example:
    str = "hobnbkbsf"; str.split("b");
    this will give ['ho', 'n', 'k', 'sf'] i.e. all b are splitted
  6. str.join("b");
  7. str.reverse(); - to reverse an array.
    if you want ot reverse a string, 1) split it into array 2) reverse it 3) join it into a string!
  8. str.repeat(n); to repeat a str n number of times
  9. str.startsWith(ch); - to check if str starts with ch
  10. str.endsWith();
  11. str.includes(ch); - to check if str contains ch
  12. str.slice(n,m); takes n to m charachetes from str

String Comparison

Arrays

Methods of cerating Array

  • Array can take any type of data type value
  • Array Methods

    1. arr.push(); - add to the end
    2. arr.pop(); - remove from the end
    3. arr.unshift(); - add to the beginning
    4. arr.shift(); remove from the beginning
    5. arr.indexOf();
    6. arr.lastindexOf();
    7. arr.include()
    8. arr.reverse()
    9. Reduce Method -
      1. A function that accepts upto 4 arguments, the reduce method calls the callbackfn function one time for each element in the array
      2. Calls the specified callback function for all the elements in the array
      3. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function
      4. Return a single value
      5. Doesn't mutates the original array
      6. Syntax-
        arr.reduce(function(acc,currVal,currIdx,arr){},initialVal);
      7. const callback = (accumulator, currentValue, index) => {
          // return something here
        }
        const result = array.reduce(callback, initialValue)
      8. The previous return value is used as the next accumulator
      9. initialValue is the value you want to start with.
        accumulator is the value returned from the previous iteration.
        It will be initialValue for the first iteration.
        currentValue is array item in the current iteration.
    10. Find Method
      1. (method) Array(number).find(predicate: (value: number, index: number, obj: number[]) => unknown, thisArg?: any): number | undefined (+1 overload)
      2. Returns the value of the first element in the array where predicate is true, and undefined otherwise.
      3. @param predicate find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
      4. @param thisArg If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
      5. array.find(function(currentValue, index, arr),thisValue)
      6. currentValue Required. The value of the current element.
      7. thisValue Optional. Default undefined. A value passed to the function as its this valu
    11. Filter Method

      same as find, but this returns an array of answers not just first outcome

    12. Example
      const arri = [2, 4, 5, 2, 4];
      const reduce = arri.reduce(function (acc, currVal) {
      return acc + currVal + currVal;
      }, 0);
      const find = arri.find(function(elements){
      return elements>4;
      })
      const filter = arri.filter(function(element){
      return element> 2;
      })

      Answers
      reduce = 34, find = 5, filter = [4,5,4]

    Objects

    Accessing Object Properties

    const person = { name: 'johny', salary: 45452, hobby: ['dance','cooking']};

    1. Using dot notation i.e. person.name
    2. Using Bracket notation i.e. person["name"]

    Updating Object property

    person.name = "whateve"

    person['name'] = 'wahhah' -> used widely since it is more dynamic
    for example
    let printObj = function(obj){ for(let key in obj){ console.log(`${key}: ${obj[key]}`); } }
    is better than
    let printObj = function(obj){ for(let key in obj){ console.log(`${key}: ${obj.name}`); console.log(`${key}: ${obj.age}`); } }

    Deleting Object property

    use
    delete person.name
    that is it, done!

    this keyword

    in javasctipt 'this' keyword refers to immediate or parent object

    if you do console.log(this); randomly it will show global object that is Window

    Iterating Over Objects

    1. for in loop - for(let key in objectName){}
      for(let key in person){ console.log(key); }
    2. object.keys let ans = Object.keys(objectName);
      let keys_array = Object.keys(person); console.log(keys_array);
    3. forEach -
      keys_array.forEach(function(element){ console.log(element) })
    4. object.values - Object.values(person)
    5. object.entries - Object.entries(person)
      Example
      let objentries = Object.entries(person); objentries.forEach(function([key,value]){ console.log(`${key}: ${value}`); })

    Math Objects

    1. abs
    2. round
    3. ceil - upper val
    4. floor - removes decimal no.s
    5. sqrt
    6. pow
    7. min
    8. max
    9. random
    10. Formula for Random Number between two values:
      Math.random() * (max-min + 1) + min

    Data Mutation

    Array Methods

    1. arr.forEach(function(item,index,array){})

    Array of Objects

    An array made up of objects, hence the methods of this are different

    functions:

    1. forEach
    2. push(object)
    3. map()
    4. filter()
    5. reduce()

    Javascript Versions

    Array Function

    ()=>{}

    more concise way of writing a traditional function expression, but it cannot be used in all situations.

      Limitations

    1. Do not have this keyword
    2. Do not have Arguments
    3. Cannot use as a constructor

    Spread Operators

    The spread operator (...) is a convenient way to copy all or part of an existing array or object into another array or object

    Spread suntac expands an array into its elements, while rest syntac collects multiple elements and condenses them into a single element

    Javascript History

    console

    It is a command line interface that runs js on your js engine

    REPL - READ EVALUATE PRINT LOOP is the loop that console runs

    if you do console.log('helo') on console, you'll get helo undefined

    the helo is result of evaluating our program, the undefined is returned function of the funcction, and the console log is returning undefined unless specified

    Characteristics of Javascript

    1. Its is interpreted language not compiled
    2. It is a single threaded language - executes code line by line (this doesnt decrease performance, will prove ahead how)
    3. It is dynamically typed language - i.e. type of a variable can change during the program execution (if you dont want this you can use a language called Typescript)
    4. Object Oriented Language - it is a programming paradigm which uses objects as the primary way of representing data which uses Prototypal inheritance (like push pop methods etc)
    5. It is called a garbage collector - process that frees up memory by removing objects that are no longer used in the program and it is called garbage collection
    6. It is a client side language - using js in browser i.e chrome edge mozilla safari
    7. It is a server side language - using js on server ie. nodejs
    8. It is a non blocking - it is a code that runs concurrently in the background with the help of event loop for example - setTimeout(()=>{}, ); console.log("before"); setTimeout(function (){ console.log(500); }, 2000); console.log("after"); This wont print before 500 after, instead this will print before after 500 . so this way we can run concurrent codes using event loop.
    9. It is a high level language - resource management are done automatically
    10. Multi Paradigm Language - i.e. we have difference style of approach how we can structure our code This is a coding approach to structure code-
      • Functional Programming
      • Object Oriented Prog
      • Procedural Programming

    Javascript Engine

    is a computer program that runs js code, since computer understands only machine language i.e. 0 and 1 . All browsers have a built in javascript engine

    code execution process/p>

    Javascript Runtime (Browser)

    in a laymans language means a box containing all the things we need to run our code.

    The components-

    Javascript Callstack - A call stack is a data structure that is used to track the execution of function calls. It is used to keep track of the order in which function calls are made.

    Advanced Functions

    Types of Scope

    Global scope

    Block Scope

    Function Scope

    Lexical Scope

    First Class citizens -
    1. function returning function function fcc() { return function (a,b) { return a+b; }; } To call - fcc()(3,4);
    2. assigning function to a variable - function smt(){ console.log("helo"); } const jk = smt; jk(); smt()
    3. store function inside an array

    High order functions HOF - functions accepting functions as arguments also called as callback functions
    1. most common -
    2. reduce
    3. find
    4. filter
    5. map

    Function returning a function

    immediately Invoked Function Expression IIFE - - A FUNCTION that is gona be executed as soon as your page loads