npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

javascript-for-everyone

v2.8.5

Published

javascript-for-everyone

Downloads

1

Readme

Author: Asabeneh Yetayeh January, 2018

Support the author to create more educational materials

JS

Introduction

JavaScript for Everyone is a guide for both beginners and advanced JavaScript developers. Welcome to JavaScript. Congratulations for deciding to learn JavaScript, the language of the browser.

In this step by step tutorial, you will learn JavaScript, the most popular programming language in the history of mankind. You use JavaScript to add interactivity to websites, to develop mobile apps, desktop applications, games and nowadays JavaScript can be used for machine learning and AI. JavaScript (JS) has increased in popularity in recent years and has been the leading programming language for four consecutive years and is the most used programming language on Github.

Setup

First thing first, lets install text or code editor. Install code editor, it could be vscode, atom, bracket, notepad++ or others. I recommend vscode. Install either Chrome or Firefox if you didn't have yet.

If you want help, you may join the telegram channel.

Requirements

No prior knowledge of programming is required to follow this guide. You need only:

  1. Motivation
  2. Computer
  3. Internet
  4. Browser
  5. Code Editor

Setup

I believe you have the motivation and a strong desire to be a developer, computer and Internet. If you have those, then you have everything.

Install Node.js

You may not need it right now but you may need it for later. Install node.js.

Node download

After downloading double click and install

Install node

We can check if node is installed in our local machine by opening our device terminal or command prompt.

asabeneh $ node -v
v12.14.0

I am using node version 12.14.0, which is the recommended version of node.

Browser

There are many browsers out there. However, I strongly recommend Google Chrome.

Installing 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.

Google Chrome

Opening Google Chrome Console

You can open Google Chrome either by clicking three dots at the top right corner of the Chrome browser or using a shortcut. I prefer using shortcuts.

Opening chrome

To open the Chrome console using a short cut.

Mac
Command+Option+I

Windows:
Ctl+Shift+I

Opening console

After you open the Google Chrome console, try to explore the marked buttons. We will spend most of the time on the Console part. 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:

write code on 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 builtin 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!");
Console.log with multiple arguments

The console.log(param1, param2, param3), can take multiple arguments.

console log multiple arguments

console.log("Hello", "World", "!");
console.log("HAPPY", "NEW", "YEAR", 2020);
console.log("Welcome", "to", 30, "Days", "Of", "JavaScript");

As you can see from the above snippet code, console.log() can take multiple arguments.

Congratulations! You wrote your first JavaScript code using console.log().

Comment

We 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. Any text starts with // in JavaScript is a comment or anything enclose like this /* */ is a comment.

Example: Single Line Comment

// This is the first comment
// This is the second comment
// I am a single line comment

Example: Multiline Comment

/_ This is a multiline comment
Multiline comments can take multiple lines
JavaScript is the language of the web
_/

Syntax

JavaScript is a programming language. As a result, it has its syntax like other programming languages. If we do not write a syntax that JavaScript understands, it will raise different types of errors. We will explore different kinds of JavaScript errors later. For now, let us see syntax errors.

Error

I made a deliberate mistake. As a result, the console raises a syntax error. Actually, the syntax is very informative. It informs what type of mistake we 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 a console.log(). If we are printing text or string using console.log(), the text has to be under the single, double, or 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.

Arithmetic

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); // Exponential

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 python JavaScript challenge, we will use visual studio code.

Installing 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.

Vscode

If you installed visual studio code, let us start using it.

How to use visual studio code

Open the visual studio code by double-clicking the visual studio icon. When you open it, you will get this kind of interface. Try to interact with the labeled icons.

Vscode ui

Vscode add project

Vscode open project

script file

running script

coding running

Adding JavaScript to a web page

JavaScript can be added to a web page in three ways:

  • Inline script
  • Internal script
  • External script

The following sections show different ways of adding JavaScript code to your web page.

Inline Script

Create a folder on your desktop or in any location and create an index.html file in your folder. Then paste the following code and open it in a browser, either in Chrome or Firefox.

<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript for Everyone</title>
  </head>
  <body>
    <button onclick="alert('Welcome to JavaScript!');">Click Me</button>
  </body>
</html>

Internal script

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.

  • Internal script at the head
<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript for Everyone</title>
    <script>
      console.log("Welcome to JavaScript for Everyone");
    </script>
  </head>
  <body></body>
</html>
  • Internal script at the body
<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript for Everyone</title>
  </head>
  <body>
    <script>
      console.log("Welcome to JavaScript for Everyone");
    </script>
  </body>
</html>

External script

The external script link can be on the head or body but it is preferred to put it in the body.

  • External script at the head
<!DOCTYPE html>
  <html>
    <head>
      <title>JavaScript for Everyone</title>
      <script src="introduction.js"></script>
    </head>
    <body>
    </body>
    </html
  • External script at the body
<!DOCTYPE html>
  <html>
    <head>
      <title>JavaScript for Everyone</title>
    </head>
    <body>
      //it could be in the header or in the body
      // Here is the recommended place to put the script
      <script src="introduction.js"></script>
    </body>
    </html

