Intro To Javascript
Intro To Javascript
to JavaScript
Introduction to JavaScript
JavaScript is a programming language that adds interactivity to your website. This happens
in games, in the behavior of responses when buttons are pressed or with data entry on
forms; with dynamic styling; with animation, etc. This article helps you get started with
JavaScript and furthers your understanding of what is possible.
What is JavaScript?
JavaScript is a powerful programming language that can add interactivity to a website. It was
invented by Brendan Eich.
JavaScript is versatile and beginner-friendly. With more experience, you'll be able to create
games, animated 2D and 3D graphics, comprehensive database-driven apps, and much
more!
JavaScript itself is relatively compact, yet very flexible. Developers have written a variety of
tools on top of the core JavaScript language, unlocking a vast amount of functionality with
minimum effort. These include
JavaScript is one of the most popular modern web technologies! As your JavaScript skills
grow, your websites will enter a new dimension of power and creativity.
However, getting comfortable with JavaScript is more challenging than getting comfortable
with HTML and CSS. You may have to start small, and progress gradually. To begin, let's
examine how to add JavaScript to your page for creating a Hello world! example.
1) Go to your test site and create a new folder named scripts. Within the scripts folder,
create a new text document called main.js, and save it.
2) In your index.html file, enter this code on a new line, just before the closing
</body> tag:
3) This is doing the same job as the <link> element for CSS. It applies JavaScript to
the page, so it can have an effect on the HTML (along with the CSS, and anything
else on the page).
5) Make sure the HTML and JavaScript files are saved. Then load index.html in your
browser. You should see something like this:
What happened?
The heading text changed to Hello world! using JavaScript. You did this by using a function
called querySelector() to grab a reference to your heading and then store it in a variable
called myHeading. This is similar to what we did using CSS selectors. When you want to do
something to an element, you need to select it first.
Following that, the code set the value of the myHeading variable's textContent property
(which represents the content of the heading) to Hello world!
a) Variables
Variables are containers that store values. You start by declaring a variable with the let
keyword, followed by the name you give to the variable:
A semicolon at the end of a line indicates where a statement ends. It is only required when
you need to separate statements on a single line. However, some people believe it's good
practice to have semicolons at the end of each statement. There are other rules for when
you should and shouldn't use semicolons.
You can name a variable nearly anything, but there are some restrictions. If you are unsure,
you can check your variable name to see if it's valid.
JavaScript is case-sensitive. This means myVariable is not the same as myVariable. If you
have problems with your code, check the case!
After assigning a value to a variable, you can change it later in the code:
Note that variables may hold values that have different data types:
b) Comments
Comments are snippets of text that can be added along with the code. The browser ignores
text marked as comments. You can write comments in JavaScript just as you can in CSS:
If your comment contains no line breaks, it's an option to put it behind two slashes like this:
c) Operators
An operator is a mathematical symbol that produces a result based on two values (or
variables). In the following table, you can see some of the simplest operators, along with
some examples to try in the JavaScript console.
There are a lot more operators to explore, but this is enough for now. See Expressions and
operators for a complete list.
d) Conditionals
Conditionals are code structures used to test if an expression returns true or not. A very
common form of conditionals is the if...else statement. For example,
The expression inside the if () is the test. This uses the strict equality operator (as
described above) to compare the variable icecream with the string chocolate to see if the
two are equal. If this comparison returns true, the first block of code runs. If the comparison
is not true, the second block of code—after the else statement—runs instead.
e) Functions
Functions are a way of packaging functionality that you wish to reuse. It's possible to define
a body of code as a function that executes when you call the function name in your code.
This is a good alternative to repeatedly writing the same code. You have already seen some
uses of functions. For example,
These functions, document.querySelector and alert, are built into the browser.
If you see something which looks like a variable name, but it's followed by parentheses— ()
—it is likely a function. Functions often take arguments: bits of data they need to do their job.
Arguments go inside the parentheses, separated by commas if there is more than one
argument.
For example, the alert() function makes a pop-up box appear inside the browser window,
but we need to give it a string as an argument to tell the function what message to display.
You can also define your own functions. In the next example, we create a simple function
that takes two numbers as arguments and multiplies them:
Try running this in the console; then test with several arguments. For example
f) Events
Real interactivity on a website requires event handlers. These are code structures that listen
for activity in the browser, and run code in response. The most obvious example is handling
the click event, which is fired by the browser when you click on something with your mouse.
To demonstrate this, enter the following into your console, then click on the current webpage:
There are a number of ways to attach an event handler to an element. Here we select the
<html> element. We then call its addEventListener() function, passing in the event's name
to listen to ('click') and a function to run when the event happens.
With this review of JavaScript basics completed (above), let's add some new features to our
example site.
Before going any further, delete the current contents of your main.js file — the bit you
added earlier during the "Hello world!" example — and save the empty file. If you don't, the
existing code will clash with the new code you are about to add.
● Choose an image you want to feature on your example site. Ideally, the image will be
the same size as you added previously, or as close as possible.
● Save this image in your images folder.
● Rename the image firefox2.png.
● Add the following JavaScript code to your main.js file.
● Save all files and load index.html in the browser. Now when you click the image, it
should change to the other one.
This is what happened. You stored a reference to your <img> element in myImage. Next, you
made its onclick event handler property equal to a function with no name (an "anonymous"
function). So every time this element is clicked:
Next, let's change the page title to a personalized welcome message when the user first
visits the site. This welcome message will persist. Should the user leave the site and return
later, we will save the message using the Web Storage API. We will also include an option to
change the user, and therefore, the welcome message.
1) In index.html, add the following line just before the <script> element:
2) In main.js, place the following code at the bottom of the file, exactly as it is written. This
takes references to the new button and the heading, storing each inside variables:
3) Add the following function to set the personalized greeting. This won't do anything yet, but
this will change soon.
The setUserName() function contains a prompt() function, which displays a dialog box,
similar to alert(). This prompt() function does more than alert(), asking the user to enter
data, and storing it in a variable after the user clicks OK. In this case, we are asking the user
to enter a name. Next, the code calls on an API localStorage, which allows us to store data
in the browser and retrieve it later. We use localStorage's setItem() function to create and
store a data item called 'name', setting its value to the myName variable which contains the
user's entry for the name. Finally, we set the textContent of the heading to a string, plus the
user's newly stored name.
4) Add the following condition block. We could call this initialization code, as it structures the
app when it first loads.
This first line of this block uses the negation operator (logical NOT, represented by the !) to
check whether the name data exists. If not, the setUserName() function runs to create it. If it
exists (that is, the user set a user name during a previous visit), we retrieve the stored name
using getItem() and set the textContent of the heading to a string, plus the user's name,
as we did inside setUserName().
5) Put this onclick event handler (below) on the button. When clicked, setUserName() runs.
This allows the user to enter a different name by pressing the button.
Also, try clicking OK without entering a name. You should end up with a title that reads
Mozilla is cool, for fairly obvious reasons.
To avoid these problems, you could check that the user hasn't entered a blank name. Update
your setUserName() function to this:
In human language, this means: If myName has no value, run setUserName() again from the
start. If it does have a value (if the above statement is not true), then store the value in
localStorage and set it as the heading's text.
Conclusion
If you have followed all the instructions in this article, you should end up with a page that
looks something like the image below.
We have just scratched the surface of JavaScript. If you enjoyed playing, and wish to go
further, take advantage of the resources listed below.
If you're considering a career in Web3
Development, there's no better time
than now.
Link: https://link.almabetter.com/9w63
Introduction
to HTML
Beginner’s Guide
Introduction to HTML: Beginner’s Guide
What is HTML?
Output:
Sample Contents:
A start tag, some content, and an end tag define an HTML element:
Output:
The HTML element is everything from the start tag to the end tag:
HTML History
Since the early days of the World Wide Web, there have been many versions of
HTML:
HTML Documents
All HTML documents must start with a document type declaration: <!DOCTYPE
html>.
The HTML document itself begins with <html> and ends with </html>.
The visible part of the HTML document is between <body> and </body>.
The <!DOCTYPE> declaration represents the document type and helps browsers
HTML Headings
Output:
HTML Paragraphs
HTML Links
Output:
You will simply be redirected to the linked page source when you click on the link.
The source file (src), alternative text (alt), width, and height are provided as
attributes:
Output:
Have you ever seen a Web page and wondered "Hey! How did they do that?"
View HTML Source Code: Right-click on an HTML page and select "View Page
Source" (in Chrome) or "View Source" (in Edge), or similar in other browsers. This will
open a window containing the HTML source code of the page.
Inspect an HTML Element: Right-click on an element (or a blank area), and choose
"Inspect" or "Inspect Element" to see what elements are made up of (you will see
both the HTML and the CSS). You can also edit the HTML or CSS on-the-fly in the
Elements or Styles panel that opens.
If you're looking to get into Web Development,
then AlmaBetter is the best place to start your
journey.
Link: https://link.almabetter.com/9w63
Python
Basics
Welcome to the Python Basics
Data Science
str
type(a)
str
z = True
type(z)
bool
#Autotypecasting
3 + 4.5
7.5
True + 2
True
True
name = 'vivek'
name = 'vivek'
type(name)
str
Type Casting:
The conversion of one data type into the other data type is known as type casting in python or type
conversion in python.
3 + 6.5
9.5
14.5
int(7.5) + 3
10
bool(0)
False
#Auto typecasting
True + 3 + int(4.5)
str(3) + 'vivek'
'3vivek'
13.5
int('7') + 5
12
a = 3.4
type(a)
float
a= 3
b = 4.5
print(type(a))
print(type(b))
<class 'int'>
<class 'float'>
a + int(b)
3 + int('4')
12
Slicing
Python slice() Function
A slice object is used to specify how to slice a sequence. You can specify where to start the slicing,
and where to end. You can also specify the step, which allows you to e.g. slice only every other
item.
a = "I am a Data Scientist" #indexing start from 0 from I & we count space as well so, index of a is 2, did you under
a # "I=0","space="1","a=2","m=3" & so on.
#"t=-1","s=-2" & so on in case of reverse indexing
a[2:4] #it will print a leetr which is on index 2 & 3 excluding index 4
'am'
'Scientist'
'Data Scientist'
'I am a '
Math Operators
14
6
40
10000
2.5
1
Logical operators are used to combine conditional statements while Comparison operators are
used to compare two values.
True
True
False
True
Logica Operators
T and T --> T
T and F --> F
F and T --> F
F and F --> F
T or F --> T
F or T --> T
F or F --> F
True
False
False
True
True == bool(-18)
True
True
Conditional Statement
x = 2
if (x>0):
print("Positive number")
print("In the IF block")
else:
print("Negative number")
print("In the else block")
Positive number
In the IF block
x=5
if (x>0):
print("X is a positive")
print("I m if True Block")
else:
print("X is a Negative")
print("I m if Else/False Block")
X is a positive
I m if True Block
I am out of IF-ELSE block
if 5 < 3:
print("I am in if block")
print("So the statement is TRUE")
else:
print("I am in ELSE block")
I am in ELSE block
I am anyway printed, out of IF
if (5<3) :
print("True")
print("another statement")
else :
print("False")
print("another else st")
print("This prints anyway")
False
another else st
This prints anyway
More examples
x=12
if (x>10) :
print("This is True or IF block")
print("I am still in IF")
else :
print("This is else block")
----
I am out of IF block
if (5<3):
print("This is IF block")
else :
print("This is Else Block")
if (5<3) :
print("True block statement 1")
print("True block statement 2")
print("True block statement 3")
else:
print("False block")
False block
x = 0
if (x > 0) :
print("X is Positive")
elif (x<0):
print("X is Negative")
else:
print("X is ZERO")
X is ZERO
x=-100
if ((x>0) or (x==-100)):
print("X is positive Value or -100")
print("I am if loop")
elif (x<0):
print("I am in else if block")
print("X is negative")
else:
print("X is Zero")
x = 6
if x%2 == 0 :
print(x, " is even number")
print("hello..")
else :
print(x, " is ODD number")
6 is even number
hello..
this is out of IF else block
x = -20
# if/elif/else statement
if x > 0:
print('positive')
print('hello')
elif x == 0:
print('zero')
else:
print('negative')
print("I am out of IF block")
negative
I am out of IF block
positive
# Hello world
print('Hello world')
Hello world
Hello world!
albert einstein
'hi'
strn="""Hi,
"How are you" """ # assigning multi_line string to varibale strn
strn
c='GoodMorning'
c.startswith("Go") #Test whether c starts with the substring "Go"
True
False
c.replace("i","y") # Return a new string basedon c with all occurances of "i" replaced with "y"
'GoodMornyng'
strn.split(" ") # Split the string strn into a list of strings, separating on the character " " and return that list
"{} plus {} plus {} is {}".format(1,2,4,7) # Return the string with the values 3, 1, and 4 inserted
'goodmorning'
'GOODMORNING'
c.title() # Returns c with the first letter of every word capitalized
'Goodmorning'
'GoodM'
'GetLost'
True
Lists
A list stores a series of items in a particular order. You access items using an index, or within a
loop.
# Make a list
bikes = ['trek', 'redline', 'giant']
'trek'
'giant'
trek
redline
giant
# List comprehensions
squares = [x**2 for x in range(1, 11)]
squares
# Slicing a list
finishers = ['sam', 'bob', 'ada', 'bea']
first_two = finishers[:2]
first_two
['sam', 'bob']
# Copying a list
copy_of_bikes = bikes[:]
copy_of_bikes
z=[100,20,30,45,68,54]
# Return the first value in the list z
z[0]
100
54
# Return a slice (list) containing the fourth and fifth values of z
z[3:5]
[45, 68]
317
20
100
" ".join(["A","B","C","D"]) # Converts the list["A", "B", "C", "D"] into the string "A B C D"
'A B C D'
z.pop(3) # Returns the fourth item from a and deletes it from the list
45
z # 45 got deleted
z # 30 got removed
z[1::2] # Returns every second item from a,commencing from the 1st item
[21, 68]
Tuples
Tuples are similar to lists, but the items in a tuple can't be modified.
# Concating 2 tuples
tuple_1='Android','java','HTML'
tuple_2=5,8,6,9
print(tuple_1 + tuple_2)
# repetition
tup=('Hello',)*5
print(tup)
# Nesting of Tuples
tup_1=('Python','Java','CSS','HTML')
tup_2=(1,5,8,6,7,3)
tup_3=(tup_1,tup_2)
print(tup_3)
# lenght of tuple
t=('A','B','C','D')
print(len(t))
# Tuples in loop
A = ('Hello_World',)
n = 10 #Number of time loop runs
for i in range(int(n)):
tup = (A,)
print(tup)
(('Hello_World',),)
(('Hello_World',),)
(('Hello_World',),)
(('Hello_World',),)
(('Hello_World',),)
(('Hello_World',),)
(('Hello_World',),)
(('Hello_World',),)
(('Hello_World',),)
(('Hello_World',),)
# create a tuple
digits1 = (0, 1, 'two',0,1,1,1) # create a tuple directly
# examine a tuple
print(digits1.count(1)) # counts the number of instances of that value (0) digits.index(1) # returns the index of t
len(digits1)
4
7
# using min(),max()
tuple_A=(5,4,3,2,1,8,7)
tuple_B=('Hello','Hi','Bye','Good Morning')
print('max value in tuple_A and B:'+ str(max(tuple_A)) + ',' + str(max(tuple_B)))
print('min value in tuple_A and B:'+ str(min(tuple_A))+ ','+ str(min(tuple_B)))
# if
mark = 10
if (mark > 15):
print ("mark is less than 15")
print ("I am Not in if")
I am Not in if
# if-else
mark = 20;
if (mark < 15):
print ("mark is less than 15")
print ("i'm in if Block")
else:
print ("mark is greater than 15")
print ("i'm in else Block")
print ("i'm not in if and not in else Block")
# nested-if
mark = 10
if (mark == 10):
# First if statement
if (mark < 15):
print ("mark is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (mark < 12):
print ("mark is smaller than 12 too")
else:
print ("mark is greater than 15")
# if-elif-else ladder
mark = 20
if (mark == 10):
print ("mark is 10")
elif (mark == 15):
print ("mark is 15")
elif (mark == 20):
print ("mark is 20")
else:
print ("mark is not present")
mark is 20
# A simple if test
age=20
if age >= 18:
print("You can vote!")
# if-elif-else statements
age=10
if age <=4:
print('ticket_price = 0')
elif age < 18:
print('ticket_price = 10')
else:
print('ticket_price = 15')
ticket_price = 10
Dictionaries
Dictionaries store connections between pieces of information. Each item in a dictionary is a key-
value pair.
# A simple dictionary
alien = {'color': 'green', 'points': 5}
# Accessing a value
print("The alien's color is " + alien['color'])
eric loves 17
ever loves 4
17 is a favorite
4 is a favorite
# creating a dict with NY,IN,UK as key and their full form as values
dict = {"NY":"New_York","IN":"India","UK":"United_Kingdom"}
max(dict, key=dict.get) # Return the key that corresponds to the largest value in dict
'UK'
min(dict, key=dict.get) # Return the key that corresponds to the smallest value in dict
'IN'
While Loop
A while loop repeats a block of code as long as a certain condition is true.
1
2
3
4
5
Hello
Hello
Hello
Hello
Hello
Current Letter : d
Current Letter : o
Current Letter : y
Current Letter : o
Current Letter : u
Current Letter : r
Current Letter : o
Current Letter : r
Current Letter : k
Current Letter : H
Current Letter : a
Current Letter : p
Current Letter : p
Current Letter : y
Current Letter : L
Current Letter : y
Current Letter : u
Current Letter : w
Current Letter : e
Current Letter : f
Current Letter : f
Current Letter : u
Current Letter : y
Current Letter : g
# while-else loop
i = 0
while i < 8:
i += 1
print(i)
else: # Executed because no break in for
print("No Break\n")
i = 0
while i < 8:
i += 1
print(i)
break
else: # Not executed as there is a break
print("No Break")
1
2
3
4
5
6
7
8
No Break
For Loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string).
1
4
16
36
121
400
15
# For loop with else block
for val in range(5):
print(val)
else:
print("The loop has completed execution")
0
1
2
3
4
The loop has completed execution
0 , 10
0 , 11
0 , 12
0 , 13
1 , 10
1 , 11
1 , 12
1 , 13
2 , 10
2 , 11
2 , 12
2 , 13
User Inputs
Your programs can prompt the user for input. All input is stored as a string.
Functions
Functions are named blocks of code, designed to do one specific job. Information passed to a function is called an argument, and information
received by a function is called a parameter.
#Making a function
def greet_user():
"""Display a simple greeting."""
print("Hello!")
greet_user()
Hello!
Hello, jesse!
Hello, diana!
Hello, brandon!
#A simple function
def greet_user():
"""Display a simple greeting."""
print("Hello!")
greet_user()
Hello!
# Passing an argument
def greet_user(username):
"""Display a personalized greeting."""
print("Hello, " + username + "!")
greet_user('jesse')
Hello, jesse!
# Returning a value
def add_numbers(x, y):
"""Add two numbers and return the sum."""
return x + y
sum = add_numbers(3, 5)
print(sum)
I have a hamster.
Its name is harry.
I have a dog.
Its name is willie.
I have a hamster.
Its name is harry.
I have a dog.
Its name is willie.
I have a hamster.
Its name is harry.
I have a dog.
Its name is willie.
I have a hamster.
Its name is harry.
I have a snake.
I have a hamster.
Its name is harry.
I have a dog.
Its name is willie.
I have a hamster.
Its name is harry.
I have a snake.
Hello, hannah!
Hello, ty!
Hello, margot!
Printing ring
Printing pendant
Printing phone case
Unprinted: []
Printed: ['ring', 'pendant', 'phone case']
Printing ring
Printing pendant
Printing phone case
Classes
A class defines the behavior of an object and the kind of information an object can store. The
information in a class is stored in attributes, and functions that belong to a class are called
methods. A child class inherits the attributes and methods from its parent class.
# Inheritance
class SARDog(Dog):
"""Represent a search dog."""
def __init__(self, name):
"""Initialize the sardog."""
super().__init__(name)
def search(self):
"""Simulate searching."""
print(self.name + " is searching.")
my_dog = SARDog('Willie')
print(my_dog.name + " is a search dog.")
my_dog.sit()
my_dog.search()
def drive(self):
"""Simulate driving."""
print("The car is moving.")
audi
a4
2016
Fuel tank is full.
The car is moving.
Lists
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are
Tuple, Set, and Dictionary, all with different qualities and usage.
# Making a list
users = ['val', 'bob', 'mia', 'ron', 'ned']
val
bob
ned
# Changing an element
users[0] = 'valerie'
users[-2] = 'ronald'
users
bob
joe
We have 1 users.
['val']
['val']
val
Welcome, val!
Welcome, we're glad to see you all!
1
99
Hello willie!
Hello hootz!
Hello peso!
Hello goblin!
I love these dogs!
Dictionaries
Use curly braces to define a dictionary. Use colons to connect keys and values, and use commas
to separate individual key-value pairs.
# Making a dictionary
alien_0 = {'color': 'green', 'points': 5}
green
5
green
0
jen: python
sarah: c
edward: ruby
phil: python
jen
sarah
edward
phil
python
c
ruby
python
edward: python
jen: python
phil: python
sarah: python
last: fermi
first: enrico
username: efermi
last: curie
first: marie
username: mcurie
last: fermi
first: enrico
username: efermi
last: curie
first: marie
username: mcurie
jen:
- python
- ruby
sarah:
- c
edward:
- ruby
- go
phil:
- python
- haskell
Username: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris
jen:
- python
- ruby
sarah:
- c
edward:
- ruby
- go
phil:
- python
- haskell
# A million aliens
aliens = []
# Make a million green aliens, worth 5 points
# each. Have them all start in one row.
for alien_num in range(1000000):
new_alien = {}
new_alien['color'] = 'green'
new_alien['points'] = 5
new_alien['x'] = 20 * alien_num
new_alien['y'] = 0
aliens.append(new_alien)
# Prove the list contains a million aliens.
num_aliens = len(aliens)
print("Number of aliens created:")
print(num_aliens)
An if statement checks if an expression is true or false, and then runs the code inside the
statement only if it is true. The code inside the loop is only run once. A while statement is a loop.
Basically, it continues to execute the code in the while statement for however long the expression
is true.
#conditional tests
#Checking for equality
#A single equal sign assigns a value to a variable. A double equal
#sign (==) checks whether two values are equal.
car = 'bmw'
print(car == 'bmw')
car = 'audi'
print(car == 'bmw')
True
False
True
True
True
False
True
True
False
False
age_0 = 18
print(age_0 >= 21 or age_1 >= 21)
False
True
True
False
# if statements
#Simple if statement
age = 19
if age >= 18:
print("You're old enough to vote!")
# If-else statements
age = 17
if age >= 18:
print("You're old enough to vote!")
else:
print("You can't vote yet.")
# The if-elif-else chain
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
else:
price = 10
print("Your cost is $" + str(price) + ".")
True
False
#Simple input
name = input("What's your name? ")
print("Hello, " + name + ".")
#Accepting numerical input
age = input("How old are you? ")
age = int(age)
if age >= 18:
print("\nYou can vote!")
else:
print("\nYou can't vote yet.")
# While loops
# Counting to 5
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
1
2
3
4
5
print(pets)
# An infinite loop
#while True:
# name = input("\nWho are you? ")
# print("Nice to meet you, " + name + "!")
Loading [MathJax]/extensions/Safe.js
If you're looking to get into Data Science, then
AlmaBetter is the best place to start your journey.