Categories
Uncategorized

Understanding the Execution of Code in JavaScript

What happens when JavaScript executes our code ? This is the question that we will address in this lesson.

Let us first go over the below code.

As soo as we start running our code, a global execution context gets created. So there is a thread of execution that is parsing and executing the code line by line. In global variable environment, live memory of variables with data is allocated. The above code clearly demonstrates the single threaded nature of JavaScript but it only shows the synchronous execution.

LOCAL EXECUTION CONTEXT

Running/calling or invoking a function is what creates a local execution context. So when you execute a function, a new execution context gets created. So this is what comprises an execution context :

  1. The thread of execution (we go through the code in the function line by line)
  2. A local memory (variable environment) where anything defined in the function is stored.

When we start running a function, a local execution context pertaining to that automatically gets created. Once the function is done with its execution, the same gets simply popped off from the call stack.

But what exactly is a call stack ?

Call stack is something that helps you to follow your code. So it basically tells us where the thread of execution is currently in our JavaScript code. This is a great format for tracking where our JavaScript thread currently is running the code.

Closures

When our function gets called, we create a live store of data (local memory/variable environment) for that function’s execution context. Now when the function is done with its execution, it’s local memory gets deleted except the returned value. But what if our functions could hold on to live data/state between executions ? This would let our function definitions to have an associated cache/persistent memory.

This starts with returning us a function from another function. JavaScript performs automatic garbage collection if the memory is no longer required whereas in other languages you may have to explicitly perform the deallocation of memory.

LEXICAL SCOPE

For closures, you can say it is closed over the variable environment. When a function is defined, it gets a [[scope]] property that references the local memory/variable environment to which it has been defined.

Let us see an example now,

Whenever we call the above incrementCounter function, it will always look first in its immediate local memory (variable environment) and then in the [[scope]] hidden property next before it looks any further up in the scope chain. It will always look first in its lexical scope. If it does not find the variable there, it will go up the scope chain till it finds a variable. Our lexical scope (the available live data when our function was defined) is what determines our available variables and prioritization at function execution, not where our function is called.

Categories
reactjs

Demystifying Virtual DOM in React.js

DOM manipulation as we know is the most common operation that is used for performing dynamic interactions in a website. We grab references to certain DOM elements, then we might need to register listeners on the elements to listen for certain events and things like that. The problem here is that this DOM manipulation is a slow process and too much of DOM manipulation operations can bloat your application and this is because the JavaScript and its frameworks update the DOM quite frequently than they need to.

Let us understand this with the help of an example :

Consider a list of elements and let us say we want to delete the second item of that list. Now as we know most of the JavaScript frameworks that we have out there will rebuild the entire list which is of course more work than what needs to be done. So what happens here is that the entire list was made to rebuilt for just one deletion. So there is a huge overhead if we take into account the amount of DOM manipulation that goes into this. So to address this problem, the concept of Virtual DOM came into picture.

Virtual DOM

So let’s discuss about the virtual DOM that we discussed in the previous paragraph.

The virtual DOM is simply a virtual representation of the entire DOM.

So what happens here is that whenever any piece of our application state undergoes a change, that change is mapped to the virtual DOM instead of directly applying it to the real DOM. Now you may wonder, how come then it is faster than the real DOM. No worries, we are here to dive into the reasons as to why Virtual DOM is faster and efficient than the real DOM.

So for every DOM object we get a corresponding virtual DOM object. Both these objects have the same properties. Now here comes the main crux which is that manipulating the real DOM is a lot slower than the virtual DOM. So manipulating the virtual DOM is just like having a copy of the real DOM and performing changes on it before the same gets committed to the real DOM.

How it all works ?

So as we develop our UI, new elements get added to the DOM which in turn composes the entire DOM tree. Each element that we create is a node of this tree. Now if a piece of our application state experiences a change, then a new virtual DOM tree needs to be tree. This new tree that gets created is then made to undergo a comparison or in React terms we call this as “diffing” with the previous virtual DOM.

Next, once we are done with this step, computations regarding how these changes will be mapped to the real DOM are carried by the virtual DOM. The goal is to ensure that the updates can be made as fast as possible without interacting much with the real DOM and with as less operations as possible. The benefit of this in the end is to improvise on performance standpoint and thus reducing the cost of updating the real DOM.

Patching of changes from virtual DOM to real DOM

Now once the virtual DOM gets updated, React then compares the virtual DOM with the previous snapshot of the virtual DOM so basically the version of virtual DOM that existed before the update came into picture. With this comparison, React is able to figure out which parts of the virtual DOM underwent changes. This process is called as diffing which we also discussed above.