Exercises:Setting Up your machine

Variables

Variables are containers of data. Variables store data in a memory location. When a variable is declared a memory location is reserved and when it is assigned to a value, the memory space will be filled. To declare a variable we use, var, let or const key words. For a variable which changes at different time we use let but if the data doesn't change at all we use const. For example PI, country name, gravity.

  • A JavaScript variable name shouldn't begin with a number
  • A JavaScript variable name does not allow special characters except dollar sign and underscore.
  • A JavaScript variable name follow a camelCase convention.
  • A JavaScript variable name shouldn't have space between words. The following are valid examples of JavaScript variables.

Valid variables in JavaScript:

firstName;
lastName;
country;
city;
capitalCity;
age;
isMarried;

first_name;
last_name;
is_married;
capital_city;

num1;
num_1;
_num_1;
$num1;
year2019;
year_2019;

Camel case(camelCase) or the first way of declaring is conventional in JavaScript. In this material, camelCase variables will be used.

Invalid variable:

  first-name
  1_num
  num_#_1

Declaring variables

// Declaring different variables of different data types

let firstName = "Asabeneh"; // first name of a person
let lastName = "Yetayeh"; // last name of a person
let country = "Finland"; // country
let city = "Helsinki"; // capital city
let age = 100; // age in years
let isMarried = true;
console.log(firstName, lastName, country, city, age, isMarried); // Asabeneh, Yetayeh, Finland, Helsinki, 100, True

// Declaring variables with number values

const gravity = 9.81; // earth gravity  in m/s2
const boilingPoint = 100; // water boiling point, temperature in oC
const PI = 3.14; // geometrical constant
console.log(gravity, boilingPoint, PI); // 9.81, 100, 3.14

// Variables can also be declaring in one line separated by comma

let name = "Asabeneh", //name of a person
  job = "teacher",
  live = "Finland";
console.log(name, job, live);

Exercise - 1 : Variables

  1. Declare four variables without assigning values

  2. Declare four variables with assigning values

  3. Declare variables to store your first name, last name, marital status, country and age in multiple lines

  4. Declare variables to store your first name, last name, marital status, country and age in a single line

  5. Declare two variables myAge and yourAge and assign them initial values and log to browser console. Output:

    I am 25 years old.
    You are 30 years old.

Comments

Commenting in JavaScript is similar to other programming languages. Comments can help to make code more readable. There are two ways of commenting:

  • Single line commenting
  • Multiline commenting
// let firstName = 'Asabeneh'; single line comment
// let lastName = 'Yetayeh'; single line comment

Multiline commenting:

/*
    let location = 'Helsinki';
    let age = 100;
    let isMarried = true;
    This is a Multiple line comment
    */

Exercise: Comments

  1. Write a single line comment which says, comments can make code readable
  2. Write a multiline comment which says, comments can make code readable, easy to use and informative

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. Primitive data types
  2. Non-primitive data types(Object References)

Primitive Data Types

Primitive data types in JavaScript includes:

  1. Numbers - Integers, floats
  2. Strings - Any data under single or double quote
  3. Booleans - true or false value
  4. Null - empty value or no value
  5. Undefined - a declared variable without a value

Non-primitive data types in JavaScript includes:

  1. Objects
  2. Functions
  3. Arrays

Now, let us see what exactly mean primitive and non-primitive data types. Primitive data types are immutable(non-modifiable) data types. Once a primitive data type is created we can not modify it. Example:

let word = "JavaScript";

If we try to modify the string stored in variable word, JavaScript will raise an error. Any data type under a single quote, double-quote, or backtick 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 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;

console.log(numOne == numTwo); // true

let js = "JavaScript";
let py = "Python";

console.log(js == py); //false

let lightOn = true;
let lightOff = false;

console.log(lightOn == lightOff); // false

Non-Primitive Data Types

Non-primitive data types are modifiable or mutable. We can modify the value of non-primitive data types after it gets created. Let us see by creating an array. An array is a list of data values in a square bracket. Arrays can contain the same or different data types. Array values are referenced by their index. In JavaScript array index starts at zero. I.e., the first element of an array is found at index zero, the second element at index one, and the third element at index two, etc.

let nums = [1, 2, 3];
nums[0] = 10;

console.log(nums); // [10, 2, 3]

As you can see, an array in which a non-primitive data type is mutable. Non-primitive data types can not be compared by value. Even if two non-primitive data types have the same properties and values, they are not strictly equal.

let nums = [1, 2, 3];
let numbers = [1, 2, 3];

console.log(nums == numbers); // false

let userOne = {
  name: "Asabeneh",
  role: "teaching",
  country: "Finland",
};

let userTwo = {
  name: "Asabeneh",
  role: "teaching",
  country: "Finland",
};

console.log(userOne == userTwo); // false

Rule of thumb, we do not compare non-primitive data types. Do not compare array, function, or object. 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 nums = [1, 2, 3];
let numbers = nums;

