Episode-1 : JavaScript Fundamentals

(Values, Data Types, Operators,& Some JavaScript Fundamentals)

Episode-1 : JavaScript Fundamentals

Welcome to "Episode -1 : JavaScript Fundamentals" There is no prerequisite for this blog series, just start with episode-1, I am writing all these episode after reading Eloquent Javacript and learning all stuffs related to JavaScript from internet.

Believe me , after reading all these episodes ,you will not be a beginner anymore , I will try to explain all the concepts in a simplest way.

Before starting this Series.

You can run all the code mentioned here in browser. By just right clicking in the browser and selecting inspect and then go into console section.

Just write the code in the console and press enter to run the code.console.log() is an easy way to give the output in JavaScript. Don't worry about this console.log(). Just see it as a method for giving the output.

Values

These are just the smallest unit of information(data) . We store these values inside a box which we called variable .So , we do not need to create values again and again .Whenever we need or want to use that value, we just call the variable in which that value is stored.

image007.jpg

Variables

Variables are like boxes which van store values. So it is a named memory location in a computer that hold a value which can be used later in the program.

Here , 15 is a value stored in variable eggs and 10 is a value stored in variable bacon.

In JavaScript or any other programming language we need some special words to declare a variable or to tell the computer that this is a variable.

We can declare variables in three ways :-

let bacon; const eggs; var name;

This is called variable declaration. When we put value inside the variable then it is called initialization. Like:- bacon=10; eggs=15; name="himanshu";

We can also declare and initialize variable in one line.

let bacon=10; const eggs=15; var name="himanshu";

We will se the difference among let , const and var later in the series ,for now just understand it as we declare variable using let and var when we supposed to change the value stored in the variable later in our code and declare the variable using const when we know that the value is fixed or constant or say the value will not change later in the the code.

Rules to declare a variable

  • A variable name can have letters, numbers, a dollar sign ($), and an underscore (_), but cannot begin with a number.
  • There are some reserved words in JavaScript known as Keywords. We can not use these keywords to name the variable. Some keywords are if for switch etc.

Data Types

You may have noticed that we are storing different type of values in variables. So, values can have different data types.

please note that data type is of a value but not of a variable , it will make much sense later in your learning

Types of Data Types :-

Number : These can be integers, whole numbers, natural numbers and decimal numbers.

const Pi = 3.14; // 3.14 is of data type Number.

String : Anything inside the quotes (" ") are considered as string .So , we can say string is just a sequence of characters. Quotes can be single quotes(' ') or double quotes(" ") or backticks(` `).

let name="coders"; // "coders" is of data type String.

Boolean : When we have possibilities like yes or no ,then the value is of type Boolean and it has only two values true or false.

let isEligible = true; // true is of data type Boolean.

Undefined : This is both a value and a data type. This is the value taken by a variable which is not initialized or not defined.

let age; // variable is declared but value is not assigned.
// So, if you try to use this age variable the value returned by it will be undefined.
console.log(age) // output will be undefined.
console.log(typeof age) // output will be undefined.
// this typeof is giving the data type of the value stored in variable age.

All of these data types are primitive data type . The Data types which are derived from these data type are known as non-primitive or referenced data types.

JavaScript has dynamic typing. We do not have to manually define the data type of a value stored in a variable. Instead data types are determined automatically.

Operators

Operators are symbols which can transform values and can combine values to produce new values.

There are different kind of operators :-

Arithmetic :

  • addition : 2+3 // here + operator combine 2 and 3 to produce 5.
  • subtraction : 5-3 // here - operator combine 5 and 3 to produce 2.
  • multiplication : 25 // here operator combine 5 and 2 to produce 10.
  • division : 10/2 // here / operator combine 10 and 2 to produce 5.
  • modulo : 5%2 // here % operator combine 5 and 2 to produce 1. It gives remainder.

Assignment : We have already seen this operator . Do you know where ? Well when we initialized a variable like : let bacon = 10; // this = operator is assignment operator. We assigned the value to a variable and it is evaluated from right to left . It is obvious. right ?

We have some more assignments operators. for example :-

let number = 1;
number +=1; // this is equal to number = number +1;
let mangoes =5;
mangoes -= 1; // this is equal to mangoes = mangoes-1;
let product = 2;
product *=3 // this is equal to product = product*3;

Comparison : These are the operators which produce Boolean values (true or false).

These are : >, < , >= , <= , == ,=== ,!= , !==

let isGreater = 6 > 2; // true will be assigned to isGreater.
let isEligible = 12 > 18; // false will be assigned to isEligible.

Logical : These are the operators applied on Boolean values. Or say on the values returned after evaluating comparison operators.

There are three logical operators :-

  • And(&&) : It returns to true only if both the values given to it are true.
let x = true && true; //x=true
let y = true && false; // y =false
let z = false && false; // z=false
let w= false && true; //w=false
let isEligible = 22 > 18 && true; // isEligible = true

What if there are more operators together. Like:-

2+3*100;

what does the above example mean ? "add 2 and 3 and then multiply the result with 100" or "multiply 3 and 100 and then add the result with 2" ? May be you know the answer . multiplication will happen first. But if we want to have addition first then we need to change this as : (2+3)*100;