So to sum it up, once React has the knowledge of which virtual DOM objects have undergone a change, it simply updates those and only those objects on the real DOM. So for the example of our list, React simply updates the one item that was deleted without touching the other items of the list. This is what makes the entire difference in performance. So therefore this is how React can make sure that it updates only the relevant parts of the DOM.

Categories
angular

Learn Angular in One Video

Hi Guys,

A couple of months back I released a video on “Angular Tutorial For Beginners | FULL COURSE”. Here is the link for that video just in case if you want to check that out :

Also if you want the complete source code for the video. Here is the link for the same:

unruffled-feynman-4vgqo – CodeSandbox

I hope you enjoyed the video. Do like, share and subscribe to my channel for more such awesome videos. Keep coding !

Categories
ruby

Learn Ruby in one video (with source code)

Hi Guys,

A couple of months back I released a vide on “Learn Ruby Programming in 3 hours | FULL COURSE”. Here is the link for that video just in case if you want to check that out :

Also if you want the complete source code for the video. Here is the full code :

puts "Hello to Ruby Programming Language"

#variables, constants and literals  

first_name = 'Alex'
last_name = 'James'

puts first_name 
puts last_name 

# constants 
PIE = 3.14 
radius = 5 
area = PIE * radius * radius
puts area 

puts 123 
puts 1_234
puts -500 
puts 0366 
puts 0xff 
puts 0b1011 

puts 123.45 

# strings 

full_name = first_name + " " + last_name 

puts full_name 

# string interpolation 

puts "The full name is #{full_name}"

age = 12 
puts "The age of the person is #{age}"

# <<
sentence = "A quick brown fox " 
sentence << "jumps over the ";
sentence << "lazy dog"

puts sentence 

# Manipulation of strings 

#gsub (global substitution)

puts sentence.gsub("dog","cat") 
puts sentence 


# split method 

words = sentence.split(' ')
puts words 

code = "abc_123"
puts code.split("_")

# substrings 
greet = "hello world".freeze
puts greet[0..3]

puts greet[-1]

puts greet.upcase()
puts greet.downcase()
puts greet.capitalize() 
puts greet.reverse() 
puts greet.include? 'w'
puts greet.start_with? 'h'
puts greet.end_with? 'd'

# Immutability and Frozen strings 

# greet[0] = ""
# puts greet 
puts greet.frozen?

# object_id 
string_one = "tommy".freeze 
string_two = "tommy".freeze 

puts string_one.object_id == string_two.object_id 

# Arrays in Ruby 

superheroes = ['spider-man','super-man','goku']

puts superheroes[0]
puts superheroes[1]
puts superheroes[2]

# printing first element of the array 
puts superheroes.first 
# printing last element of the array 
puts superheroes.last 

# printing first two elements of the array 
puts superheroes.first(2)
# printing last two elements of the array 
puts superheroes.last(2)

superheroes.push "batman"
puts superheroes 


superheroes << "hulk"
puts superheroes 

last_hero = superheroes.pop 

puts last_hero 
puts superheroes 

superheroes.delete_at(1)

puts superheroes 

# adds an element to the front of the array 
superheroes.unshift "alex"

puts superheroes 

# removing an element from the front of the array 
superheroes.shift 

puts superheroes 

# insert method 

superheroes.insert(2,'power rangers')

puts superheroes 


puts "The size of the array is #{superheroes.size}"
puts "The length of the array is #{superheroes.length}"


numbers =  [1,2,3,4,5]

count = numbers.count { |number| number.even? }

puts "The count of the even numbers in the array is #{count}"

#initialize an array, we can use the square brace 
# notation

# read an element (access) index notation, first, last 

# append an element - push, <<, unshift 
# remove an element - pop, delete_at, shift 

# iterating over an array 

# iterate over the superheroes array 

superheroes.each { |superhero| puts superhero }

# each_with_index 

superheroes.each_with_index { |superhero, index|
puts "superheroes[#{index}] : #{superhero}"}

# each_char and the chars 
some_string = "Alex is a software developer"
some_string.each_char { 
  |character| puts character
}

puts some_string.chars 

# map 

puts superheroes 

superheroes = superheroes.map { |superhero| superhero.upcase() }

puts superheroes 

# select 

# selecting odd numbers 
puts numbers.select { |number| number % 2 == 1}

some_numbers = [1,4,3,2,3.4,5]

some_numbers = some_numbers.sort 

# sorting the numbers in ascending order 
puts some_numbers 

duplicates = [1,3,3,4,5,4,1]

uniques = duplicates.uniq 

puts uniques 

# sample method 

puts numbers.sample 

# take, slice 

first_three = numbers.take(3)
puts first_three 

first_three = numbers[0,3]
puts first_three 

# Splat Operator in Ruby 

*a,b = 1,2,3,4,5 

puts "#{a}, #{b}"

# concat method 
even_numbers = [2,4]
odd_numbers = [1,3]