console.log(nums == numbers); // true

let userOne = {
  name: "Asabeneh",
  role: "teaching",
  country: "Finland",
};

let userTwo = userOne;

console.log(userOne == userTwo); // true

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. Lets' see some examples of Numbers.

Declaring number data types

let age = 35;
const gravity = 9.81; //we use const for non-changing values, gravitational constant in  m/s2
let mass = 72; // mass in Kilogram
const PI = 3.14; // pi a geometrical constant

//More Examples
const boilingPoint = 100; // temperature in oC, boiling point of water which is a constant
const bodyTemp = 37; // oC average human body temperature, which is a constant

console.log(age, gravity, mass, PI, boilingPoint, bodyTemp);

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

// Rounding to the closest number
// if above .5 up if less 0.5 down rounding

console.log(Math.round(PI)); // 3 to round values to the nearest number

console.log(Math.round(9.81)); // 10

console.log(Math.floor(PI)); // 3 rounding down

console.log(Math.ceil(PI)); // 4 rounding up

console.log(Math.min(-5, 3, 20, 4, 5, 10)); // -5, returns the minimum value

console.log(Math.max(-5, 3, 20, 4, 5, 10)); // 20, returns the maximum value

const randNum = Math.random(); // creates random number between 0 to 0.999999
console.log(randNum);

// Let us  create random number between 0 to 10

const num = Math.floor(Math.random() * 11); // creates random number between 0 and 10
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
//Returns the natural logarithm of base E of x, Math.log(x)
console.log(Math.log(2)); // 0.6931471805599453
console.log(Math.log(10)); // 2.302585092994046

// Trigonometry
Math.sin(0);
Math.sin(60);

Math.cos(0);
Math.cos(60);

Random number generator

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 inclusive.

let randomNum = Math.random(); // generates 0 to 0.999
let numBtnZeroAndTen = randomNum * 11;

console.log(numBtnZeroAndTen); // this gives: min 0 and max 10.99

let randomNumRoundToFloor = Math.floor(numBtnZeroAndTen);
console.log(randomNumRoundToFloor); // this gives between 0 and 10

Strings

Strings are texts, which are under single or double quote. To declare a string, we need a variable name, assignment operator, a value under a single quote, double-quote, or backtick. Lets' see some examples of string:

let space = " "; // an empty space string
let firstName = "Asabeneh";
let lastName = "Yetayeh";
let country = "Finland";
let city = "Helsinki";
let language = "JavaScript";
let job = "teacher";

String Concatenation

Connect two or more strings together is called concatenation.

// Declaring different variables of different data types
let space = " ";
let firstName = "Asabeneh";
let lastName = "Yetayeh";
let country = "Finland";
let city = "Helsinki";
let language = "JavaScript";
let job = "teacher";
let fullName = firstName + space + lastName; // concatenation, merging two string together.
console.log(fullName);
Asabeneh Yetayeh

We can concatenate string in different ways.

Concatenating using addition operator

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 second way.

// Declaring different variables of different data types
let space = " ";
let firstName = "Asabeneh";
let lastName = "Yetayeh";
let country = "Finland";
let city = "Helsinki";
let language = "JavaScript";
let job = "teacher";
let age = 250;
let fullName = firstName + space + lastName;

let personInfoOne = fullName + ". I am " + age + ". I live in " + country; // ES5

console.log(personInfoOne);
Asabeneh Yetayeh. I am 250. I live in Finland

Long Literal Strings

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:

const paragraph =
  "My name is Asabeneh Yetayeh. I live in Finland, Helsinki.\
I am a teacher and I love teaching. I teach HTML, CSS, JavaScript, React, Redux, \
Node.js, Python, Data Analysis and D3.js for anyone who is interested to learn. \
In the end of 2019, I was thinking to expand my teaching and to reach \
to global audience and I started a Python challenge from November 20 - December 19.\
It was one of the most rewarding and inspiring experience.\
Now, we are in 2020. I am enjoying preparing the 30DaysOfJavaScript challenge and \
I hope you are enjoying too.";
console.log(paragraph);

Escape Sequences in string

In JavaScript and other programming language \ followed by some characters is an escape sequence. Let's see the most common escape characters:

  • \n: new line
  • \t: Tab means(8 spaces)
  • \\: Back slash
  • \': Single quote (')
  • \":Double quote (")
console.log(
  "I hope every one is enjoying the 30 Days Of JavaScript challenge.\nDo you ?"
); // line break
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");
console.log("This is a back slash  symbol (\\)"); // To write a back slash
console.log('In every programming language it starts with "Hello, World!"');
console.log("In every programming language it starts with 'Hello, World!'");
console.log("The saying 'Seeing is Believing' is't correct in 2020");

Template Literals(Template Strings)

To create a template string, we use two backticks. We can inject data as expression inside a template string. To inject data, we enclose the expression with a curly bracket({}) followed by a $ sign. See the syntax below.

//Syntax
`String literal text``String literal text ${expression}`;

