JS Day 1
JS Day 1
js
You may not need Node.js right now but you may need it for later. Install node.js.
asabeneh $ node -v
v12.14.0
When making this tutorial I was using Node version 12.14.0, but now the recommended
version of Node.js for download is v14.17.6, by the time you use this material you may
have a higher Node.js version.
Browser
There are many browsers out there. However, I strongly recommend Google Chrome.
Install Google Chrome if you do not have one yet. We can write small JavaScript code
on the browser console, but we do not use the browser console to develop applications.
Opening Google Chrome Console
You can open Google Chrome console either by clicking three dots at the top right
corner of the browser, selecting More tools -> Developer tools or using a keyboard
shortcut. I prefer using shortcuts.
To open the Chrome console using a keyboard shortcut.
Mac
Command+Option+J
Windows/Linux:
Ctl+Shift+J
After you open the Google Chrome console, try to explore the marked buttons. We will
spend most of the time on the Console. The Console is the place where your JavaScript
code goes. The Google Console V8 engine changes your JavaScript code to machine
code. Let us write a JavaScript code on the Google Chrome console:
Writing Code on Browser Console
We can write any JavaScript code on the Google console or any browser console.
However, for this challenge, we only focus on Google Chrome console. Open the
console using:
Mac
Command+Option+I
Windows:
Ctl+Shift+I
Console.log
To write our first JavaScript code, we used a built-in function console.log(). We passed
an argument as input data, and the function displays the output. We passed 'Hello,
World' as input data or argument in the console.log() function.
console.log('Hello, World!')
As you can see from the snippet code above, console.log() can take multiple
arguments.
Comments
We can add comments to our code. Comments are very important to make code more
readable and to leave remarks in our code. JavaScript does not execute the comment
part of our code. In JavaScript, any text line starting with // in JavaScript is a comment,
and anything enclosed like this // is also a comment.
/*
This is a multiline comment
Multiline comments can take multiple lines
JavaScript is the language of the web
*/
Syntax
I made a deliberate mistake. As a result, the console raises syntax errors. Actually, the
syntax is very informative. It informs what type of mistake was made. By reading the
error feedback guideline, we can correct the syntax and fix the problem. The process of
identifying and removing errors from a program is called debugging. Let us fix the
errors:
console.log('Hello, World!')
console.log('Hello, World!')
So far, we saw how to display text using the console.log(). If we are printing text or
string using console.log(), the text has to be inside the single quotes, double quotes,
or a backtick. Example:
console.log('Hello, World!')
console.log("Hello, World!")
console.log(`Hello, World!`)
Arithmetics
Now, let us practice more writing JavaScript codes using console.log() on Google
Chrome console for number data types. In addition to the text, we can also do
mathematical calculations using JavaScript. Let us do the following simple calculations.
It is possible to write JavaScript code on Google Chrome console can directly without
the console.log() function. However, it is included in this introduction because most of
this challenge would be taking place in a text editor where the usage of the function
would be mandatory. You can play around directly with instructions on the console.
console.log(2 + 3) // Addition
console.log(3 - 2) // Subtraction
console.log(2 * 3) // Multiplication
console.log(3 / 2) // Division
console.log(3 % 2) // Modulus - finding remainder
console.log(3 ** 2) // Exponentiation 3 ** 2 == 3 * 3
Code Editor
We can write our codes on the browser console, but it won't be for bigger projects. In a
real working environment, developers use different code editors to write their codes. In
this 30 days of JavaScript challenge, we will be using Visual Studio Code.
Visual Studio Code is a very popular open-source text editor. I would recommend to
download Visual Studio Code, but if you are in favor of other editors, feel free to follow
with what you have.
Open the Visual Studio Code by double-clicking its icon. When you open it, you will get
this kind of interface. Try to interact with the labeled icons.
Adding JavaScript to a Web Page
JavaScript can be added to a web page in three different ways:
● Inline script
● Internal script
● External script
● Multiple External scripts
The following sections show different ways of adding JavaScript code to your web page.
Inline Script
Create a project folder on your desktop or in any location, name it 30DaysOfJS and
create an index.html file in the project folder. Then paste the following code and open it
in a browser, for example Chrome.
<!DOCTYPE html>
<html lang="en">
<head>
<title>30DaysOfScript:Inline Script</title>
</head>
<body>
<button onclick="alert('Welcome to 30DaysOfJavaScript!')">Click Me</button>
</body>
</html>
Now, you just wrote your first inline script. We can create a pop up alert message using
the alert() built-in function.
Internal Script
The internal script can be written in the head or the body, but it is preferred to put it on
the body of the HTML document. First, let us write on the head part of the page.
<!DOCTYPE html>
<html lang="en">
<head>
<title>30DaysOfScript:Internal Script</title>
<script>
console.log('Welcome to 30DaysOfJavaScript')
</script>
</head>
<body></body>
</html>
This is how we write an internal script most of the time. Writing the JavaScript code in
the body section is the most preferred option. Open the browser console to see the
output from the console.log().
<!DOCTYPE html>
<html lang="en">
<head>
<title>30DaysOfScript:Internal Script</title>
</head>
<body>
<button onclick="alert('Welcome to 30DaysOfJavaScript!');">Click
Me</button>
<script>
console.log('Welcome to 30DaysOfJavaScript')
</script>
</body>
</html>
Open the browser console to see the output from the console.log().
External Script
Similar to the internal script, the external script link can be on the header or body, but it
is preferred to put it in the body. First, we should create an external JavaScript file with
.js extension. All files ending with .js extension are JavaScript files. Create a file named
introduction.js inside your project directory and write the following code and link this .js
file at the bottom of the body.
console.log('Welcome to 30DaysOfJavaScript')
<!DOCTYPE html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:External script</title>
<script src="introduction.js"></script>
</head>
<body></body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:External script</title>
</head>
<body>
<!-- JavaScript external link could be in the header or in the body -->
<!-- Before the closing tag of the body is the recommended place to put the
external JavaScript script -->
<script src="introduction.js"></script>
</body>
</html>
console.log('Hello, World!')
<!DOCTYPE html>
<html lang="en">
<head>
<title>Multiple External Scripts</title>
</head>
<body>
<script src="./helloworld.js"></script>
<script src="./introduction.js"></script>
</body>
</html>
Your main.js file should be below all other scripts. It is very important to remember this.
Introduction to Data types
In JavaScript and also other programming languages, there are different types of data
types. The following are JavaScript primitive data types: String, Number, Boolean,
undefined, Null, and Symbol.
Numbers
● Integers: Integer (negative, zero and positive) numbers Example: ... -3, -2, -1, 0,
1, 2, 3 ...
● Float-point numbers: Decimal number Example ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2,
3.5 ...
Strings
A collection of one or more characters between two single quotes, double quotes, or
backticks.
Example:
'a'
'Asabeneh'
"Asabeneh"
'Finland'
'JavaScript is a beautiful programming language'
'I love teaching'
'I hope you are enjoying the first day'
`We can also create a string using a backtick`
'A string could be just as small as one character or as big as many pages'
'Any data type under a single quote, double quote or backtick is a string'
Booleans
A boolean value is either True or False. Any comparisons returns a boolean value,
which is either true or false.
Example:
Undefined
In JavaScript, if we don't assign a value to a variable, the value is undefined. In addition
to that, if a function is not returning anything, it returns undefined.
let firstName
console.log(firstName) // undefined, because it is not assigned to a value yet
Null
Null in JavaScript means an empty value.
Comments Again
Remember that commenting in JavaScript is similar to other programming languages.
Comments are important in making your code more readable. There are two ways of
commenting:
Multiline commenting:
/*
let location = 'Helsinki';
let age = 100;
let isMarried = true;
This is a Multiple line comment
*/
Variables
Variables are containers of data. Variables are used to store data in a memory location.
When a variable is declared, a memory location is reserved. When a variable is
assigned to a value (data), the memory space will be filled with that data. To declare a
variable, we use var, let, or const keywords.
For a variable that changes at a different time, we use let. If the data does not change at
all, we use const. For example, PI, country name, gravity do not change, and we can
use const. We will not use var in this challenge and I don't recommend you to use it. It is
error prone way of declaring variable it has lots of leak. We will talk more about var, let,
and const in detail in other sections (scope). For now, the above explanation is enough.
firstName
lastName
country
city
capitalCity
age
isMarried
first_name
last_name
is_married
capital_city
num1
num_1
_num_1
$num1
year2020
year_2020
The first and second variables on the list follows the camelCase convention of declaring
in JavaScript. In this material, we will use camelCase variables(camelWithOneHump).
We use CamelCase(CamelWithTwoHump) to declare classes, we will discuss about
classes and objects in other section.
first-name
1_num
num_#_1
Let us declare variables with different data types. To declare a variable, we need to use
let or const keyword before the variable name. Following the variable name, we write an
equal sign (assignment operator), and a value(assigned data).
// Syntax
let nameOfVariable = value
The nameOfVriable is the name that stores different data of value. See below for detail
examples.
When you run index.html file in the 01-Day folder you should get this:
Data Types
In the previous section, we mentioned a little bit about data types. Data or values have
data types. Data types describe the characteristics of data. Data types can be divided
into two:
1. Objects
2. Arrays
Now, let us see what exactly primitive and non-primitive data types mean. Primitive data
types are immutable(non-modifiable) data types. Once a primitive data type is created
we cannot modify it.
Example:
If we try to modify the string stored in variable word, JavaScript should raise an error.
Any data type under a single quote, double quote, or backtick quote is a string data
type.
word[0] = 'Y'
This expression does not change the string stored in the variable word. So, we can say
that strings are not modifiable or in other words immutable. Primitive data types are
compared by its values. Let us compare different data values. See the example below:
let numOne = 3
let numTwo = 3
let js = 'JavaScript'
let py = 'Python'
nums[0] = 10
console.log(nums) // [10, 2, 3]
As you can see, an array, which is a non-primitive data type is mutable. Non-primitive
data types cannot be compared by value. Even if two non-primitive data types have the
same properties and values, they are not strictly equal.
let userOne = {
name:'Asabeneh',
role:'teaching',
country:'Finland'
let userTwo = {
name:'Asabeneh',
role:'teaching',
country:'Finland'
Rule of thumb, we do not compare non-primitive data types. Do not compare arrays,
functions, or objects. Non-primitive values are referred to as reference types, because
they are being compared by reference instead of value. Two objects are only strictly
equal if they refer to the same underlying object.
let userOne = {
name:'Asabeneh',
role:'teaching',
country:'Finland'
If you have a hard time understanding the difference between primitive data types and
non-primitive data types, you are not the only one. Calm down and just go to the next
section and try to come back after some time. Now let us start the data types by number
type.
Numbers
Numbers are integers and decimal values which can do all the arithmetic operations.
Let's see some examples of Numbers.
// More Examples
Math Object
In JavaScript the Math Object provides a lots of methods to work with numbers.
const PI = Math.PI
console.log(PI) // 3.141592653589793
console.log(Math.round(9.81)) // 10
console.log(Math.ceil(PI)) // 4 rounding up
console.log(randNum)
console.log(num)
//Absolute value
console.log(Math.abs(-10)) // 10
//Square root
console.log(Math.sqrt(100)) // 10
console.log(Math.sqrt(2)) // 1.4142135623730951
// Power
console.log(Math.pow(3, 2)) // 9
console.log(Math.E) // 2.718
// Logarithm
console.log(Math.log(2)) // 0.6931471805599453
console.log(Math.log(10)) // 2.302585092994046
console.log(Math.LN2) // 0.6931471805599453
console.log(Math.LN10) // 2.302585092994046
// Trigonometry
Math.sin(0)
Math.sin(60)
Math.cos(0)
Math.cos(60)
The JavaScript Math Object has a random() method number generator which generates
number from 0 to 0.999999999...
let randomNum = Math.random() // generates 0 to 0.999...
Now, let us see how we can use random() method to generate a random number
between 0 and 10:
Strings
Strings are texts, which are under single , double, back-tick quote. To declare a string,
we need a variable name, assignment operator, a value under a single quote, double
quote, or backtick quote. Let's see some examples of strings:
String Concatenation
Connecting two or more strings together is called concatenation. Using the strings
declared in the previous String section:
console.log(fullName);
Asabeneh Yetayeh
Concatenating using the addition operator is an old way. This way of concatenating is
tedious and error-prone. It is good to know how to concatenate this way, but I strongly
suggest to use the ES6 template strings (explained later on).
let personInfoOne = fullName + '. I am ' + age + '. I live in ' + country; //
ES5 string addition
console.log(personInfoOne)
Asabeneh Yetayeh. I am 250. I live in Finland
A string could be a single character or paragraph or a page. If the string length is too big
it does not fit in one line. We can use the backslash character (\) at the end of each line
to indicate that the string will continue on the next line. Example:
Node.js, Python, Data Analysis and D3.js for anyone who is interested to learn.
\
console.log(paragraph)
console.log('Days\tTopics\tExercises')
console.log('Day 1\t3\t5')
console.log('Day 2\t3\t5')
console.log('Day 3\t3\t5')
console.log('Day 4\t3\t5')
Output in console:
Do you ?
Day 1 3 5
Day 2 3 5
Day 3 3 5
Day 4 3 5
To create a template strings, we use two back-ticks. We can inject data as expressions
inside a template string. To inject data, we enclose the expression with a curly
bracket({}) preceded by a $ sign. See the syntax below.
//Syntax
Example: 1
let a = 2
let b = 3
console.log(`The sum of ${a} and ${b} is ${a + b}`) // injecting the data
dynamically
Example:2
console.log(personInfoTwo)
console.log(personInfoThree)
let a = 2
let b = 3
String Methods
Everything in JavaScript is an object. A string is a primitive data type that means we can
not modify it once it is created. The string object has many string methods. There are
different string methods that can help us to work with strings.
1. length: The string length method returns the number of characters in a string
included empty space.
Example:
let js = 'JavaScript'
console.log(js.length) // 10
console.log(firstName.length) // 8
console.log(firstLetter) // J
console.log(lastLetter) // t
console.log(lastIndex) // 9
console.log(string[lastIndex]) // t
console.log(string.toUpperCase()) // JAVASCRIPT
console.log(firstName.toUpperCase()) // ASABENEH
console.log(string.toLowerCase()) // javascript
console.log(firstName.toLowerCase()) // asabeneh
console.log(country.toLowerCase()) // finland
5. substr(): It takes two arguments, the starting index and number of characters to
slice.
console.log(string.substr(4,6)) // Script
6. substring(): It takes two arguments, the starting index and the stopping index but
it doesn't include the character at the stopping index.
console.log(string.substring(0,4)) // Java
console.log(string.substring(4,10)) // Script
console.log(string.substring(4)) // Script
console.log(country.substring(3)) // land
console.log(string)
console.log(string.trim(' '))
console.log(firstName)
30 Days Of JavasCript
30 Days Of JavasCript
Asabeneh
Asabeneh
console.log(string.includes('Days')) // true
console.log(string.includes('Script')) // true
console.log(string.includes('script')) // false
console.log(string.includes('java')) // false
console.log(string.includes('Java')) // true
let country = 'Finland'
console.log(country.includes('fin')) // false
console.log(country.includes('Fin')) // true
console.log(country.includes('land')) // true
console.log(country.includes('Land')) // false
10. replace(): takes as a parameter the old substring and a new substring.
string.replace(oldsubstring, newsubstring)
11. charAt(): Takes index and it returns the value at that index
string.charAt(index)
console.log(string.charAt(0)) // 3
console.log(string.charAt(lastIndex)) // t
12. charCodeAt(): Takes index and it returns char code (ASCII number) of the value
at that index
string.charCodeAt(index)
13. indexOf(): Takes a substring and if the substring exists in a string it returns the
first position of the substring if does not exist it returns -1
string.indexOf(substring)
console.log(string.indexOf('D')) // 3
console.log(string.indexOf('Days')) // 3
console.log(string.indexOf('days')) // -1
console.log(string.indexOf('a')) // 4
console.log(string.indexOf('JavaScript')) // 11
console.log(string.indexOf('Script')) //15
console.log(string.indexOf('script')) // -1
14. lastIndexOf(): Takes a substring and if the substring exists in a string it returns
the last position of the substring if it does not exist it returns -1
//syntax
string.lastIndexOf(substring)
let string = 'I love JavaScript. If you do not love JavaScript what else can
you love.'
console.log(string.lastIndexOf('love')) // 67
console.log(string.lastIndexOf('you')) // 63
console.log(string.lastIndexOf('JavaScript')) // 38
console.log(country.concat("land")) // Finland
16. startsWith: it takes a substring as an argument and it checks if the string starts
with that specified substring. It returns a boolean(true or false).
//syntax
string.startsWith(substring)
console.log(string.startsWith('Love')) // true
console.log(string.startsWith('love')) // false
console.log(string.startsWith('world')) // false
console.log(country.startsWith('Fin')) // true
console.log(country.startsWith('fin')) // false
console.log(country.startsWith('land')) // false
17. endsWith: it takes a substring as an argument and it checks if the string ends
with that specified substring. It returns a boolean(true or false).
string.endsWith(substring)
console.log(string.endsWith('love')) // false
console.log(country.endsWith('land')) // true
console.log(country.endsWith('fin')) // false
console.log(country.endsWith('Fin')) // false
18. search: it takes a substring as an argument and it returns the index of the first
match. The search value can be a string or a regular expression pattern.
string.search(substring)
let string = 'I love JavaScript. If you do not love JavaScript what else can
you love.'
console.log(string.search('love')) // 2
console.log(string.search(/javascript/gi)) // 7
Match syntax
// syntax
string.match(substring)
let string = 'I love JavaScript. If you do not love JavaScript what else can
you love.'
console.log(string.match('love'))
["love", index: 2, input: "I love JavaScript. If you do not love JavaScript
what else can you love.", groups: undefined]
Let us extract numbers from text using a regular expression. This is not the regular
expression section, do not panic! We will cover regular expressions later on.
let txt = 'In 2019, I ran 30 Days of Python. Now, in 2020 I am super exited to
start this challenge'
console.log(txt.match(regEx)) // ["2", "0", "1", "9", "3", "0", "2", "0", "2",
"0"]
20. repeat(): it takes a number as argument and it returns the repeated version of the
string.
string.repeat(n)
console.log(string.repeat(10)) // lovelovelovelovelovelovelovelovelovelove
Example:
String to Int
We can convert string number to a number. Any number inside a quote is a string
number. An example of a string number: '10', '5', etc. We can convert string to number
using the following methods:
● parseInt()
● Number()
● Plus sign(+)
console.log(numInt) // 10
console.log(numInt) // 10
console.log(numInt) // 10
String to Float
We can convert string float number to a float number. Any float number inside a quote is
a string float number. An example of a string float number: '9.81', '3.14', '1.44', etc. We
can convert string float to number using the following methods:
● parseFloat()
● Number()
● Plus sign(+)
let num = '9.81'
console.log(numFloat) // 9.81
console.log(numFloat) // 9.81
console.log(numFloat) // 9.81
Float to Int
We can convert float numbers to integers. We use the following method to convert float
to int:
● parseInt()
console.log(numInt) // 9