first_four = even_numbers.concat(odd_numbers)

puts "#{first_four}"

# concat method mutates the original array as well 
# on which it gets applied
puts "#{even_numbers}, #{odd_numbers}"

# & operator  
puts "The common elements are #{even_numbers & odd_numbers}"

# | operator 
puts "The union is #{even_numbers | odd_numbers}"

puts "#{duplicates | some_numbers}"

# HASH TABLES 

# CREATING a hash table 

items = { }

items[:pen] = 2
items[:pencil] = 5
items[:laptop] = 6

puts "The quantity of pens are #{items[:pen]}"
puts "The quantity of the pencils are #{items[:pencil]}"
puts "The quantity of the laptops are #{items[:laptop]}"

# iterate over the hash tables 

# each 

puts "Current items : #{items}"

# print each key-value pair 

items.each do |item, quantity|
  puts "#{item}:#{quantity}"
end 

# each_key, each_value 


items.each_key do |item|
  puts "#{item}"
end 


items.each_value do |quantity|
  puts "#{quantity}"
end 

# keys, values 
puts "#{items.keys}"
puts "#{items.values}"

# key? 

puts "#{items.key?(:pencil)}"
puts "#{items.key?(:tab)}"

# Exercise: 
given_string = "thenerdydev" 

frequency_ht = { } # initialization 

# iterate over the given string 

given_string.each_char do |character|
  if frequency_ht.key?(character)
    frequency_ht[character] += 1
  else
    frequency_ht[character] = 1
  end 
end 

puts "#{frequency_ht}"

# Exercise:
frequency_ht.each do |k,v|
  if v == 1
    puts k 
  end 
end 

# fetch and merge methods 

hash_table = { } 

puts "#{hash_table[:something_random]}"

# fetch method 

puts "#{hash_table.fetch(:something_random, 'INVALID')}"


# merging two hash tables 

# merge 

user = { 
  name: 'alex',
  age: 21,
  profession: 'developer'
}

new_user = user.merge({age: 41, country: 'UK'})

puts "Original hash table : #{user}"
puts "New hash table : #{new_user}"

#dig method 

person = {
  details: { 
    name: 'alex',
    gender: 'male',
    profession: 'developer',
    age: 21
  }
}

puts person.fetch(:details).fetch(:name)

puts person.dig(:details, :name)

puts person.dig(:details, :anything)

# transform_values 

puts items 

items = items.transform_values { |v| v*2}

puts items 

# Sets 

require 'set' 

numbers = Set.new 

numbers << 1 
numbers << 2 
numbers << 3 
numbers << 2 

puts "#{numbers}"

puts numbers.include?(1)

# ranges 

puts "#{('a'..'z').to_a}"

# numbers ranging from 1 to 10 

puts "#{(1..10).to_a}"

# step method 

puts "#{(1..10).step(2).to_a}"
# iterate over a range of numbers from 1 to 10 

(1..10).each {|number| puts number }

# random number in range(1,10)

random_number = rand(1..10)
puts "The random number is #{random_number}"

# Data Serialization 

# csv and json 


# CSV (comma separated values )

require 'csv'

puts CSV.read('items.csv', headers: true)


# json 

require 'json'

json_object = '{
  "pen" : 300,
  "pencil": 400,
  "laptop": 600
}'
hash = JSON.parse(json_object)

puts hash 

puts hash.to_json 


# all classes in Ruby inherit from the Object class 
# Object < BasicObject 

puts json_object.class 
puts hash.class 


# methods 

def greet()
 puts "Good morning!"
end 

greet()

def add(number_one, number_two)
  return number_one + number_two 
end 

result = add(2,3)
puts "The addition of 2 and 3 gives #{result}"

# Class 

puts Array.class
puts String.class 
puts Hash.class 
puts Integer.class 

class Customer
  attr_reader :id, :name, :age, :type, :gender
  attr_accessor :type 
  @@customer_count = 0 

  def self.count
    @@customer_count
  end 

  def initialize(id, name, age, type, gender)
    @id = id 
    @name = name 
    @age = age 
    @type = type 
    @gender = gender 
    @@customer_count += 1 
  end 
  
  def display_customer_details()
    puts "Customer id: #@id"
    puts "Customer name: #@name"
    puts "Customer age: #@age"
    puts "Customer type: #@type"
    puts "Customer gender: #@gender"
  end 
end 

puts "Current count of customers : #{Customer.count}"
customer_one = Customer.new(1, 'alex', 21, 'high-spender', 'male')
customer_two = Customer.new(2, 'james',29,'low-spender','male')
puts "Current count of customers after creation : #{Customer.count}"

# call methods 
customer_one.display_customer_details()
customer_two.display_customer_details()

puts customer_one.id 
puts customer_one.name 
puts customer_one.age 
puts customer_one.gender 