Example: 1

console.log(`The sum of 2 and 3 is 5`); // statically writing the data
let a = 2;
let b = 3;
console.log(`The sum of ${a} and ${b} is ${a + b}`); // injecting the data dynamically

Example:2

let firstName = "Asabeneh";
let lastName = "Yetayeh";
let country = "Finland";
let city = "Helsinki";
let language = "JavaScript";
let job = "teacher";
let age = 250;
let fullName = firstName + " " + lastName;

let personInfoTwo = `I am ${fullName}. I am ${age}. I live in ${country}.`; //ES6 - String interpolation method
let personInfoThree = `I am ${fullName}. I live in ${city}, ${country}. I am a ${job}. I teach ${language}.`;
console.log(personInfoTwo);
console.log(personInfoThree);
I am Asabeneh Yetayeh. I am 250. I live in Finland.
I am Asabeneh Yetayeh. I live in Helsinki, Finland. I am a teacher. I teach JavaScript.

Using a string template or string interpolation method, we can add expression, which could be a value or some operations(comparison, arithmetic operations, ternary operation).

let a = 2;
let b = 3;
console.log(`${a} is greater than ${b}: ${a > b}`);
2 is greater than 3: false

String Methods

Everything in JavaScript is an object. A string is a primitive data type that means we can not modify 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
    let firstName = "Asabeneh";
    console.log(firstName.length); // 8
  2. Accessing characters in a string: We can access each character in a string using its index. In programming, counting starts from 0. The first index of the string is zero, and the last index is one minus the length of the string.

Accessing sting by index

Let us access different characters in 'JavaScript' string.

let string = "JavaScript";
let firstLetter = string[0];

console.log(firstLetter); // J

let secondLetter = string[1]; // a
let thirdLetter = string[2];
let lastLetter = string[9];

console.log(lastLetter); // t

let lastIndex = string.length - 1;

console.log(lastIndex); // 9
console.log(string[lastIndex]); // t
  1. toUpperCase(): this method changes the string to uppercase letters.
let string = "JavaScript";

console.log(string.toUpperCase()); // JAVASCRIPT

let firstName = "Asabeneh";

console.log(firstName.toUpperCase()); // ASABENEH

let country = "Finland";

console.log(country.toUpperCase()); // FINLAND
  1. toLowerCase(): this method changes the string to lowercase letters.
let string = "JavasCript";

console.log(string.toLowerCase()); // javascript

let firstName = "Asabeneh";

console.log(firstName.toLowerCase()); // asabeneh

let country = "Finland";

console.log(country.toLowerCase()); // finland
  1. substr(): It takes two arguments, the starting index and number of characters to slice.
let string = "JavaScript";
console.log(string.substr(4, 6)); // Script

let country = "Finland";
console.log(country.substr(3, 4)); // land
  1. substring(): It takes two arguments, the starting index and the stopping index but it doesn't include the stopping index.
let string = "JavaScript";

console.log(string.substring(0, 4)); // Java
console.log(string.substring(4, 10)); // Script
console.log(string.substring(4)); // Script

let country = "Finland";

console.log(country.substring(0, 3)); // Fin
console.log(country.substring(3, 7)); // land
console.log(country.substring(3)); // land
  1. split(): The split method splits a string at a specified place.
let string = "30 Days Of JavaScript";

console.log(string.split()); // ["30 Days Of JavaScript"]
console.log(string.split(" ")); // ["30", "Days", "Of", "JavaScript"]

let firstName = "Asabeneh";

console.log(firstName.split()); // ["Asabeneh"]
console.log(firstName.split("")); // ["A", "s", "a", "b", "e", "n", "e", "h"]

let countries = "Finland, Sweden, Norway, Denmark, and Iceland";

console.log(countries.split(",")); // ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"]
console.log(countries.split(", ")); //  ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"]
  1. trim(): Removes trailing space in the beginning or the end of a string.
let string = "   30 Days Of JavaScript   ";

console.log(string);
console.log(string.trim(" "));

let firstName = " Asabeneh ";

console.log(firstName);
console.log(firstName.trim());
   30 Days Of JavasCript
30 Days Of JavasCript
  Asabeneh
Asabeneh
  1. includes(): It takes a substring argument and it check if substring argument exists in the string. includes() returns a boolean. It checks if a substring exist in a string and it returns true if it exists and false if it doesn't exist.
let string = "30 Days Of JavaScript";

console.log(string.includes("Days")); // true
console.log(string.includes("days")); // false
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
  1. replace(): takes to parameter the old substring and new substring.
string.replace(oldsubstring, newsubstring);
let string = "30 Days Of JavaScript";
console.log(string.replace("JavaScript", "Python")); // 30 Days Of Python

let country = "Finland";
console.log(country.replace("Fin", "Noman")); // Nomanland
  1. charAt(): Takes index and it returns the value at that index
string.charAt(index);
let string = "30 Days Of JavaScript";
console.log(string.charAt(0)); // 3

