Javascript Basics 101

Oh yeah, Here I am excited to take you on a journey of learning something new every day. I will be learning myself and you can follow along too. It all started by watching a Ted Talk by “Josh Kaufman” titled “The first 20 hours: How to learn anything” and this with other series will be completely based on learning that way. And I will include all the useful links for learning and all the code that I’ll write will be available to you on GitHub. And yes beginners who have a little or no programming language experience can follow along. This whole journey will be around 3 months covering: JavaScript, HTML & CSS, Git, Linux commands, Gulp.js, Angular JS, React JS, and Node JS.

So why waiting let’s start our first journey(There will be a lot of journeys😉people).

Let’s start with JavaScript

Today we will be covering the following topics: “Introduction to JavaScript”. So let’s start with an introduction to this amazing evolving scripting language “JavaScript”.

Console

The console is a panel that displays important messages, like errors, for developers. We will be frequently using the console to test our code by printing or logging to make things appear on it. To access our console we will use the “console” keyword which gives us access to it. We will utilize an action or method of our “console” object(for now just remember that objects are just like real-world things which have some states and behaviors.) called “log()” method. And we can access that using “.”(dot operator) as “console.log(message)” which will print or log the message we passed it in the parenthesis.

It will be very useful for us to print values to the console, so we can see the work that we’re doing.

console.log("Hello World!");
Note: We don’t need semicolon in JavaScript but it’s just a good way to write your code.

Comments

Comments are a great way to let readers of your code know how the code works. It’s also a refresher to you to see your code after of a lot of time. There are completely ignored while interpreting your code.

There are two types of comment in JavaScript:

  1. Single line comment will comment out a single line and is denoted by two forward slashes “//”.

//This is a single line comment

2. A multi-line comment will comment out multiple lines at the same time and is denoted by “/*” to begin and “*/” to end the comment.

/* This 
is 
a multi-line
comment
*/

Data types

In JavaScript there seven fundamental data types:

  1. Number: Any number, also including decimals.

  2. String: Any grouping of characters inside single (‘…’) or double quotes (“…”).

  3. Boolean: It has two possible values: true and false

  4. Null: Denotes intentional absence of a value

  5. Undefined: Denotes absence of a value, but a bit different then Null

  6. Symbol: New feature introduced in JavaScript, I’ll discuss this future. No need to worry now.

  7. Object: More on this later.

Arithmetic Operators

An operator is a character that performs a basic task. And arithmetic operators are the similar operators you have learned in mathematics to performs calculations on numbers. You can perform addition(+), subtraction(-), division(/), multiplication(*) and remainder(%).

console.log(6 + 6); //Outputs 12
console.log(6 * 6); //Outputs 36
console.log(6 / 6); //Outputs 1
console.log(6 - 6); //Outputs 0
console.log(6 % 5); // Outputs 1

String Concatenation

Some operators have multi behavior also depending on the data type they are used on. One such behavior is shown by the “+” operator while operating on the string data type. While it adds two or more numbers but in the case of Strings it appends them together and this appending is called concatenation.

console.log("Hello"); // Output: Hello
console.log("Hello" + " " + "World"); // Output: Hello World
//space is also considered a character and appended to other characters.

length property

Properties of objects allow us to perform more complex operations on the data and get useful information from it. One such property for string data types is “length” and is accessed also by “.”(dot operator) and it gives us the number of characters present in the string it’s applied on.

console.log("Hello World"); //Outputs 11 as space is also counted

Methods

These are actions that we can perform and there are a lot of built-in methods in JavaScript that we can use to see the magic of them. We can also create our own methods but more on that later, first we will utilize those built-in function and we will see some methods made for string type.

console.log("hello");//Output: hello
console.log("hello".toUpperCase()); //Output: HELLO
console.log("HELLO".toLowerCase()); // Output: hello
console.log("Hello".startsWith('H')); //Output: true

You can find more on these string methods here: JavaScript String Documentation


Variables

These are like containers somewhere in the memory that stores some type of information or value. They can also be considered as labels that describe our data more clearly to the reader and ourselves.

Now in JavaScript we have dynamic variables that are we don’t have to declare the data type by ourselves and the variable will define its data type by itself depending on the value given. But there are some keywords that we have to use to create our variables and they are “let”, “const” (these are introduced in the ES6 version of JavaScript), and “var”. As from the name, “const” declared variables are constant and cannot be changed once the value is assigned*. And the other two keywords can be changed again after initialization.

*There are some exceptions that I will show so chill up exceptions are everywhere.