# attr_writer, attr_accessor
customer_two.type = 'high-spender'
puts customer_two.display_customer_details()


# public access control, private access control 
# protected access control 

# private methods 

# protected methods 

class Cube
  def initialize(side)
    @side = side 
  end 

  def getArea()
    return 6 * @side * @side 
  end 

  def getVolume()
    return @side * @side * @side 
  end 

  private :getArea, :getVolume 

  def printArea()
    area = getArea()
    puts "The area of the cube is #{area}"
  end 

  def printVolume()
    volume = getVolume()
    puts "The volume of the cube is #{volume}"
  end 
end 

# instantiation 
cube_one = Cube.new(4)
cube_one.printArea()
cube_one.printVolume() 

# Inheritance in RUby 

class A
  def doSomething()
    puts "Doing something..."
  end
  def walkTheDog()
    puts "Walking with the dog..."
  end 
end 

class B < A
  def doThat()
    puts "Doing that..."
  end 
  def singSong()
    puts "Singing the song.."
  end 
end 

b = B.new 
puts b.doSomething()
puts b.walkTheDog() 
puts b.doThat() 


# Ruby blocks 
[1,2,3].each { |number| puts number} 

# multiline block 

[1,2,3].each do |number| 
  puts number
end 

# yield keyword in ruby 

def a()
  puts "inside a"
  yield 
  puts "coming out of a"
end 

a { puts "hello from outside of a" }

def perform_operation()
  yield 2*3
  puts "inside perform_operation"
  yield 5/6 
end 


perform_operation { |number| puts "#{number}" }

def print_2_times()
  yield 
  yield 
end 

print_2_times { puts "Hello World "}

# Lambda 

first = -> { puts "This is a lambda"}

first.call 
first.call() 
first.() 
first[]
first.=== 

multiply_by_2 = ->(num) { num * 2 }

puts multiply_by_2.call(4)

# Procs in Ruby 

result = Proc.new do |a,b|
  puts "inside the proc"
  sum = a + b 
  product = a * b 
  puts "The sum of #{a} and #{b} is #{sum}"
  puts "The product of #{a} and #{b} is #{product}"
  puts "coming out of the proc"
end

result.call(2,4)

puts Proc.instance_methods

b = Proc.new { |one, two| puts "#{one}, #{two}"}

b.call 

b = ->(one, two) { puts "#{one}, #{two}"}

b.call(2,3)

# lambda 
hello = -> { return 'hello'}

puts "#{hello.call}"

#  proc 
# hello = Proc.new { return 'hello'}
# puts "#{hello.call}"

def hello_method()
  puts "before proc execution..."
  hello = Proc.new { return 'hello'}
  puts "#{hello.call}"
  puts "after proc execution..."
end 

hello_method() 

# procs and lambdas 
# Proc.new {} , ->() {} 
# returns from the current method, return from the lambda 
# procs do not care about arguments while lambdas 
# raise an exception in such cases

# Closures 

def invoke_proc(proc_fn)
  counter = 1
  proc_fn.call 
end 

counter = 0
proc_fn = Proc.new { puts counter }

invoke_proc(proc_fn)

# binding class 

def get_binding()
  foo = 1 
  bar = 2 
  binding 
end 

puts get_binding.eval('foo')
puts get_binding.eval('bar')

# puts foo 
# puts bar

string_one = "I love JavaScript and Ruby"

puts string_one =~ /love/ 

puts string_one.include? 'love' 

# Character classes 

# [aeiou]

def includes_vowel(string_one)
  return string_one =~ /[aeiou]/
end 

puts includes_vowel('love')
puts includes_vowel('nerd')
puts includes_vowel('xyz')

#character ranges 

puts /[1-4]/

def contains_number_from_14(number_one)
  return number_one =~ /[1-4]/
end 

puts contains_number_from_14('23456')
puts contains_number_from_14('7890')

# [0-9],[a-z],[^a-z]
# \d 

#wildcards 

puts "7f4".match(/\d.\d/)
puts "7f4".match(/\d\.\d/)
puts "7.4".match(/\d\.\d/)

# Modifiers 

# +  one or more characters 
# *  zero or more characters 
# ?  zero or one character 
# {2,4}, {5,9}

def validate_ip_address(string_one)
  return !!(string_one =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)
end 

puts validate_ip_address("176.334.1.1")
puts validate_ip_address("000.334.1.1")
puts validate_ip_address("0000.334.1.1")

# ^

puts !!"the nerdy dev".match(/^the/)

# Modules 

module Computation
  PIE = 3.14
  def self.double(number)
    return number*2
  end 
end 

puts Computation::PIE
puts Computation.double(45)

# include 

class Calculator 
  include Computation
end 

puts Calculator.ancestors 