let lastIndex = string.length - 1;
console.log(string.charAt(lastIndex)); // t
  1. charCodeAt(): Takes index and it returns char code(ASCII number) of the value at that index
string.charCodeAt(index);
let string = "30 Days Of JavaScript";
console.log(string.charCodeAt(3)); // D ASCII number is 51

let lastIndex = string.length - 1;
console.log(string.charCodeAt(lastIndex)); // t ASCII is 116
  1. 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);
let string = "30 Days Of JavaScript";

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
  1. 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
  1. concat(): it takes many substrings and creates concatenation.
string.concat(substring, substring, substring);
let string = "30";
console.log(string.concat("Days", "Of", "JavaScript")); // 30DaysOfJavaScript

let country = "Fin";
console.log(country.concat("land")); // Finland
  1. 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);
let string = "Love is the best to in this world";

console.log(string.startsWith("Love")); // true
console.log(string.startsWith("love")); // false
console.log(string.startsWith("world")); // false

let country = "Finland";

console.log(country.startsWith("Fin")); // true
console.log(country.startsWith("fin")); // false
console.log(country.startsWith("land")); //  false
  1. endsWith: 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).
string.endsWith(substring);
let string = "Love is the best to in this world";

console.log(string.endsWith("world")); // true
console.log(string.endsWith("love")); // false
console.log(string.endsWith("in this world")); // true

let country = "Finland";

console.log(country.endsWith("land")); // true
console.log(country.endsWith("fin")); // false
console.log(country.endsWith("Fin")); //  false
  1. search: it takes a substring as an argument and it returns the index of the first match.
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
  1. match: it takes a substring or regular expression pattern as an argument and it returns an array if there is match if not it returns null. Let us see how a regular expression pattern looks like. It starts with / sign and ends with / sign.
let string = "love";
let patternOne = /love/; // with out any flag
let patternTwo = /love/gi; // g-means to search in the whole text, i - case insensitive

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 pattern = /love/gi;
console.log(string.match(pattern)); // ["love", "love", "love"]

Let us extract numbers from text using regular expression. This is not regular expression section, no panic, we will cover regular expression in other section.

let txt =
  "In 2019, I run 30 Days of Python. Now, in 2020 I super exited to start this challenge";
let regEx = /\d+/;

// d with escape character means d not a normal d instead acts a digit
// + means one or more digit numbers,
// if there is g after that it means global, search everywhere.

console.log(txt.match(regEx)); // ["2", "0", "1", "9", "3", "0", "2", "0", "2", "0"]
console.log(txt.match(/\d+/g)); // ["2019", "30", "2020"]
  1. repeat(): it takes a number argument and it returned the repeated version of the string.
string.repeat(n);
let string = "love";
console.log(string.repeat(10)); // lovelovelovelovelovelovelovelovelovelove

Checking Data types and Casting

Checking data types

  • Check Data types: To check the data type of a certain data type we use the typeof and we also change one data type to another. Example:
// Different javascript data types
// Let's declare different data types

let firstName = "Asabeneh"; // string
let lastName = "Yetayeh"; // string
let country = "Finland"; // string
let city = "Helsinki"; // string
let age = 250; // number, it is not my real age, do not worry about it
let job; // undefined, because a value was not assigned

console.log(typeof "Asabeneh"); // string
console.log(typeof firstName); // string
console.log(typeof 10); // number
console.log(typeof 3.14); // number
console.log(typeof true); // boolean
console.log(typeof false); // boolean
console.log(typeof NaN); // number
console.log(typeof job); // undefined
console.log(typeof undefined); // undefined
console.log(typeof null); // object

Changing data type(Casting)

  • Casting: Converting one data type to another data type. We use parseInt(), parseFloat(), Number(), + sign, str() When we do arithmetic operations string numbers should be first converted to integer or float if not it returns an error.

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(+)
let num = "10";
let numInt = parseInt(num);
console.log(numInt); // 10
let num = "10";
let numInt = Number(num);

console.log(numInt); // 10
let num = "10";
let numInt = +num;

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";
let numFloat = parseFloat(num);

console.log(numFloat); // 9.81
let num = "9.81";
let numFloat = Number(num);

console.log(numFloat); // 9.81
let num = "9.81";
let numFloat = +num;

console.log(numInt); // 9.81

Float to Int

We can convert float numbers to integers. We use the following method to convert float to int:

  • parseInt()
let num = 9.81;
let numInt = parseInt(num);

console.log(numInt); // 9

Exercises: Data Types

  1. Declare variables and assign string, boolean, undefined and null data types
  2. The JavaScript typeof operator uses to check different data types. Check the data type of each variables from question number 1.