So, when operators appears together without parentheses ,the order in which they applied are determined by the precedence of the operators.

As * comes before + in the precedence table. hence, it is evaluated first. We should not worry about rule of precedence. Whenever you are in doubt just add parentheses.

Unary and Binary Operators

Till now we have seen that operator applies on two values(operands). But there are some operators which can be applied only on a single value.

for example :- let number = -6;//- is applied on one value only console.log(typeof number);//typeof is also a operator which is applied on one value

so, the operators which are applied on a single value is known as unary operator. And therefore typeof is an unary operator.

And the operators which are applied on two values are known as binary operators.

Comment

It is a way by which we can deliver or write message about our code . The code or the text followed by // is not get executed or ignored when the program runs.

There are two type of comments

Single Line Comment

// this is the comment . It is ignored when the program runs.

Multiple Line Comment

/*
Here you can write multiple line comment.
As much as lines you want , you can write here.
*/

Type Conversion and Type Coercion

Type Coercion

When JavaScript automatically convert type of value into another type ,then it is called type coercion. Basically it happens when an operation is dealing with two values of different type.

2 + "3" // output : "23"
//JavaScript converts 2 into String as "2" 
//then "2" concatenated with "3" to produce "23"

But if we calculate "3" - "2";,JavaScript converts the "3" and "2" into values of type Number and then produce 1 which is of type Number.

So, according to operations JavaScript changes the type of one value into the type of another value.

Type Conversion

But we can also manually convert one type to another. for example :- Number("5");//"5"(String) will be converted to 5(Number).

Similarly we can convert Number into String : String(5);//5(Number) will be converted to "5"(String).

Truthy and Falsy Values

Falsy values are those which are actually not false but evaluated to false when we tries to convert it into Boolean.

Five values are falsy values : 0 , " " , undefined , null , NaN . Everything else are truthy values.

You don't know null and Nan . Right? Well, null can be treated as undefined for now, I will explain the difference between them later in this blog series.

NaN : Whenever an operation that invloves number to produce a new number fails , it gives NaN.

"five"*2;// Nan 10/0 ;// Infinity Infinity-Infinity; //Nan

In Operators, we have comparison operators ...

And in that there were two operators == and === , These are equality operators.

  • == -> This a loose equality operator . What I mean by loose ? Lets understand this with an example .

2 == "2" ;// true It performs type coercion . So, it converts "2" into 2 and then checks whether 2 is equal to 2 or not.

  • === -> This is a strict equality operator . You might have guessed its working . Lets see whether your guess is right or not . 2 === "2";// false .It does'nt perform type coercion .So , It checks for "2"and 2 and gives true or we can say it also checks the type of values.

Short-Circuiting of Logical Operators

The logical operators && and || also used for short - circuiting . First see this :-

0 || "hi";// output : "hi"
false || "hi"; //output : "hi"
"hello" || "hi";//output : "hello"
true || "hi";// output : true
"hello" && "hi" ; // output : "hi"
true && "hi"; // output : "hi"
false && "hello"; //output : false
0 && "hi"; //output : 0

I know you may be wondering that how these outputs are coming . It is simple to understand this.

They will convert the values on their left hand side to Boolean values , according to falsy and truthy value concept . for example :- 0 will be converted to false and "hello" is converted to true.

Now if the operator is && , it gives the value of its right hand side, if the left hand side value is evaluated to true. Otherwise it gives left hand value.

And if the operator is || , it gives the value of its right hand side, if the left hand side value is evaluated to false. Otherwise it gives left hand value.

Little more about String

As we know we can write strings(sequence of characters) in three ways single quotes console.log('Hello') , double quotes console.log("Hello") and backticks (template literals) .

console.log('single quote');
console.log("double quote");
console.log(`backticks`);
// backtick quoted strings are also called template literals.

When we want to compute some value inside strings or if we want to read value of any variable inside string then we use template literals.

let name = "Himanshu";
let birthYear = 2000;
console.log(`My name is ${name} and I am ${2021 - birthYear} years old`;
// My name is Himanshu and I am 21 years old.

So, using backticks we can consume value of a variable inside string as ${name} and also can compute values after consuming the variable as ${2021 - birthYear}

Escape Character

What if we want to have double quote or single quote in our output.

Then we have a very simple way for it . If we want to have double quote in output , use string quoted in single quotes and then double quotes inside the string can be appear in output and vice-versa.

console.log('I am learning "JavaScript" ');
// Output : I am learning "JavaScript"

console.log("I am learning 'JavaScript' ");
// Output : I am learning 'JavaScript'

But we have a one more method and that is escape character(). This backslash inside the string tells that the character after it has some special meaning . This is called escaping the character.

The quote that is preceded by a backslash will not end a string but be a part of it.

console.log("I am learning \"JavaScript\"");
// Output : I am learning "JavaScript"

Recap

We have covered basics of JavaScript in this episode. You should now have a better understanding of values, variables , data types ,operators and fundamentals. Now you are ready to move on to next episode where you will learn about program structure and how to build programs. See you in next episode.