module Al

end 

class B 
end 

class C < B
  include Al 
end 

puts C.ancestors 

# Enumerable 

# inject 

result = [1,2,3,4,5].inject { |acc, current_number| acc + current_number }

puts "#{result}"


items_count = { }
items_count[:pencils] = 20 
items_count[:pens] = 45
items_count[:laptops] = 3 

puts "Current hash map : #{items_count}"

count_of_items = items_count.inject(0) { 
 |acc, (key, value) | acc + value
}

puts "Count of items : #{count_of_items}"

# class ProductRepository extend Enumerable
#   def self.all
#     [
#     Product.new('A Perfume', 24),
#     Product.new('A Shoe', 67),
#     Product.new('Apple Macbook', 3000)
#   ]
#   end 

#   def self.each
#     all.each {|product| yield product } 
#   end 
# end 


# Product = Struct.new(:product_name, :product_price)

# puts ProductRepository.select {
#   |product| product.product_price > 90
# }

# implement map method 

class Shop
  attr_accessor :products 

  def initialize
      @products = [
      Product.new('A Perfume', 24),
      Product.new('A Shoe', 67),
      Product.new('Apple Macbook', 3000)
    ]
  end
  def map()
    results = []
    @products.each { |product| results << yield(product)}
    return results 
  end 
end 

Product = Struct.new(:product_name, :product_price)



# instance for shop 
shop = Shop.new 
puts "#{shop.map(&:product_name)}"

# enumerator objects

puts "#{[1,2,3,4].to_enum()}"

enum = [1,2,3,4].select 
puts enum.class 

puts enum.each { |number| number % 2 == 0}

# next 
puts enum.next 
puts enum.next 
puts enum.next 
puts enum.next 
# puts enum.next 

enum.rewind 
puts enum.next 
enum.rewind 

loop {
  puts enum.next 
}

# Exceptions 

# def buy_cheese()
#   puts "cheese bought!"
# end 


# def buy_chocolate()
#   raise "No chocolate left!"
# end 


# def go_shopping()
#   buy_cheese() 
#   buy_chocolate() 
# end 


# go_shopping() 

# 1.txt 

# File.open("1.txt")

def open_file() 
  content = File.read("items.csv")
  File.write('items-copy.csv', content)
rescue Errno::ENOENT => ex
  puts "File not found.."
  puts ex.message 
  puts ex.backtrace 
end 


open_file()

# ensure 

begin 
  puts "Inside the begin block"
ensure 
  puts "I will always get executed"
end 


# map and all 

array_elements = Array(1..10_00_000)
array_elements.lazy.map {|n| puts n; n ** 2 }.all? {
  |n| n < 500; 
}

I hope you enjoyed the video. Do like, share and subscribe to my channel for more such awesome videos. Keep coding !

Categories
reactjs

โœจTop resources to learn React.js [in no particular order]

Hey everyone ๐Ÿ‘‹๐Ÿป,

I recently wrote an article where I mentioned about React Projects Every Beginner Should Try : https://dev.to/thenerdydev/10-react-projects-every-beginner-should-try-fk9.

In this article, I will be mentioning the top 5 resources that I highly recommend if you want to learn React.js.

PS : I am not an affiliate of any of these resources/courses. These are just some of my personal recommendations if you are looking to learn React.

Introduction

Image description


React.js is a frontend JavaScript library for building amazing, sleek and performant user interfaces specifically for single page applications a.k.a SPAs. It is used for handling the view layer for web and mobile apps. React allows us to compose the entire user interface using the basic building blocks that are called as components.

Here are the top 5 recommendations (in no particular order) of the courses that you should definitely check out for learning React.

1. Build Web Apps with React & Firebase by Shaun Pelling a.k.a The Net Ninja (rated 4.8)

Image description

Shaun is a gifted teacher. He knows how to explain stuff in a very easy and lucid manner. This course will definitely take your knowledge to the next level if you are looking to learn this specific technology.

Here is what this course covers

Learn how to create modern & dynamic React websites from the ground up

Learn how to implement a database, authentication & file uploads with React & Firebase

Learn about Components, Props, Hooks, Context, State, Reducers & the React Router

Create & deploy fully fledged user-based React websites

Course Link :

https://www.udemy.com/course/build-web-apps-with-react-firebase/

2. React.js – The Complete Guide by Maximilian Schwarzmuller ( rated 4.6)

Image description

This course as the name can probably tell you covers the internals of React in great detail. The course starts from the very basics like What React.js is and how it works and later on moves to more complex and advanced topics

Here is what this course covers

A thorough introduction to React.js (What is it and why would you use it?)

All the core basics: How React works, building components with React & building UIs with React

Components, props & dynamic data binding

Working with user events and state to create interactive applications