One thing more there is some differences in the use of “var” and “let” and the major one is that “var” is defined in function scope and “let” is defined in block scope. I’ll not discuss them in detail because you will learn better by using them but still if you want to learn more then you check out this article here.

var varChocolate = 'cadbury';
let letChocolate = 'cadbury';
const constChocolate = 'cadbury';
console.log(varChocolate);
console.log(letChocolate);
console.log(constChocolate);constChocolate = "Nestle"; 
// This will give error because it's a constant

One Best use of variables is reducing redundant work. How by giving a name to value you can use that name everywhere in your code and when you want to change the value then you have to change that at only one place. Isn’t it amazing?

let a = 10;
let b = 10;
console.log(a + b);
console.log(a *b);
console.log(a / b);
console.log(a - b);
console.log(a + b + a);
console.log(a + b - a * b);a = 20;
b = 30;console.log(a + b);
console.log(a *b);
console.log(a / b);
console.log(a - b);
console.log(a + b + a);
console.log(a + b - a * b);// see you only have to change at just one place not everywhere.

String Interpolation

This is also on amazing use of variables and allows us to perform some you can say string formatting.

For achieving this task we need three things that is the power of variables,``(a pair of backticks are), and {}(curly braces). How?

const a = 10;
console.log(`Ten is written as: {a}`); 
// Output: Ten is written as: 10//We can also achieve this through concatenation but in complex //cases it will be quite tedious.

There is a “type of” operator that has a special behavior to give us the data type of variable it’s applied on.

const a = "Hello"
console.log(typeof a) // Output : string

Conditional Statements

Decisions are really an important part of our life and we have to decide our next move based on some conditions and if a wrong decision is taken then results can be disturbing. Similar to real-life we have conditional statements in JavaScript too, so let’s see them in action.

Using if..else if…else statements

if (condition1) {
  //condition is true then this code will run
}
else if (condition2){
   //This will run only if condition1 is false and condition2}
...
...
...
...//There can be any number of else if statements as you want//When condition turns out to be true the rest are not checked
else {// This will only run if all the above condition fails to be true.}

Now we will learn conditional statements by coding the following scenario: “Say two friends have one chocolate left and they don’t wanna share but they are good enough to have a fair chance to eat that chocolate so they decided to toss and whoever wins will eat the chocolate”. Let’s code this but before that remember these comparison operators use to determine results of certain conditions.

Comparison Operators

Here is a list of some handy comparison operators and their syntax:

  • Less than: <

  • Greater than: >

  • Less than or equal to <=

  • Greater than or equal to>=

  • Is equal to: ===

  • Is NOT equal to: !==

Comparison operators compare the value on the left with the value on the right.

Now here is the solution to the above scenario:

const friend1 = "Head";
const friend2 = "Tail";
const toss = "Head"; // or "Tail"if(friend1 === toss){   console.log("friend1 will eat")}
else if (friend2 === toss){
console.log("friend2 will eat");}else {
console.log("Two friends should share and if not then toss again.")}

But conditions are not that simple and you need to use additional logic to solve the more complex condition and thankfully we have a solution for this and that is the use of Logical Operators.

Logical Operators

Working with conditionals means that we will be using boolean, true or false values. In JavaScript, there are operators that work with boolean values known as logical operators. We can use logical operators to add more sophisticated logic to our conditionals. There are three logical operators:

  • the and operator (&&) [Will give true if both conditions are true]

  • the or operator (||) [Will give true if either one or both are true] [One special thing if the first operand is true then next operator is not checked and true will return]

  • the not operator, otherwise known as the bang operator (!) [make true to false and false to true]

Let’s code a complex scenario based on badminton as I love badminton very much: “Toss between two players and choosing court or server depending on the toss”. It will be beginner based okay so if it feels little bit a easy you can move ahead to other articles this series.

const friend1Toss = "Tail";
const friend2Toss = "Head";const friend1Choice = "Court";
const friend2Choice = "Serve";const toss = "Tail"; if(friend1Toss === toss && friend1Choice === "Court"){
console.log("Friend1 win chose Court");}
else if(friend1Toss === toss && friend1Choice === "Serve"){console.log("Friend1 win chose Serve");
}else if(friend2Toss === toss && friend2Choice === "Serve"){console.log("Friend2 win chose Serve");
}
else if(friend2Toss === toss && friend2Choice === "Serve"){console.log("Friend2 win chose Serve");
}
else {console.log("match cancelled or toss again");}//use of not operator
console.log(!true); // Output: false
console.log(!false); // Output: true

So you got the basic introduction to JavaScript and I hope you got the basic know-how of the language. I think that’s enough for today see you soon with something amazing.

38 views

© 2020 by My Hobbyverse