Introduction

To introduce JavaScript, I want to tell you that you don't need to read a lot about it. You just need to glance at some simplified examples and practice them with your hands and keyboard.

For more information scroll below.

Arrays

Array is a linear data structure, where you are able to store your preffered data. I'm gonna show you the most popular array's methods these you will use in your JS journey.

slice()

It returns selected elements in an array, especially as a new array and doesn't change the original array.

  
              const items = ["key", "toy", "notebook", "car"];

              items.slice(-3, -1) // output -> ["toy", "notebook"]
              

Array()

This is a constructor that is used to create Array object, you can call it with or without a new keyword.

  • new Array(1,2,3)
  • Array(10)

If we take the last one length should be 10.

fill()

This method fills specified elements in an array with value and overwrites the original array.

                  
              const range = (start, end) => Array(end - start + 1)
              .fill(start).map((el, ind)=> el+index);
              

reduce() & reduceRight()

It returns a single value, especially the function's accumulated result. Also it doesn't change the origianl array and doesn't execute the func for empyy array elements.

Let's examine unfamiliar things in this syntax: array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

  • initialValue -- a value to be passed to the function as the inital value.
    Such as: 0, "", [], {}
  • total -- the initialValue or the previusly returned value of the function.

                const reducedVal = [2,3,4,5,6].reduce((total, currVal)=> total+currVal, 0);

                // reducedVal should be 20 
              

reduceRight() is same as reduce() but works from right to left.

some()

It returns boolean value true / false if a callback function's conditions meet, and a specified array contains it. Also it doesn't change the origianl array.


                ["a", "b", "c", "A", "d"].some(letter => letter == letter.toUpperCase());

                // returns true cause of "A"
              

Strings

In a simple term it's a sequence of characters, typically used to represent text.

parseFloat()

This Number.parseFloat() method parses a value as a string and returns the first number.

  • If the first character cann't be converted, NaN is returned
  • Only the first number found is returned
 
             const myStr = "20 40 string";

             Number.parseFloat(myStr) // output is 20
             

charAt()

This returns the character at a specified index (position) in a string.

             
              const myStr = "This is a string";

              myStr.charAt(2) // output is "i"
             

split()

It splits a string into an array of substrings, doesn't change the original string and returns new array.

  • if (" ") is used as separator the string is split between words.
  • The syntax is the following: myStr.split(separator, limit)
    • limit is an integer that limits the number of splits. Items after the limit are excluded.

              let fruits = "apple,banana,grape,orange";

              let fruitArray = fruits.split(","); 

              // output is ["apple", "banana", "grape", "orange"]
             

indexOf()

It returns the position of the first occurrance of a value in string, otherwise returns -1, if the value isn't found. Keep in mind that this method is case sensitive. Syntax is the following: text.indexOf("e",5) default is 0 but you can define the postion to start from.


                "Say Hello to JS".indexOf("JS",2);

                // It'll start from this specified position and returns 13
              

includes()

It returns true if a string contains a specified string. Otherwise it returns false.


                text.includes("world", 12);
                
                // Returns true if this text contains "world"
              

DOM

Document Object Model (DOM) is an interface that allows programs and scripts to dynamically access and update the content. It helps us to make our webpage interactive.

getElementById()

With that we are able to access an HTML element with a given ID name.


                  document.getElementById("#info");
                

querySelector() & querySelectorAll()

It returns the first element that matches a CSS selector to return all matches, use querySelectorAll() instead. Especially, querySelectorAll method returns a NodeList of all the elements that match the selector. A NodeList is an array-like object, so you can access the elements using bracket notation.


                  document.querySelelctorAll(".input-container");
                

getElementsByClassName()

To get all the elements with this class use that. It returns an HTMLCollection, which is an array like object of all the elements that have a matching class name.


                  document.getElementByClassName("values-dropdown");
                

createElement()

This method creates an element node.


                    const btn = document.createElement("button");
                  

appendChild()

Appends a node element as the last child of an element.


                  const btn = document.createElement("copy");

                  btn.innerHTML = "Copy";

                  document.body.appendChild(btn);
                

Exercises

To practice in JS let's try these exercises in your own.

Deep Clone and Object "Without JSON"

Write a function deepClone(obj) that creates a deep copy of a given object, handling nested structures, arrays, and objects without using JSON.stringify()

Rrequirements:
  • Should work for nested objects and arrays
  • Should preserve functions and special objects like Date
Example

            const obj = { 
                name: "John", 
                details: { age: 30, hobbies: ["coding", "reading"] }, 
                date: new Date()
            };

            const clonedObj = deepClone(obj);
            console.log(clonedObj.details === obj.details); // false (should not be the same reference)            
            

Implement a Custom Promise.all()

Write a function promiseAll(promises) that mimics Promise.all(), resolving all promises in an array and returning their results. If one promise rejects, it should return the rejected value immediately.

Example

          const p1 = Promise.resolve(10);
          const p2 = Promise.resolve(20);
          const p3 = Promise.reject("Error occurred");
          
          promiseAll([p1, p2]).then(console.log); // [10, 20]
          promiseAll([p1, p3]).catch(console.error); // "Error occurred"
          

LRU Cache Implementation

Implement an LRU (Least Recently Used) Cache using a class. The cache should store key-value pairs and remove the least recently used entry when it exceeds the capacity.

Example

          const cache = new LRUCache(3);
          cache.put(1, "A");
          cache.put(2, "B");
          cache.put(3, "C");
          cache.get(1); // Moves 1 to most recently used
          cache.put(4, "D"); // Removes 2 (Least Recently Used)
          console.log(cache.get(2)); // null (2 was removed)
          

Infinite Currying Function

Create a function add() that supports infinite currying, meaning it can be called repeatedly and returns a function, until it's called without arguments.

Example

          console.log(add(2)(3)(5)()); // 10
          console.log(add(1)(2)(3)(4)(5)()); // 15
          

Implement a Debounce Function

Create a debounce(func, delay) function that ensures a given function executes only after a specified delay from the last call.

Example

          const debouncedFunc = debounce(() => console.log("Function Executed!"), 2000);
          debouncedFunc();
          debouncedFunc();
          debouncedFunc(); // Only this call will execute after 2s