Exercise: String

  1. Declare a variable name company and assign it to an initial value 'Coding Academy'.
  2. Print the string on the browser console using console.log()
  3. Print the length of the string on the browser console using console.log()
  4. Change all the string to capital letters using toUpperCase() method
  5. Change all the string to lowercase letters using toLowerCase() method
  6. Cut(slice) out the first word of the string using slice, substr() or substring() method
  7. Use substr to slice out the phase because because because in the following sentence:'You cannot end a sentence with because because because is a conjunction'
  8. Check if the string contains a word Academy using includes() method
  9. Split the string into array using split() method
  10. Split the string Coding Academy at the space using split() method
  11. 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' split the string at the comma and change it to an array.
  12. Change Coding Academy to Microsoft Academy using replace() method.
  13. What is character at index 10 in 'Coding Academy' string use charAt() method.
  14. What is the character code of A in 'Coding Academy' string using charCodeAt()
  15. Use indexOf to determine the position of the first occurrence of c in Coding Academy
  16. Use lastIndexOf to determine the position of the last occurrence of c in Coding Academy.
  17. Use indexOf to find the position of the first occurrence of the word because in the following sentence:'You cannot end a sentence with because because because is a conjunction'
  18. Use lastIndexOf to find the position of the first occurrence of the word because in the following sentence:'You cannot end a sentence with because because because is a conjunction'
  19. Use search to find the position of the first occurrence of the word because in the following sentence:'You cannot end a sentence with because because because is a conjunction'
  20. Use trim() to remove if there is trailing whitespace at the beginning and the end of a string.E.g ' Coding Academy '.
  21. Use startsWith() method with the string Coding Academy make the result true
  22. Use endsWith() method with the string Coding Academy make the result true
  23. Use match() method to find all the c’s in Coding Academy
  24. Use match() to count the number all because's in the following sentence:'You cannot end a sentence with because because because is a conjunction'
  25. Use concat() and merge 'Coding' and 'Academy' to a single string, 'Coding Academy'
  26. Use repeat() method to print Coding Academy 5 times
  27. Calculate the total annual income of the person by extract the numbers from the following text. 'He earns 5000 euro from salary per month, 10000 euro annual bonus, 15000 euro online courses per month.'

Booleans

Boolean value is either true or false. Any comparisons return a boolean value which is either true or false.

let isLightOn = true;
let isRaining = false;
let hungry = false;
let isMarried = true;

Exercise: Booleans

Boolean value is either true or false.

  1. Write three JavaScript statement which provide truthy value.
  2. Write three JavaScript statement which provide falsy value.
  3. Use all the following comparison operators to compare the following values: >, < >=, <=, !=, !==,===. Which are true or which are false ?
    1. 4 > 3
    2. 4 >= 3
    3. 4 < 3
    4. 4 <= 3
    5. 4 == 4
    6. 4 === 4
    7. 4 != 4
    8. 4 !== 4
    9. 4 != '4'
    10. 4 == '4'
    11. 4 === '4'

Undefined

let firstName;
console.log(firstName); //not defined, because it is not assigned to a value yet

Null

let empty = null;
console.log(empty); // -> null , means no value

Exercise - 6 : Data types

String, number, boolean, null, undefined and symbol(ES6) are JavaScript primitive data types.

  1. The JavaScript typeof operator uses to check different data types. Check the data type of each variables from question number 1.

Operators

Arithmetic Operators

Arithmetic operators are mathematical operators:+, -, _, /, _

let numOne = 4;
let numTwo = 3;
let sum = numOne + numTwo;
let diff = numOne - numTwo;
let mult = numOne * numTwo;
let div = numOne / numTwo;
let remainder = numOne % numTwo;

console.log(sum, diff, mult, div, remainder); // ->7,1,12,1.33,1

let PI = 3.14;
let radius = 100; // length in meter

const gravity = 9.81; // in m/s2
let mass = 72; // in Kilogram
const boilingPoint = 100; // temperature in oC, boiling point of water
const bodyTemp = 37; // body temperature in oC

// Lets calculate area of a circle

const areaOfCircle = PI * radius * radius;
console.log(areaOfCircle); // -> 314 m

// Lets calculate weight of a substance
const weight = mass * gravity;
console.log(weight); // -> 706.32 N(Newton)

// ConcatEnating string with numbers using string interpolation
/*
 The boiling point of water is 100 oC.
 Human body temperature is 37 oC.
 The gravity of earth is 9.81 m/s2.
 */
console.log(
  `The boiling point of water is ${boilingPoint} oC.\nHuman body temperature is ${body} oC.\nThe gravity of earth is ${gravity} m / s2.`
);

Exercises : Arithmetic Operators

JavaScript arithmetic operators are addition(+), subtraction(-), multiplication(*), division(/), modulus(%), increment(++) and decrement(--).

let operandOne = 4;
let operandTwo = 3;

Using the above operands apply different JavaScript arithmetic operators

Logical Operators

The following symbols are the common logical operators: &&(ampersand) , ||(pipe) and !(negation). && gets true only if the two operands are true. || gets true either of the operand is true. ! negates true to false, false to true.

// && ampersand example

const check = 4 > 3 && 10 > 5; // true and true -> true
const check = 4 > 3 && 10 < 5; // true and false -> false
const check = 4 < 3 && 10 < 5; // false and false -> false

// || pipe or, example