A (thorough) look behind the scenes to understand how React works under the hood

Detailed explanations on how to work with lists and conditional content

React Hooks (in-depth)!

Working with built-in Hooks and building custom Hooks

How to debug React apps

Styling React apps with “Styled Components” and “CSS Modules”

Working with “Fragments” & “Portals”

Dealing with side effects

Class-based components and functional components

Sending Http requests & handling transitional states + responses

Handling forms and user input (incl. validation)

Redux & Redux Toolkit

Routing with React Router

An in-depth introduction into Next.js

Deploying React Apps

Implementing Authentication

Unit Tests

Combining React with TypeScript

Adding Animations

Tons of examples and demo projects so that you can apply all the things you learned in real projects

and more …

Course Link :

https://www.udemy.com/course/react-the-complete-guide-incl-redux/

3. Complete React Developer in 2022 (w/ Redux, Hooks, GraphQL)

Become a Senior React Developer! Build a massive E-commerce app with Redux, Hooks, GraphQL, ContextAPI, Stripe, Firebase. This course is created by two instructors – Andrei Neagoie and Yihua Zhang who have working experience with some of the best US Startups and big companies.

Image description

Here is what this course covers

React Basics

– React Router

– Redux

– Redux Saga

– Asynchronous Redux

– React Hooks

– Context API

– React Suspense + React Lazy

– Firebase

– Stripe API

– Styled-Components

– GraphQL

– Apollo

– PWAs

– React Performance

– React Design Patterns

– Testing with Jest, Enzyme and Snapshot testing

– React Best Practices

– Persistence + Session Storage

– State Normalization

Course Link :

https://www.udemy.com/course/complete-react-developer-zero-to-mastery

4. React.js Documentation (a must thing to refer)

Image description

Docs link :

https://reactjs.org/docs/getting-started.html

So this is it for this article. Thanks for reading.
Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Categories
frontend javascript web development

JavaScript methods for finding elements

Hey guys,

Welcome back to a new article !

In this article, we will learn about different JavaScript methods that we can make use of for finding elements in an array. Arrays, as we know, is a data structure that is one of the key building blocks that we make use of for building data-based intensive web applications. With an array, we can easily store and manipulate elements within the array as and how we want to. Let us see the 4 methods that you can make use of for finding an element in an array.


find

The find() method returns the first element in the provided array that satisfies the provided testing function. So we specify a testing function as the callback and the find method will return the first item that returns true for the condition that we test within the specified callback. If no elements satisfy the testing function, then undefined gets returned. Let us see an example for the find method.

const numbers = [5, 12, 8, 130, 44];

const firstNumberGreaterThan10 = numbers.find(element => element > 10);

console.log(firstNumberGreaterThan10 );
// expected output: 12

findIndex

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. So as a testing function, we pass a callback to the findIndex method and there we explicitly mention a condition and based on the truthiness of that condition, we get an element that satisfies that specified condition. In case, no element passes the testing condition then it returns -1.

const numbers = [1, 3, 4, 6, 10];

const greaterIndex = numbers.findIndex(element => element > 6); 
console.log(greaterIndex); // 4

const smallerIndex = numbers.findIndex(element => element > 10); 
console.log(smallerIndex); // -1 

Consider the above example in which we have a list of numbers that is given to us, let us say we want to find the index of the first occurrence of an element which is greater than 6. So for this case, we can make use of the findIndex method with the testing condition as element > 6. Next, let us say we want to find the index of the first occurrence of an element which is greater than 10. So we again make use of the findIndex method with the testing condition as element > 10. Now since there is no element that satisfies the above condition, hence we get a -1 for this.


indexOf

The indexOf() method returns the index of the first occurrence of the substring or element that we specify as the argument.

Let us see an example for the indexOf method, let us say we are given an array of elements and we want to find the index of some elements within that array. So see the below code :

const numbers = [1, 3, 4, 6, 10];

const indexOf10 = numbers.indexOf(10); // 4

const indexOf16 = numbers.indexOf(16); // -1

So if we try to search the index of the number 10 in the given array of numbers, then we get 4 because 10 is sitting at index 4 of the given array. Next, for the number 16 we get -1 because the number 16 is not present anywhere within the given array.


lastIndexOf

The lastIndexOf() method returns the index of the last occurrence of the specified substring or element that we specify as argument. The lastIndexOf method is similar to the indexOf method that we just discussed but the only difference being that it starts to look up from the trailing end of the array instead of the start of the array like we do in indexOf. So in essence, if you know for sure that the element that you are looking for lies in the latter half of the array, then using the lastIndexOf method makes more sense.

const numbers = [1, 3, 4, 6, 10];

const indexOf10FromLast = numbers.lastIndexOf(10); 

console.log(indexOf10FromLast); // 4

const indexOf16FromLast = numbers.lastIndexOf(16); 

console.log(indexOf16FromLast); // -1

So in above example, if we try to find the index of the last occurrence of a particular element, say 10, then we get 4. Since, 10 is present at index 4 and we only have one occurrence of 10 in the numbers array. Next, 16 is not present anywhere in the array so for that if we try to find the last occurrence of it using the lastIndexOf method, we get -1.


So this is it for this article. Thanks for reading.

Categories
Uncategorized

Literals, Variables and Constants in C++

Variables, Literals and Constants in C++

In this tutorial, let us learn about variables, literals, and constants in C++ with help of some examples. So let us learn first what a variable is in C++.

C++ Variables

In programming, a variable is defined as a container that is used to store data. So it is used to store some information that we can later on reference and manipulate in our code.

So to create a variable, we first need a unique name for the variable. This unique name for the variable is also called as the identifier. So let us see some examples on how we can create and initialize variables in C++.

int age = 23; 
char b = 'a'

Here, age is a variable of the int data type, and to it we have assigned a value of 23. Next we have b which is a variable of the char data type and to it we have assigned some character data which in this case is ‘a’.

Note: One thing to note here is that a variable with the int data type can only hold integers. Similarly, a variable with the char data type can only hold data of character type. If we want to store decimals and exponentials, we can make use of the double data type.

Another thing to note here is that the variables are mutable in the sense that you can reassign the variable to difference values and hence this implies that you can change the content of a variable.

Let us also see an example for this :

int age = 23;   // initially age is set to 23
age = 29;       // reassigning the age to a new value of 29

Rules for naming a variable

  • A variable name can only have alphabets, numbers, and the underscore _.
  • A variable name cannot begin with a number.
  • It is a preferred practice to begin variable names with a lowercase character. For example, name is preferable to Name.
  • A keyword cannot be used as a variable name. For example, a keyword like int cannot be used as a variable name.
  • A variable name can start with an underscore. Also ensure that you give meaningful names to your variables which semantically makes sense.


C++ Literals

Literals are data used for representing fixed values. They can be used directly in the code. So in essence, these are source code representation of a fixed value or a sequence of characters which represents a constant value that is to be stored inside a variable.

For example: 156.5'z' etc.

Now these are called literals because you cannot assign a different value to these terms. Here is a list of different literals that we have in C++ Programming :


1. Integers

According to Wikipedia,

 An integer is a datum of integral data type, a data type that represents some range of mathematical integers. Integral data types may be of different sizes and may or may not be allowed to contain negative values. Integers are commonly represented in a computer as a group of binary digits (bits)

This means that an integer is a numerical literal that does not have any fractional or exponent within it. There are three types of integer literals in C Programming :

  • decimal (base 10)
  • octal (base 8)
  • hexadecimal (base 16)

For example:

Decimal: 0, -21, 46 etc
Octal: 02, 786 etc
Hexadecimal: 0x3f,  0x421 etc

A thing to note here is that an octal starts with aย 0 and a hexadecimal starts with aย 0x.


2. Floating-point Literals

Floating-point literals are numbers that have a decimal point or an exponential part. They can be represented as: Real literals. Binary floating-point literals.

-2.0

0.0000234

-0.22E-5

Note: E-5 = 10-5


3. Characters

A character literal is a type of literal in programming for the representation of a single character’s value within the source code of a computer program. It is represented by enclosing a single character inside single quotes. For example : 'b', 'f', 'G', '21', '}' etc.


4. Escape Sequences

 An escape sequence is a combination of characters that has a meaning other than the literal characters contained therein; it is marked by one or more preceding characters

Here is a lit of escape sequences for the given characters :

Escape SequencesCharacters
\bBackspace
\fForm feed
\nNewline
\rReturn
\tHorizontal tab
\vVertical tab
\\Backslash
\'Single quotation mark
\"Double quotation mark
\?Question mark
\0Null Character

5. String Literals

A string literal is a sequence of characters enclosed in double-quote marks. For example:

"This is a string"create a string
""empty string
" "string with a whitespace in quotes.
"x"a single character enclosed within quotes.
"This is a string\n"prints a string with a newline

We will also learn about Strings in a separate article as well. Let us now move forward to constants in C++.


C++ Constants

The value of a constant never changes once defined, so kind of it is immutable and cannot be re-assigned once a value has been fixed for a constant.

const int PI = 3.14;
PI = 3.233 // Error! PI is a constant.

See the above example here we have used the const keyword to declare a constant which we have named PI. Now if we try to mutate or change the value of PI,we will get an error because we cannot reassign a variable that we have declared using the const keyword. If we do so, we will get an error.

We can also create a constant using the #define preprocessor directive, something that we will learn about in a separate article.

Categories
web design web development

Top 10 Tools for Web Design