const check = 4 > 3 || 10 > 5; // true and true -> true
const check = 4 > 3 || 10 < 5; // true and false -> true
const check = 4 < 3 || 10 < 5; // false and false -> false

// ! Negation examples

let check = 4 > 3; // -> true
let check = !(4 > 3); // -> false
let isLightOn = true; // -> true
let isLightOff = !isLightOn; // -> false
let isMarried = !false; // -> true

Exercises: Logical Operators

Which are true or which are false ?

  1. 4 > 3 && 10 < 12
  2. 4 > 3 && 10 > 12
  3. 4 > 3 || 10 < 12
  4. 4 > 3 || 10 > 12
  5. !(4 > 3)
  6. !(4 < 3)
  7. !(false)
  8. !(4 > 3 && 10 < 12)
  9. !(4 > 3 && 10 > 12)
  10. !(4 === '4')

Comparison Operators

4 > 3;
4 >= 4;
4 < 3;
4 <= 3;
4 != 3;
4 !== "4";
4 == "4";
4 === "4";
4 === 4;

Exercise: Comparison Operators

Boolean value is either true or false. Any comparison return a boolean either true or false. Use all the following comparison operators to compare the following values: >, < >=, <=, !=, !==,===. Which are true or which are false ?

  1. 4 > 3
  2. 4 >= 3
  3. 4 < 3
  4. 4 <= 3
  5. 4 == 4
  6. 4 === 4
  7. 4 != 4
  8. 4 !== 4
  9. 4 != '4'
  10. 4 == '4'
  11. 4 === '4'

Conditionals

if

We use if condition to check only on condition.

if (condition) {
  // code goes here
}

let isRaining = true;
if (isRaining) {
  console.log("Remember to take your rain coat.");
}

if else

When we have more than one condition we use the if and else condition.

if (condition) {
  // if the condition meets, this block of code runs
} else {
  // if condition doesn't meet, this block code runs
}

let isRaining = true;
if (isRaining) {
  console.log("You need a rain coat.");
} else {
  console.log("No need for a rain coat.");
}

if else if else

Whenever we have multiple conditions.

// if else if else
let weather = "sunny";
if (weather === "rainy") {
  console.log("You need a rain coat.");
} else if (weather === "cloudy") {
  console.log("It might be cold, you need a jacket.");
} else if (weather === "sunny") {
  console.log("Go out freely.");
} else {
  console.log("No need for rain coat.");
}

switch

Switch an alternative for if else if else

var weather = "cloudy";
switch (weather) {
  case "rainy":
    console.log("You need a rain coat.");
    break;
  case "cloudy":
    console.log("It might be cold, you need a jacket.");
    break;
  case "sunny":
    console.log("Go out freely.");
    break;
  default:
    console.log(" No need for rain coat.");
    break;
}
// Switch More Examples
var dayUserInput = prompt("What day is it ?");
var day = dayUserInput.toLowerCase();
switch (day) {
  case "monday":
    console.log("Today is Monday");
    break;
  case "tuesday":
    console.log("Today is Tuesday");
    break;
  case "wednesday":
    console.log("Today is Wednesday");
    break;
  case "thursday":
    console.log("Today is Thursday");
    break;
  case "friday":
    console.log("Today is Friday");
    break;
  case "saturday":
    console.log("Today is Saturday");
    break;
  case "sunday":
    console.log("Today is Sunday");
    break;

  default:
    console.log("It is not a week day.");
    break;
}

Ternary Operators

Another way to write conditionals is using ternary operators.

let isRaining = true;
isRaining
  ? console.log("You need a rain coat.")
  : console.log("No need for a rain coat.");

Exercise: Conditionals

  1. Get user input using prompt(“Enter your age:”). If user is 18 or older , give feedback:You are old enough to drive but if not 18 give feedback to wait for the years he supposed to wait for. Output:

    Enter your age: 30
    You are old enough to drive.

    Output:

    Enter your age:15
    You are left with 3 years to drive.
  2. Compare the values of myAge and yourAge using if … else. Based on the comparison log to console who is older (me or you). Use prompt(“Enter your age:”) to get the age as input. Output:

    Enter your age: 30
    You are 5 years older than me.
  3. If a is greater than b return a is greater than b else a is less than b. Output:

     let a = 4
     let b = 3
     4 is greater than 3
  4. Write a code which give grade students according to theirs scores:

    • 80-100, A
    • 70-89, B
    • 60-69, C
    • 50-59, D
    • 0 -49, F
  5. Check if the season is Autumn, Winter, Spring or Summer. If the user input is:

    • September, October or November, the season is Autumn.
    • December, January or February, the season is Winter.
    • March, April or May, the season is Spring
    • June, July or August, the season is Summer

Loops

In programming languages to carry out repetitive task we use different kinds of loop. The following examples are the commonly used loops.

For Loop

// for loop structure
for(initialization, condition, increment/decrement){
  // code goes here
}
for(let i = 0; i <= 5; i++){
  console.log(i)
}

While loop

let i = 0;
while (i <= 5) {
  console.log(i);
  i++;
}