Are you looking for magic tools to ease out your design process ?
Well, your search ends here. In this article, I am going to present you 10 tools that are a MUST to ease out your design process and make your overall workflow super efficient.

With me ? Amazing. Here we go.

The first tool is:

1. Pexels

Pexels.com is my top most preferred website to grab royalty free images for my projects. The best part of these images is that they are professional high grade images that you can use in your web designs.

Link: https://pexels.com

2. CSS Clip Path Maker (Clippy)

Clippy is another amazing tool that you can use for image clipping. It gives you different templates that you can apply on your images to make them look different and eases the clipping process. So you drag a couple of points here and there and it gives you the CSS property for same that you can directly paste into your project and you are DONE. Isn’t it dead simple ? Pretty awesome, right?

Link : https://bennettfeely.com/clippy/

3. CSS Gradient

CSS Gradient is another quality tool that helps you in creating amazing and sleek gradients to enhance the overlook look, feel and aesthetics of your website. This is another must have tool for web design.

Link: https://cssgradient.io/

4. Animista

Who can forget Animista ? It is literary one of the best CSS tools that I have used so far for creating amazing, smooth and clean animations. IMO it is the best tool that you can use to animate your CSS elements. It lets you go crazy and creative at the very same time. It also provides tons of COOL animations out of the box which can be useful for most of the cases. You can even tweak them a bit to generate animations with the desired effect that you are looking for.

Link: https://animista.net/

4. ColorHunt

Color Hunt is a free and open platform for color inspiration with thousands of trendy hand-picked color palettes. So use these palettes for colors that look great to the eye.

Link: https://colorhunt.co/

5. Filter CSS Generator

A filter CSS generator that helps you quickly generate filter CSS declarations for your website. It comes with many options and it demonstrates instantly.

Link: https://cssgenerator.org/

5. Keyframes.app

Keyframes helps you write better CSS. It provides dead simple visual tools to help you generate CSS for your projects.It is a pretty new tool but I feel it has tremendous potential. Currently it allows you to play with animations, colors and shadows. So feel free to try this tool as well.

Link: https://keyframes.app/

6. Bounce.js

Bounce.js is a handy JavaScript library that enables you to create complicated animations. Bounce.js has a mature user interface that allows you to either add different components โ€“ such as easing, duration, delay, and number of bounces โ€“ manually to your animation, or select a ready-to-use preset, then play the animation, and fine-tune the properties if itโ€™s necessary.

Link: https://bouncejs.com

7. Single Element CSS Spinners

Looking for enhancing your CSS designs with simple yet awesome looking animated loading spinners ? If the answer is yes, this CSS spinner library may be the perfect choice for you.

Link: https://projects.lukehaas.me/css-loaders/

8. Normalize.css

A HTML5-ready alternative to CSS resets. It preserves some useful browser default settings, normalizes styles for a wide range of HTML elements, corrects some common browser inconsistencies, and is well commented for easier use.

Link: https://necolas.github.io/normalize.css/

9. Voxel.css

Voxel.css is a CSS library for 3D rendering. Voxel is flexible enough to be used for everything from 3D web animations to full-on video games. It exposes 4 different classes – Scene, World, Editor and Voxel. So it offers a customization that is as close as a full 3D animation website.

Link: http://www.voxelcss.com/

10. Blush

Easily create stunning and beautiful illustrations with collections made by artists across the globe

Link: https://blush.design/

Those are my 10 favorite resources which I use in countless projects, go ahead and try those and let me know what you think of them!

๐Ÿ‘‰๐Ÿป Follow me on Twitter : https://twitter.com/The_Nerdy_Dev

๐Ÿ‘‰๐Ÿป Check out my YouTube Channel : https://youtube.com/thenerdydev

Categories
javascript

A Quick Refresher on Scopes in JavaScript – Function Scope, Global Scope and Block Scope

In this video, we will do a basic refresher on Scopes in JavaScript before we proceed further with more advanced topics in JavaScript. We will first talk about the Global Scope in JavaScript along with Function Scopes where we use the var keyword. Then we will move further and talk about the block scope in JavaScript that uses the modern ES6 introduced let and const keywords.

Follow me on:
๐Ÿ‘‰ Twitter:ย https://twitter.com/The_Nerdy_Dev
๐Ÿ‘‰ Instagram:ย https://instagram.com/thenerdydev

Categories
css

Creating Complex Animations using CSS Keyframes [video]

In this video, we will learn how we can create complex animations using CSS Keyframes. We will make use of the @keyframes CSS rule to define the percentage of time through a timing sequence.

Follow me on:
๐Ÿ‘‰ Twitter:ย https://twitter.com/The_Nerdy_Dev
๐Ÿ‘‰ Instagram:ย https://instagram.com/thenerdydev