Do while loop

let i = 0;
do {
  console.log(i);
  i++;
} while (i <= 5);

Exercises:Loops

  1. Iterate 0 to 10 using for loop, do the same using while and do while loop.

  2. Iterate 10 to 0 using for loop, do the same using while and do while loop.

  3. Write a loop that makes seven calls to console.log to output the following triangle:

        #
        ##
        ###
        ####
        #####
        ######
        #######
  4. Iterate the array, ['HTML', 'CSS', 'JavaScript'] using a for loop and print out the items.

  5. Use for loop to iterate from 0 to 100 and print only even numbers

  6. Use for loop to iterate from 0 to 100 and print only odd numbers

  7. Use for loop to iterate from 0 to 100 and print and print the sum of all numbers.

    The sum all numbers is 5050.
  8. Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds.

    The sum of all evens is 2550. And the sum of all odds is 2500.

Arrays

In contrast to variables array can store multiple values. Each value in an array has an index and each index has a reference in a memory address. Each value can be accessed by using their indexes. The index of an array starts from zero and the last element is less by one from the length of the array.

const numbers = [0, 3.14, 9.81, 37, 98.6, 100]; // set of numbers

console.log(numbers.length) // => to know the size of the array, which is 6
console.log(numbers)        // -> [0, 3.14, 9.81, 37, 98.6, 100]
console.log(numbers[0])     //  -> 0
console.log(numbers[5])     //  -> 100

let lastIndex = numbers.length - 1;
console.log(numbers[lastIndex]) -> 100
const webTechs = [
  'HTML',
  'CSS',
  'JavaScript',
  'React',
  'Redux',
  'Node',
  'MongoDB'
]; // List of web technologies

console.log(webTechs)        // all the array items
console.log(webTechs.length) // => to know the size of the array, which is 7
console.log(webTechs[0])     //  -> HTML
console.log(webTechs[6])     //  -> MongoDB

let lastIndex = webTechs.length - 1;
console.log(webTechs[lastIndex]) -> MongoDB
const countries = [
  'Albania',
  'Bolivia',
  'Canada',
  'Denmark',
  'Ethiopia',
  'Finland',
  'Germany',
  'Hungary',
  'Ireland',
  'Japan',
  'Kenya'
]; // List of countries;

console.log(countries)     // -> all countries in array
console.log(countries[0])  //  -> Albania
console.log(countries[10]) //  -> Kenya

let lastIndex = countries.length - 1;
console.log(countries[lastIndex]) -> // Kenya

const shoppingCart = [
  'Milk',
  'Mango',
  'Tomato',
  'Potato',
  'Avocado',
  'Meat',
  'Eggs',
  'Sugar'
]; // List of food products

console.log(shoppingCart)     // -> all shoppingCart in array
console.log(shoppingCart[0])  //  -> Milk
console.log(shoppingCart[7])  //  -> Sugar

let lastIndex = shoppingCart.length - 1;
console.log(shoppingCart[lastIndex]) -> // Sugar

Exercise : Arrays

  1. Declare an empty array;
  2. Declare an array with more than 5 number of items
  3. Find the length of your array
  4. Get the first item, the middle item and the last item of the array
  5. Declare an array called mixedDataTypes,put different data types and in your array and the array size should be greater than 5
  6. Declare an array variable name itCompanies and assign initial values Facebook, Google, Microsoft, Apple, IBM, Oracle and Amazon.
  7. Print the array using console.log()
  8. Print the number of companies in the array
  9. Print the first company, middle and last company
  10. Print out each company
  11. Change companies to uppercase and print them out
  12. Print the array like as a sentence: Facebook, Google, Microsoft, Apple, IBM,Oracle and Amazon are big IT companies.
  13. Check if a certain company exists in the itCompanies array. If it exist return the company else return a company is not found.
  14. Filter out companies which have more than one 'o' without the filter method
  15. Sort the array using sort() method
  16. Reverse the array without reverse method
  17. Reverse the array using reverse() method
  18. Slice out the first 3 companies from the array
  19. Slice out the last 3 companies from the array
  20. Slice out the middle IT company or companies from the array
  21. Remove the first IT company from the array
  22. Remove the middle IT company or companies from the array
  23. Remove the last IT company from the array
  24. Remove all IT companies

More on Arrays

There are different methods to manipulate an array. These are some of the available methods to deal with arrays:Array,length, concat, indexOf, slice, splice, join, toString, includes, lastIndexOf, isArray, fill, push, pop, shift, unshift Array:To create an array.

const arr = Array(); // creates an an empty array
console.log(arr);

const eightEmptyValues = Array(8); // it creates eight empty values
console.log(eightEmptyValues); // [empty x 8]
  • fill: Fill all the array elements with a static value
const arr = Array(); // creates an an empty array
console.log(arr);
const eightXvalues = Array(8).fill("X"); // it creates eight element values
console.log(eightXvalues); // ['X', 'X','X','X','X','X','X','X']
  • concat: To concaten